blob: 2701c3e6c9a4769ec337fc86c5b14182c8164ecd [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);
366 property_get("debug.sf.disableBlurs", value, "0");
367 bool disableBlurs = atoi(value);
368 mEnableBlurs = supportsBlurs && !disableBlurs;
369 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
370 disableBlurs);
371
Yiwei Zhang243b3782018-05-15 17:40:04 -0700372 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Dan Stozaec460082018-12-17 15:35:09 -0800376 property_get("debug.sf.luma_sampling", value, "1");
377 mLumaSampling = atoi(value);
378
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800379 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800380 mDisableClientCompositionCache = atoi(value);
381
Romain Guy11d63f42017-07-20 12:47:14 -0700382 // We should be reading 'persist.sys.sf.color_saturation' here
383 // but since /data may be encrypted, we need to wait until after vold
384 // comes online to attempt to read the property. The property is
385 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800386
387 if (useTrebleTestingOverride()) {
388 // Without the override SurfaceFlinger cannot connect to HIDL
389 // services that are not listed in the manifests. Considered
390 // deriving the setting from the set service name, but it
391 // would be brittle if the name that's not 'default' is used
392 // for production purposes later on.
393 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
394 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800395
396 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397}
398
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399void SurfaceFlinger::onFirstRef()
400{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800401 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402}
403
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700404SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405
Dan Stozac7014012014-02-14 15:03:43 -0800406void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407{
408 // the window manager died on us. prepare its eulogy.
409
Andy McFadden13a082e2012-08-24 10:16:42 -0700410 // restore initial conditions (default device unblank, etc)
411 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412
413 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700414 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415}
416
Robert Carr1db73f62016-12-21 12:58:51 -0800417static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700418 status_t err = client->initCheck();
419 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800420 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421 }
Robert Carr1db73f62016-12-21 12:58:51 -0800422 return nullptr;
423}
424
425sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
426 return initClient(new Client(this));
427}
428
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700429sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
430 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700431{
432 class DisplayToken : public BBinder {
433 sp<SurfaceFlinger> flinger;
434 virtual ~DisplayToken() {
435 // no more references, this display must be terminated
436 Mutex::Autolock _l(flinger->mStateLock);
437 flinger->mCurrentState.displays.removeItem(this);
438 flinger->setTransactionFlags(eDisplayTransactionNeeded);
439 }
440 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700441 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 : flinger(flinger) {
443 }
444 };
445
446 sp<BBinder> token = new DisplayToken(this);
447
448 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700449 // Display ID is assigned when virtual display is allocated by HWC.
450 DisplayDeviceState state;
451 state.isSecure = secure;
452 state.displayName = displayName;
453 mCurrentState.displays.add(token, state);
454 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455 return token;
456}
457
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700458void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700459 Mutex::Autolock _l(mStateLock);
460
Dominik Laskowski075d3172018-05-24 15:50:06 -0700461 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
462 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700463 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700464 return;
465 }
466
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
468 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 ALOGE("destroyDisplay called for non-virtual display");
470 return;
471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 mInterceptor->saveDisplayDeletion(state.sequenceId);
473 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 setTransactionFlags(eDisplayTransactionNeeded);
475}
476
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800477std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
478 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800480 const auto internalDisplayId = getInternalDisplayIdLocked();
481 if (!internalDisplayId) {
482 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483 }
484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485 std::vector<PhysicalDisplayId> displayIds;
486 displayIds.reserve(mPhysicalDisplayTokens.size());
487 displayIds.push_back(internalDisplayId->value);
488
489 for (const auto& [id, token] : mPhysicalDisplayTokens) {
490 if (id != *internalDisplayId) {
491 displayIds.push_back(id.value);
492 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495 return displayIds;
496}
497
498sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
499 Mutex::Autolock lock(mStateLock);
500 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501}
502
Ady Abraham37965d42018-11-01 13:43:32 -0700503status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
504 if (!outGetColorManagement) {
505 return BAD_VALUE;
506 }
507 *outGetColorManagement = useColorManagement;
508 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700509}
510
Lloyd Pique441d5042018-10-18 16:49:51 -0700511HWComposer& SurfaceFlinger::getHwComposer() const {
512 return mCompositionEngine->getHwComposer();
513}
514
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700515renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
516 return mCompositionEngine->getRenderEngine();
517}
518
Lloyd Pique70d91362018-10-18 16:02:55 -0700519compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
520 return *mCompositionEngine.get();
521}
522
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523void SurfaceFlinger::bootFinished()
524{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700525 if (mStartPropertySetThread->join() != NO_ERROR) {
526 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800527 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528 const nsecs_t now = systemTime();
529 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000530 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531
Mikael Pessa90092f42019-08-26 17:22:04 -0700532 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000533 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // wait patiently for the window manager death
536 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700537 mWindowManager = defaultServiceManager()->getService(name);
538 if (mWindowManager != 0) {
539 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540 }
Robert Carr720e5062018-07-30 17:45:14 -0700541 sp<IBinder> input(defaultServiceManager()->getService(
542 String16("inputflinger")));
543 if (input == nullptr) {
544 ALOGE("Failed to link to input service");
545 } else {
546 mInputFlinger = interface_cast<IInputFlinger>(input);
547 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548
Steven Thomas050b2c82017-03-06 11:45:16 -0800549 if (mVrFlinger) {
550 mVrFlinger->OnBootFinished();
551 }
552
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700554 // formerly we would just kill the process, but we now ask it to exit so it
555 // can choose where to stop the animation.
556 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700557
558 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
559 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
560 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700561
Ana Krulecbd6654b2019-02-15 15:18:15 -0800562 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800563 readPersistentProperties();
564 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565
Ady Abraham8a82ba62020-01-17 12:43:17 -0800566 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
567 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
568 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
569 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800571}
572
Dan Stoza436ccf32018-06-21 12:10:12 -0700573uint32_t SurfaceFlinger::getNewTexture() {
574 {
575 std::lock_guard lock(mTexturePoolMutex);
576 if (!mTexturePool.empty()) {
577 uint32_t name = mTexturePool.back();
578 mTexturePool.pop_back();
579 ATRACE_INT("TexturePoolSize", mTexturePool.size());
580 return name;
581 }
582
583 // The pool was too small, so increase it for the future
584 ++mTexturePoolSize;
585 }
586
587 // The pool was empty, so we need to get a new texture name directly using a
588 // blocking call to the main thread
589 uint32_t name = 0;
590 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
591 return name;
592}
593
Mathias Agopian3f844832013-08-07 21:24:32 -0700594void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700595 std::lock_guard lock(mTexturePoolMutex);
596 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
597 // to actually delete this or not based on mTexturePoolSize
598 mTexturePool.push_back(texture);
599 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700600}
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700610 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800611 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700612 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
613 renderengine::RenderEngineCreationArgs::Builder()
614 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
615 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
616 .setUseColorManagerment(useColorManagement)
617 .setEnableProtectedContext(enable_protected_contents(false))
618 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800619 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700620 .setContextPriority(useContextPriority
621 ? renderengine::RenderEngine::ContextPriority::HIGH
622 : renderengine::RenderEngine::ContextPriority::MEDIUM)
623 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800624 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700628 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800629 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800630 // Process any initial hotplug and resulting display changes.
631 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700632 const auto display = getDefaultDisplayDeviceLocked();
633 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700634 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700635 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800636
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700639 // This callback is called from the vr flinger dispatch thread. We
640 // need to call signalTransaction(), which requires holding
641 // mStateLock when we're not on the main thread. Acquiring
642 // mStateLock from the vr flinger dispatch thread might trigger a
643 // deadlock in surface flinger (see b/66916578), so post a message
644 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700645 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700646 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
647 mVrFlingerRequestsDisplay = requestDisplay;
648 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700649 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
652 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700653 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 .value_or(0),
655 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (!mVrFlinger) {
657 ALOGE("Failed to start vrflinger");
658 }
659 }
660
Mathias Agopian92a979a2012-08-02 18:32:23 -0700661 // initialize our drawing state
662 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700663
Andy McFadden13a082e2012-08-24 10:16:42 -0700664 // set initial conditions (e.g. unblank default device)
665 initializeDisplays();
666
Steven Thomas137d4bc2019-07-25 16:55:14 -0700667 char primeShaderCache[PROPERTY_VALUE_MAX];
668 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
669 if (atoi(primeShaderCache)) {
670 getRenderEngine().primeCache();
671 }
Dan Stoza4e637772016-07-28 13:31:51 -0700672
Wei Wangf9b05ee2017-07-19 20:59:39 -0700673 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700674
675 const bool presentFenceReliable =
676 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
677 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700678
679 if (mStartPropertySetThread->Start() != NO_ERROR) {
680 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800681 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800682
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700684}
685
Romain Guy11d63f42017-07-20 12:47:14 -0700686void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700687 Mutex::Autolock _l(mStateLock);
688
Romain Guy11d63f42017-07-20 12:47:14 -0700689 char value[PROPERTY_VALUE_MAX];
690
691 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800692 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700693 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800694 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100695
696 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700697 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800698
699 property_get("persist.sys.sf.color_mode", value, "0");
700 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700701}
702
Mathias Agopiana67e4182012-06-19 17:26:12 -0700703void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800704 // Start boot animation service by setting a property mailbox
705 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800707 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 if (mStartPropertySetThread->join() != NO_ERROR) {
709 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800710 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700711}
712
Mathias Agopian875d8e12013-06-07 15:35:48 -0700713size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700714 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700715}
716
Mathias Agopian875d8e12013-06-07 15:35:48 -0700717size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700719}
720
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800722
Jamie Gennis582270d2011-08-17 18:19:00 -0700723bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800724 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800725 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800726 return authenticateSurfaceTextureLocked(bufferProducer);
727}
728
729bool SurfaceFlinger::authenticateSurfaceTextureLocked(
730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800731 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800732 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800733}
734
Brian Anderson6b376712017-04-04 10:51:39 -0700735status_t SurfaceFlinger::getSupportedFrameTimestamps(
736 std::vector<FrameEvent>* outSupported) const {
737 *outSupported = {
738 FrameEvent::REQUESTED_PRESENT,
739 FrameEvent::ACQUIRE,
740 FrameEvent::LATCH,
741 FrameEvent::FIRST_REFRESH_START,
742 FrameEvent::LAST_REFRESH_START,
743 FrameEvent::GPU_COMPOSITION_DONE,
744 FrameEvent::DEQUEUE_READY,
745 FrameEvent::RELEASE,
746 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700747 ConditionalLock _l(mStateLock,
748 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700749 if (!getHwComposer().hasCapability(
750 HWC2::Capability::PresentFenceIsNotReliable)) {
751 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
752 }
753 return NO_ERROR;
754}
755
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800756status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
757 if (!displayToken || !state) {
758 return BAD_VALUE;
759 }
760
761 Mutex::Autolock lock(mStateLock);
762
763 const auto display = getDisplayDeviceLocked(displayToken);
764 if (!display) {
765 return NAME_NOT_FOUND;
766 }
767
768 state->layerStack = display->getLayerStack();
769 state->orientation = display->getOrientation();
770
771 const Rect viewport = display->getViewport();
772 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
773
774 return NO_ERROR;
775}
776
777status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
778 if (!displayToken || !info) {
779 return BAD_VALUE;
780 }
781
782 Mutex::Autolock lock(mStateLock);
783
784 const auto display = getDisplayDeviceLocked(displayToken);
785 if (!display) {
786 return NAME_NOT_FOUND;
787 }
788
Dominik Laskowski55c85402020-01-21 16:25:47 -0800789 if (const auto connectionType = display->getConnectionType())
790 info->connectionType = *connectionType;
791 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800792 return INVALID_OPERATION;
793 }
794
795 if (mEmulatedDisplayDensity) {
796 info->density = mEmulatedDisplayDensity;
797 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800798 info->density = info->connectionType == DisplayConnectionType::Internal
799 ? mInternalDisplayDensity
800 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800801 }
802
803 info->secure = display->isSecure();
804
805 return NO_ERROR;
806}
807
Dominik Laskowski22488f62019-03-28 09:53:04 -0700808status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800809 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700810 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Dominik Laskowski22488f62019-03-28 09:53:04 -0700814 Mutex::Autolock lock(mStateLock);
815
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800816 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 if (!displayId) {
818 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800821 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700822
Dan Stoza7f7da322014-05-02 15:26:25 -0700823 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700824
Dominik Laskowski075d3172018-05-24 15:50:06 -0700825 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800828 auto width = hwConfig->getWidth();
829 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 auto xDpi = hwConfig->getDpiX();
832 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700833
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800834 if (isInternal &&
835 (internalDisplayOrientation == ui::ROTATION_90 ||
836 internalDisplayOrientation == ui::ROTATION_270)) {
837 std::swap(width, height);
838 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 }
840
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800842
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800843 if (mEmulatedDisplayDensity) {
844 config.xDpi = mEmulatedDisplayDensity;
845 config.yDpi = mEmulatedDisplayDensity;
846 } else {
847 config.xDpi = xDpi;
848 config.yDpi = yDpi;
849 }
850
851 const nsecs_t period = hwConfig->getVsyncPeriod();
852 config.refreshRate = 1e9f / period;
853
854 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
855 config.appVsyncOffset = offsets.late.app;
856 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857
Andy McFadden91b2ca82014-06-13 14:04:23 -0700858 // This is how far in advance a buffer must be queued for
859 // presentation at a given time. If you want a buffer to appear
860 // on the screen at time N, you must submit the buffer before
861 // (N - presentationDeadline).
862 //
863 // Normally it's one full refresh period (to give SF a chance to
864 // latch the buffer), but this can be reduced by configuring a
865 // DispSync offset. Any additional delays introduced by the hardware
866 // composer or panel must be accounted for here.
867 //
868 // We add an additional 1ms to allow for processing time and
869 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700871
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700873 }
874
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 return NO_ERROR;
876}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700877
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700878status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
879 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700880 return BAD_VALUE;
881 }
882
Ana Krulecc2870422019-01-29 19:00:58 -0800883 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700884 return NO_ERROR;
885}
886
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
888 const auto display = getDisplayDevice(displayToken);
889 if (!display) {
890 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800891 return BAD_VALUE;
892 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700893
Steven Thomasc9098452019-09-30 17:15:05 -0700894 if (display->isPrimary()) {
895 std::lock_guard<std::mutex> lock(mActiveConfigLock);
896 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800897 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700898 }
Steven Thomasc9098452019-09-30 17:15:05 -0700899 }
Ady Abraham2139f732019-11-13 18:56:40 -0800900
901 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Ady Abraham03b02dd2019-03-21 15:40:11 -0700904void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800905 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800906 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
907 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800908
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800909 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800910 // config twice. However event generation config might have changed so we need to update it
911 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800912 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700913 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
914 mDesiredActiveConfig = info;
915 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800916
917 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800918 // This will trigger HWC refresh without resetting the idle timer.
919 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700920 // Start receiving vsync samples now, so that we can detect a period
921 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800922 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700923 // As we called to set period, we will call to onRefreshRateChangeCompleted once
924 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700925 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800926
Ady Abraham9e16a482019-12-03 17:19:41 -0800927 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
928 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800930 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700931
932 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800933 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700934 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800935}
936
937status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
938 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800939
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100940 if (!displayToken) {
941 return BAD_VALUE;
942 }
Ady Abraham838de062019-02-04 10:24:03 -0800943
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100944 status_t result = NO_ERROR;
945
946 postMessageSync(new LambdaMessage([&]() {
947 const auto display = getDisplayDeviceLocked(displayToken);
948 if (!display) {
949 ALOGE("Attempt to set allowed display configs for invalid display token %p",
950 displayToken.get());
951 result = BAD_VALUE;
952 } else if (display->isVirtual()) {
953 ALOGW("Attempt to set allowed display configs for virtual display");
954 result = BAD_VALUE;
955 } else {
956 HwcConfigIndexType config(mode);
957 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
958 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
959 refreshRate.fps);
960 }
961 }));
962
963 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964}
965
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966void SurfaceFlinger::setActiveConfigInternal() {
967 ATRACE_CALL();
968
Dominik Laskowski22488f62019-03-28 09:53:04 -0700969 const auto display = getDefaultDisplayDeviceLocked();
970 if (!display) {
971 return;
972 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800975 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700976 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 display->setActiveConfig(mUpcomingActiveConfig.configId);
978
Ady Abraham2139f732019-11-13 18:56:40 -0800979 auto refreshRate =
980 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800981 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
982 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800983 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700984
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800985 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700986 const nsecs_t vsyncPeriod =
987 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
988 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800989 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700990 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800991 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992}
993
Ady Abraham53852a52019-05-28 18:07:44 -0700994void SurfaceFlinger::desiredActiveConfigChangeDone() {
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
996 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
997 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700998
Kevin DuBois5988f482020-01-17 09:03:32 -0800999 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001000 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001001 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001002 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1003 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001004}
1005
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001007 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001008 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001010 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001012 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 return true;
1014 }
1015
1016 // We received the present fence from the HWC, so we assume it successfully updated
1017 // the config, hence we update SF.
1018 mCheckPendingFence = false;
1019 setActiveConfigInternal();
1020 }
1021
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022 // Store the local variable to release the lock.
1023 ActiveConfigInfo desiredActiveConfig;
1024 {
1025 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 if (!mDesiredActiveConfigChanged) {
1027 return false;
1028 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 desiredActiveConfig = mDesiredActiveConfig;
1030 }
1031
Ady Abraham2139f732019-11-13 18:56:40 -08001032 auto refreshRate =
1033 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1034 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1035 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001036 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1038 // display is not valid or we are already in the requested mode
1039 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001040 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001042 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043
Ady Abraham838de062019-02-04 10:24:03 -08001044 // Desired active config was set, it is different than the config currently in use, however
1045 // allowed configs might have change by the time we process the refresh.
1046 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001047 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001048 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001049 return false;
1050 }
Alec Mouri7f015182019-07-11 13:56:22 -07001051
Ady Abrahamb838aed2019-02-12 15:30:16 -08001052 mUpcomingActiveConfig = desiredActiveConfig;
1053 const auto displayId = display->getId();
1054 LOG_ALWAYS_FATAL_IF(!displayId);
1055
Ady Abraham2139f732019-11-13 18:56:40 -08001056 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001057
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001058 // TODO(b/142753666) use constrains
1059 HWC2::VsyncPeriodChangeConstraints constraints;
1060 constraints.desiredTimeNanos = systemTime();
1061 constraints.seamlessRequired = false;
1062
1063 HWC2::VsyncPeriodChangeTimeline outTimeline;
1064 auto status =
1065 getHwComposer().setActiveConfigWithConstraints(*displayId,
1066 mUpcomingActiveConfig.configId.value(),
1067 constraints, &outTimeline);
1068 if (status != NO_ERROR) {
1069 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1070 return false;
1071 }
1072
1073 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1074 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001075 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001076 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001077}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1080 Vector<ColorMode>* outColorModes) {
1081 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return BAD_VALUE;
1083 }
1084
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001086 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001087 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001088 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1089
1090 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1091 if (!displayId) {
1092 return NAME_NOT_FOUND;
1093 }
1094
Dominik Laskowski075d3172018-05-24 15:50:06 -07001095 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001096 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001097 }
Michael Wright28f24d02016-07-12 13:30:53 -07001098 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001099
1100 // If it's built-in display and the configuration claims it's not wide color capable,
1101 // filter out all wide color modes. The typical reason why this happens is that the
1102 // hardware is not good enough to support GPU composition of wide color, and thus the
1103 // OEMs choose to disable this capability.
1104 if (isInternalDisplay && !hasWideColorDisplay) {
1105 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1106 isWideColorMode);
1107 } else {
1108 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1109 }
Michael Wright28f24d02016-07-12 13:30:53 -07001110
1111 return NO_ERROR;
1112}
1113
Daniel Solomon42d04562019-01-20 21:03:19 -08001114status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1115 ui::DisplayPrimaries &primaries) {
1116 if (!displayToken) {
1117 return BAD_VALUE;
1118 }
1119
1120 // Currently we only support this API for a single internal display.
1121 if (getInternalDisplayToken() != displayToken) {
1122 return BAD_VALUE;
1123 }
1124
1125 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1126 return NO_ERROR;
1127}
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1130 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001131 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001132 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001133 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001134}
1135
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001136status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001137 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001138 Vector<ColorMode> modes;
1139 getDisplayColorModes(displayToken, &modes);
1140 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1141 if (mode < ColorMode::NATIVE || !exists) {
1142 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1143 decodeColorMode(mode).c_str(), mode, displayToken.get());
1144 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001145 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 const auto display = getDisplayDevice(displayToken);
1147 if (!display) {
1148 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1149 decodeColorMode(mode).c_str(), mode, displayToken.get());
1150 } else if (display->isVirtual()) {
1151 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1152 decodeColorMode(mode).c_str(), mode);
1153 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001154 display->getCompositionDisplay()->setColorProfile(
1155 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1156 RenderIntent::COLORIMETRIC,
1157 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001158 }
1159 }));
1160
Michael Wright28f24d02016-07-12 13:30:53 -07001161 return NO_ERROR;
1162}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001163
Galia Peycheva5492cb52019-10-30 14:13:16 +01001164status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1165 bool* outSupport) const {
1166 Mutex::Autolock _l(mStateLock);
1167
1168 if (!displayToken) {
1169 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1170 return BAD_VALUE;
1171 }
1172 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1173 if (!displayId) {
1174 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1175 displayToken.get());
1176 return NAME_NOT_FOUND;
1177 }
1178 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1179 HWC2::DisplayCapability::AutoLowLatencyMode);
1180 return NO_ERROR;
1181}
1182
1183void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1184 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1185}
1186
1187void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1188 if (!displayToken) {
1189 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1190 return;
1191 }
1192 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1193 if (!displayId) {
1194 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1195 displayToken.get());
1196 return;
1197 }
1198
1199 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1200}
1201
1202status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1203 bool* outSupport) const {
1204 Mutex::Autolock _l(mStateLock);
1205
1206 if (!displayToken) {
1207 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1208 return BAD_VALUE;
1209 }
1210 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1211 if (!displayId) {
1212 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1213 displayToken.get());
1214 return NAME_NOT_FOUND;
1215 }
1216
1217 std::vector<HWC2::ContentType> outSupportedContentTypes;
1218 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1219 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1220 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1221 return NO_ERROR;
1222}
1223
1224void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1225 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1226}
1227
1228void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1229 if (!displayToken) {
1230 ALOGE("setGameContentType() failed. Missing display token.");
1231 return;
1232 }
1233 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1234 if (!displayId) {
1235 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1236 displayToken.get());
1237 return;
1238 }
1239
1240 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1241 getHwComposer().setContentType(*displayId, type);
1242}
1243
Svetoslavd85084b2014-03-20 10:28:31 -07001244status_t SurfaceFlinger::clearAnimationFrameStats() {
1245 Mutex::Autolock _l(mStateLock);
1246 mAnimFrameTracker.clearStats();
1247 return NO_ERROR;
1248}
1249
1250status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1251 Mutex::Autolock _l(mStateLock);
1252 mAnimFrameTracker.getStats(outStats);
1253 return NO_ERROR;
1254}
1255
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001256status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1257 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001258 Mutex::Autolock _l(mStateLock);
1259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001260 const auto display = getDisplayDeviceLocked(displayToken);
1261 if (!display) {
1262 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001263 return BAD_VALUE;
1264 }
1265
Peiyong Linfb069302018-04-25 14:34:31 -07001266 // At this point the DisplayDeivce should already be set up,
1267 // meaning the luminance information is already queried from
1268 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001269 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001270 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1271 capabilities.getDesiredMaxLuminance(),
1272 capabilities.getDesiredMaxAverageLuminance(),
1273 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001274
1275 return NO_ERROR;
1276}
1277
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001278status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1279 ui::PixelFormat* outFormat,
1280 ui::Dataspace* outDataspace,
1281 uint8_t* outComponentMask) const {
1282 if (!outFormat || !outDataspace || !outComponentMask) {
1283 return BAD_VALUE;
1284 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001285 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001286 if (!display || !display->getId()) {
1287 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1288 return BAD_VALUE;
1289 }
1290 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1291 outDataspace, outComponentMask);
1292}
1293
Kevin DuBois74e53772018-11-19 10:52:38 -08001294status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1295 bool enable, uint8_t componentMask,
1296 uint64_t maxFrames) const {
1297 const auto display = getDisplayDevice(displayToken);
1298 if (!display || !display->getId()) {
1299 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1300 return BAD_VALUE;
1301 }
1302
1303 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1304 componentMask, maxFrames);
1305}
1306
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001307status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1308 uint64_t maxFrames, uint64_t timestamp,
1309 DisplayedFrameStats* outStats) const {
1310 const auto display = getDisplayDevice(displayToken);
1311 if (!display || !display->getId()) {
1312 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1313 return BAD_VALUE;
1314 }
1315
1316 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1317 outStats);
1318}
1319
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001320status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1321 if (!outSupported) {
1322 return BAD_VALUE;
1323 }
1324 *outSupported = getRenderEngine().supportsProtectedContent();
1325 return NO_ERROR;
1326}
1327
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001328status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1329 bool* outIsWideColorDisplay) const {
1330 if (!displayToken || !outIsWideColorDisplay) {
1331 return BAD_VALUE;
1332 }
1333 Mutex::Autolock _l(mStateLock);
1334 const auto display = getDisplayDeviceLocked(displayToken);
1335 if (!display) {
1336 return BAD_VALUE;
1337 }
Peiyong Linff84a152019-05-17 18:36:19 -07001338
1339 // Use hasWideColorDisplay to override built-in display.
1340 const auto displayId = display->getId();
1341 if (displayId && displayId == getInternalDisplayIdLocked()) {
1342 *outIsWideColorDisplay = hasWideColorDisplay;
1343 return NO_ERROR;
1344 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001345 *outIsWideColorDisplay = display->hasWideColorGamut();
1346 return NO_ERROR;
1347}
1348
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001349status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001350 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001351 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001352
Dominik Laskowski6505f792019-09-18 11:10:05 -07001353 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1354 mEventQueue->setEventConnection(
1355 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001356 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001357 }));
1358
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001359 return NO_ERROR;
1360}
1361
1362status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001363 Mutex::Autolock lock(mStateLock);
1364 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001365}
1366
Lloyd Pique755e3192018-01-31 16:46:15 -08001367status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1368 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001369 // Try to acquire a lock for 1s, fail gracefully
1370 const status_t err = mStateLock.timedLock(s2ns(1));
1371 const bool locked = (err == NO_ERROR);
1372 if (!locked) {
1373 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1374 return TIMED_OUT;
1375 }
1376
1377 outLayers->clear();
1378 mCurrentState.traverseInZOrder([&](Layer* layer) {
1379 outLayers->push_back(layer->getLayerDebugInfo());
1380 });
1381
1382 mStateLock.unlock();
1383 return NO_ERROR;
1384}
1385
Peiyong Linc6780972018-10-28 15:24:08 -07001386status_t SurfaceFlinger::getCompositionPreference(
1387 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1388 Dataspace* outWideColorGamutDataspace,
1389 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001390 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001391 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001392 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001393 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001394 return NO_ERROR;
1395}
1396
Dan Stozaec460082018-12-17 15:35:09 -08001397status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1398 const sp<IBinder>& stopLayerHandle,
1399 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001400 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001401 return BAD_VALUE;
1402 }
1403 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001404 return NO_ERROR;
1405}
1406
Dan Stozaec460082018-12-17 15:35:09 -08001407status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001408 if (!listener) {
1409 return BAD_VALUE;
1410 }
Dan Stozaec460082018-12-17 15:35:09 -08001411 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001412 return NO_ERROR;
1413}
Dan Gittik57e63c52019-01-18 16:37:54 +00001414
1415status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1416 bool* outSupport) const {
1417 if (!displayToken || !outSupport) {
1418 return BAD_VALUE;
1419 }
1420 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1421 if (!displayId) {
1422 return NAME_NOT_FOUND;
1423 }
1424 *outSupport =
1425 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1426 return NO_ERROR;
1427}
1428
1429status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1430 float brightness) const {
1431 if (!displayToken) {
1432 return BAD_VALUE;
1433 }
1434 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1435 if (!displayId) {
1436 return NAME_NOT_FOUND;
1437 }
1438 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1439}
1440
Ady Abraham8532d012019-05-08 14:50:56 -07001441status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1442 PowerHint powerHint = static_cast<PowerHint>(hintId);
1443
1444 if (powerHint == PowerHint::INTERACTION) {
1445 mScheduler->notifyTouchEvent();
1446 }
1447
1448 return NO_ERROR;
1449}
1450
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001451// ----------------------------------------------------------------------------
1452
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001453sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001454 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001455 const auto& handle =
1456 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001457
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001458 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001459}
1460
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001462
1463void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001464 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001465}
1466
1467void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001468 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001469 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001470}
1471
1472void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001473 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001474 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001475}
1476
1477void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001478 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001479 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001480}
1481
1482status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001483 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001484 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001485}
1486
1487status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001488 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001489 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001490 if (res == NO_ERROR) {
1491 msg->wait();
1492 }
1493 return res;
1494}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001495
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001496void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001497 do {
1498 waitForEvent();
1499 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001500}
1501
Dominik Laskowski83b88212018-12-11 13:34:06 -08001502nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001503 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001504 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1505 return 0;
1506 }
1507
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001508 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001509}
1510
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001511void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001512 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001513 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001514 ATRACE_NAME("SF onVsync");
1515
Steven Thomas3cfac282017-02-06 12:29:30 -08001516 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001518 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001519 return;
1520 }
1521
Dominik Laskowski075d3172018-05-24 15:50:06 -07001522 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001523 return;
1524 }
1525
Dominik Laskowski075d3172018-05-24 15:50:06 -07001526 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001527 // For now, we don't do anything with external display vsyncs.
1528 return;
1529 }
1530
Alec Mourif8e689c2019-05-20 18:32:22 -07001531 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001532 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001533 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001534 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001535 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001536}
1537
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001539 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1540 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541}
1542
Ady Abraham2139f732019-11-13 18:56:40 -08001543bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001544 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001545}
1546
Ady Abraham2139f732019-11-13 18:56:40 -08001547void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1548 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001549 const auto display = getDefaultDisplayDeviceLocked();
1550 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001551 return;
1552 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001553 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001554
Ana Krulec7d1d6832018-12-27 11:10:09 -08001555 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001556 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1557 ALOGV("Skipping config %d as it is not part of allowed configs",
1558 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001559 return;
1560 }
1561
Ady Abraham2139f732019-11-13 18:56:40 -08001562 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001563}
1564
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001565void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001566 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001567 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001568 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001569
Lloyd Piqueba04e622017-12-14 17:11:26 -08001570 // Ignore events that do not have the right sequenceId.
1571 if (sequenceId != getBE().mComposerSequenceId) {
1572 return;
1573 }
1574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 // Only lock if we're not on the main thread. This function is normally
1576 // called on a hwbinder thread, but for the primary display it's called on
1577 // the main thread with the state lock already held, so don't attempt to
1578 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001579 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001580
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001581 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001582
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001583 if (std::this_thread::get_id() == mMainThreadId) {
1584 // Process all pending hot plug events immediately if we are on the main thread.
1585 processDisplayHotplugEventsLocked();
1586 }
1587
Lloyd Piqueba04e622017-12-14 17:11:26 -08001588 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001589}
1590
Ady Abraham7159f572019-10-11 11:10:18 -07001591void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001592 int32_t sequenceId, hwc2_display_t /*display*/,
1593 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1594 Mutex::Autolock lock(mStateLock);
1595 if (sequenceId != getBE().mComposerSequenceId) {
1596 return;
1597 }
1598 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001599}
1600
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001601void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1602 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1603 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1604}
1605
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001606void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001607 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001608 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001609 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001610 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001611 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001612}
1613
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001614void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001615 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001616
1617 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1618 // display power state.
1619 postMessageAsync(new LambdaMessage(
1620 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1621}
1622
1623void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1624 ATRACE_CALL();
1625
Ady Abraham27c70212019-06-11 10:52:26 -07001626 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1627
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001628 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001629 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1630 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001631 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001632 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001633 }
Mathias Agopian86303202012-07-24 22:46:10 -07001634}
1635
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001636// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001637void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001638 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001639 // Clear the drawing state so that the logic inside of
1640 // handleTransactionLocked will fire. It will determine the delta between
1641 // mCurrentState and mDrawingState and re-apply all changes when we make the
1642 // transition.
1643 mDrawingState.displays.clear();
1644 mDisplays.clear();
1645}
1646
Steven Thomas050b2c82017-03-06 11:45:16 -08001647void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001648 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001649 if (!mVrFlinger)
1650 return;
1651 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001652 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001653 return;
1654 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001655
Lloyd Pique441d5042018-10-18 16:49:51 -07001656 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001657 ALOGE("Vr flinger is only supported for remote hardware composer"
1658 " service connections. Ignoring request to transition to vr"
1659 " flinger.");
1660 mVrFlingerRequestsDisplay = false;
1661 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001662 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001663
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001665
Steven Thomas0123ac62018-07-12 11:32:34 -07001666 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001667 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001668
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001669 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001670
1671 // Clear out all the output layers from the composition engine for all
1672 // displays before destroying the hardware composer interface. This ensures
1673 // any HWC layers are destroyed through that interface before it becomes
1674 // invalid.
1675 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001676 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001677 }
1678
Steven Thomas0123ac62018-07-12 11:32:34 -07001679 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1680 // called below. Clear the reference now so we don't accidentally use it
1681 // later.
1682 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001683
Steven Thomasb02664d2017-07-26 18:48:28 -07001684 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001686 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001687
Steven Thomasb02664d2017-07-26 18:48:28 -07001688 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001689 // Delete the current instance before creating the new one
1690 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1691 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1692 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001693 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001694
Lloyd Pique441d5042018-10-18 16:49:51 -07001695 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001696 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001697
1698 if (vrFlingerRequestsDisplay) {
1699 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001700 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001701
1702 mVisibleRegionsDirty = true;
1703 invalidateHwcGeometry();
1704
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001705 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001706 display = getDefaultDisplayDeviceLocked();
1707 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001708 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001709
Steven Thomasb02664d2017-07-26 18:48:28 -07001710 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001711 const nsecs_t vsyncPeriod = getVsyncPeriod();
1712 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001713
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001714 // The present fences returned from vr_hwc are not an accurate
1715 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001716 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001717
Steven Thomasb02664d2017-07-26 18:48:28 -07001718 // Use phase of 0 since phase is not known.
1719 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001720 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001721 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001722
Ana Krulecc2870422019-01-29 19:00:58 -08001723 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001724
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001725 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001726 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001727}
1728
Ady Abraham11579302019-09-19 12:35:58 -07001729bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1730 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001731 // We are storing the last 2 present fences. If sf's phase offset is to be
1732 // woken up before the actual vsync but targeting the next vsync, we need to check
1733 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001734 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1735 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001736
Ady Abraham11579302019-09-19 12:35:58 -07001737 if (fence == Fence::NO_FENCE) {
1738 return false;
1739 }
1740
1741 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1742 fence->wait(graceTimeMs);
1743 }
1744
1745 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001746}
1747
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001748void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001749 DisplayStatInfo stats;
1750 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001751 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001752 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001753 mExpectedPresentTime.store(
1754 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001755}
1756
Dominik Laskowski22488f62019-03-28 09:53:04 -07001757void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001758 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001759 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001760 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001761 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001762 // calculate the expected present time once and use the cached
1763 // value throughout this frame to make sure all layers are
1764 // seeing this same value.
1765 populateExpectedPresentTime();
1766
Ady Abraham11579302019-09-19 12:35:58 -07001767 // When Backpressure propagation is enabled we want to give a small grace period
1768 // for the present fence to fire instead of just giving up on this frame to handle cases
1769 // where present fence is just about to get signaled.
1770 const int graceTimeForPresentFenceMs =
1771 (mPropagateBackpressure &&
1772 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1773 ? 1
1774 : 0;
1775 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1776 previousFrameMissed(
1777 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001778 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1779 mHadDeviceComposition && frameMissed};
1780 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1781 mHadClientComposition && frameMissed};
1782
Alec Mouricc0fc602019-02-26 21:45:19 -08001783 if (frameMissed) {
1784 mFrameMissedCount++;
1785 mTimeStats->incrementMissedFrames();
1786 }
1787
Alec Mouri40189b02019-03-05 15:07:54 -08001788 if (hwcFrameMissed) {
1789 mHwcFrameMissedCount++;
1790 }
1791
1792 if (gpuFrameMissed) {
1793 mGpuFrameMissedCount++;
1794 }
1795
Ady Abrahamadb9a992019-09-19 21:21:55 +00001796 if (frameMissed && mPropagateBackpressure) {
1797 if ((hwcFrameMissed && !gpuFrameMissed) ||
1798 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001799 signalLayerUpdate();
1800 break;
1801 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001802 }
Dan Stoza50182882016-07-08 12:02:20 -07001803
Steven Thomas050b2c82017-03-06 11:45:16 -08001804 // Now that we're going to make it to the handleMessageTransaction()
1805 // call below it's safe to call updateVrFlinger(), which will
1806 // potentially trigger a display handoff.
1807 updateVrFlinger();
1808
Dan Stoza6b9454d2014-11-07 16:00:59 -08001809 bool refreshNeeded = handleMessageTransaction();
1810 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001811
Ana Krulecc84d09b2019-11-02 23:10:29 +01001812 // Layers need to get updated (in the previous line) before we can use them for
1813 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001814 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1815 // and may eventually call to ~Layer() if it holds the last reference
1816 {
1817 Mutex::Autolock _l(mStateLock);
1818 mScheduler->chooseRefreshRateForContent();
1819 }
1820
Ana Krulecc84d09b2019-11-02 23:10:29 +01001821 if (performSetActiveConfig()) {
1822 break;
1823 }
1824
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001825 updateCursorAsync();
1826 updateInputFlinger();
1827
Dan Stoza58784442014-12-02 16:58:17 -08001828 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001829 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001830 // Signal a refresh if a transaction modified the window state,
1831 // a new buffer was latched, or if HWC has requested a full
1832 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001833 if (mFrameStartTime <= 0) {
1834 // We should only use the time of the first invalidate
1835 // message that signals a refresh as the beginning of the
1836 // frame. Otherwise the real frame time will be
1837 // underestimated.
1838 mFrameStartTime = frameStart;
1839 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001840 signalRefresh();
1841 }
1842 break;
1843 }
1844 case MessageQueue::REFRESH: {
1845 handleMessageRefresh();
1846 break;
1847 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001848 }
1849}
1850
Dan Stoza6b9454d2014-11-07 16:00:59 -08001851bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001852 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001853 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001854
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001855 bool flushedATransaction = flushTransactionQueues();
1856
1857 bool runHandleTransaction = transactionFlags &&
1858 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1859
1860 if (runHandleTransaction) {
1861 handleTransaction(eTransactionMask);
1862 } else {
1863 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001864 }
1865
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001866 if (transactionFlushNeeded()) {
1867 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001868 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001869
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001870 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001871}
1872
Mathias Agopian4fec8732012-06-29 14:12:52 -07001873void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001874 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001875
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001876 mRefreshPending = false;
1877
Lloyd Piqueab039b52019-02-13 14:22:42 -08001878 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001879 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001880 for (const auto& [_, display] : mDisplays) {
1881 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1882 }
1883 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001884 if (auto layerFE = layer->getCompositionEngineLayerFE())
1885 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001886 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001887 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1888 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001889 if (auto layerFE = layer->getCompositionEngineLayerFE())
1890 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001891 }
1892
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001893 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001894 refreshArgs.outputColorSetting = useColorManagement
1895 ? mDisplayColorSetting
1896 : compositionengine::OutputColorSetting::kUnmanaged;
1897 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1898 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001899
1900 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1901 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001902
1903 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1904 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1905 mDrawingState.colorMatrixChanged = false;
1906 }
1907
1908 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1909
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001910 if (mDebugRegion != 0) {
1911 refreshArgs.devOptFlashDirtyRegionsDelay =
1912 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1913 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001914
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001915 mGeometryInvalid = false;
1916
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001917 // Store the present time just before calling to the composition engine so we could notify
1918 // the scheduler.
1919 const auto presentTime = systemTime();
1920
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001921 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001922 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1923 // Reset the frame start time now that we've recorded this frame.
1924 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001925
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001926 mScheduler->onDisplayRefreshed(presentTime);
1927
David Sodmanfa9b2af2017-12-24 13:28:59 -08001928 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001929 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001930
Lloyd Pique66d68602019-02-13 14:23:31 -08001931 mHadClientComposition =
1932 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1933 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001934 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1935 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001936 });
1937 mHadDeviceComposition =
1938 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1939 auto& displayDevice = tokenDisplayPair.second;
1940 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1941 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001942 mReusedClientComposition =
1943 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1944 auto& displayDevice = tokenDisplayPair.second;
1945 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1946 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001947
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001948 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001949
David Sodman7e4ae112018-02-09 15:02:28 -08001950 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001951 if (mVisibleRegionsDirty) {
1952 mVisibleRegionsDirty = false;
1953 if (mTracingEnabled) {
1954 mTracing.notify("visibleRegionsDirty");
1955 }
1956 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001957
1958 if (mCompositionEngine->needsAnotherUpdate()) {
1959 signalLayerUpdate();
1960 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001962
David Sodmanfa9b2af2017-12-24 13:28:59 -08001963
1964bool SurfaceFlinger::handleMessageInvalidate() {
1965 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001966 bool refreshNeeded = handlePageFlip();
1967
Vishnu Nair4351ad52019-02-11 14:13:02 -08001968 if (mVisibleRegionsDirty) {
1969 computeLayerBounds();
1970 }
1971
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001972 for (auto& layer : mLayersPendingRefresh) {
1973 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001974 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001975 invalidateLayerStack(layer, visibleReg);
1976 }
1977 mLayersPendingRefresh.clear();
1978 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001979}
1980
Ana Krulece588e312018-09-18 12:32:24 -07001981void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1982 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 // Update queue of past composite+present times and determine the
1984 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001985 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001987 while (!getBE().mCompositePresentTimes.empty()) {
1988 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989 // Cached values should have been updated before calling this method,
1990 // which helps avoid duplicate syscalls.
1991 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1992 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1993 break;
1994 }
1995 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001996 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001997 }
1998
1999 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002000 while (getBE().mCompositePresentTimes.size() > 16) {
2001 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002002 }
2003
Ana Krulece588e312018-09-18 12:32:24 -07002004 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002005}
2006
Ana Krulece588e312018-09-18 12:32:24 -07002007void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2008 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002009 // Integer division and modulo round toward 0 not -inf, so we need to
2010 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002011 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2012 ? (stats.vsyncPeriod -
2013 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2014 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002015
Ady Abraham9e16a482019-12-03 17:19:41 -08002016 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002017 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002018 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002019 }
2020
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021 // Snap the latency to a value that removes scheduling jitter from the
2022 // composition and present times, which often have >1ms of jitter.
2023 // Reducing jitter is important if an app attempts to extrapolate
2024 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002025 // Snapping also allows an app to precisely calculate
2026 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002027 nsecs_t bias = stats.vsyncPeriod / 2;
2028 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2029 nsecs_t snappedCompositeToPresentLatency =
2030 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031
David Sodman99974d22017-11-28 12:04:33 -08002032 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002033 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2034 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002035 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036}
2037
David Sodman2b406362017-12-15 13:33:47 -08002038void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002039{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ATRACE_CALL();
2041 ALOGV("postComposition");
2042
Brian Andersonf6386862016-10-31 16:34:13 -07002043 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002044 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002045 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002046 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002047 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002048 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002049
David Sodman73beded2017-11-15 11:56:06 -08002050 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002052 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002053 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002054 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2055 ->getRenderSurface()
2056 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002057 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002058 } else {
2059 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2060 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061
David Sodman73beded2017-11-15 11:56:06 -08002062 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002063 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2064 mPreviousPresentFences[0] = displayDevice
2065 ? getHwComposer().getPresentFence(*displayDevice->getId())
2066 : Fence::NO_FENCE;
2067 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002068 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002069
Ana Krulece588e312018-09-18 12:32:24 -07002070 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002071 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072
Lloyd Piqueab039b52019-02-13 14:22:42 -08002073 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2074 // be sampled a little later than when we started doing work for this frame,
2075 // but that should be okay since updateCompositorTiming has snapping logic.
2076 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2077 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002078 CompositorTiming compositorTiming;
2079 {
David Sodman99974d22017-11-28 12:04:33 -08002080 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2081 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002082 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002083
Edgar Arriaga844fa672020-01-16 14:21:42 -08002084 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002085 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2086 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002087 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002088 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002089 }
Robert Carr2047fae2016-11-28 14:09:09 -08002090 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002091
Ady Abraham92fa2f42020-02-11 15:33:56 -08002092 if (displayDevice && displayDevice->isPrimary() &&
2093 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002094 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002095 }
2096
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002097 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002098 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2099 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002100 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002101 }
2102 }
2103
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002104 if (mAnimCompositionPending) {
2105 mAnimCompositionPending = false;
2106
Brian Anderson4e606e32017-03-16 15:34:57 -07002107 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002108 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002109 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002110 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002111 // The HWC doesn't support present fences, so use the refresh
2112 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002113 const nsecs_t presentTime =
2114 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002115 mAnimFrameTracker.setActualPresentTime(presentTime);
2116 }
2117 mAnimFrameTracker.advanceFrame();
2118 }
Dan Stozab90cf072015-03-05 11:05:59 -08002119
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002120 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002121 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002122 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002123 }
2124
Vishnu Nair9b079a22020-01-21 14:36:08 -08002125 if (mReusedClientComposition) {
2126 mTimeStats->incrementClientCompositionReusedFrames();
2127 }
2128
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002129 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002130
Alec Mouri717bcb62020-02-10 17:07:19 -08002131 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2132 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2133 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2134
Lloyd Pique32cbe282018-10-19 13:09:22 -07002135 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2136 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002137 return;
2138 }
2139
2140 nsecs_t currentTime = systemTime();
2141 if (mHasPoweredOff) {
2142 mHasPoweredOff = false;
2143 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002144 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002145 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002146 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2147 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002148 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002149 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002150 }
David Sodman4a36e932017-11-07 14:29:47 -08002151 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002152 }
David Sodman4a36e932017-11-07 14:29:47 -08002153 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002154
2155 {
2156 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002157 if (mTexturePool.size() < mTexturePoolSize) {
2158 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002159 const size_t offset = mTexturePool.size();
2160 mTexturePool.resize(mTexturePoolSize);
2161 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2162 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002163 } else if (mTexturePool.size() > mTexturePoolSize) {
2164 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2165 const size_t offset = mTexturePoolSize;
2166 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2167 mTexturePool.resize(mTexturePoolSize);
2168 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002169 }
2170 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002171
Ady Abrahambe0f9482019-04-24 15:41:53 -07002172 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002173 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002174
Kevin DuBois413287f2019-02-25 08:46:47 -08002175 if (mLumaSampling && mRegionSamplingThread) {
2176 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002177 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002178
2179 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2180 // side-effect of getTotalSize(), so we check that again here
2181 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002182 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002183 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2184 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002185}
2186
Vishnu Nair4351ad52019-02-11 14:13:02 -08002187void SurfaceFlinger::computeLayerBounds() {
2188 for (const auto& pair : mDisplays) {
2189 const auto& displayDevice = pair.second;
2190 const auto display = displayDevice->getCompositionDisplay();
2191 for (const auto& layer : mDrawingState.layersSortedByZ) {
2192 // only consider the layers on the given layer stack
2193 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002194 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002195 }
2196
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002197 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2198 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002199 }
2200 }
2201}
2202
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203void SurfaceFlinger::postFrame()
2204{
2205 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002206 const auto display = getDefaultDisplayDeviceLocked();
2207 if (display && getHwComposer().isConnected(*display->getId())) {
2208 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002209 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2210 logFrameStats();
2211 }
2212 }
2213}
2214
Mathias Agopian87baae12012-07-31 12:38:26 -07002215void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002216{
Mathias Agopian841cde52012-03-01 15:44:37 -08002217 ATRACE_CALL();
2218
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002219 // here we keep a copy of the drawing state (that is the state that's
2220 // going to be overwritten by handleTransactionLocked()) outside of
2221 // mStateLock so that the side-effects of the State assignment
2222 // don't happen with mStateLock held (which can cause deadlocks).
2223 State drawingState(mDrawingState);
2224
Mathias Agopianca4d3602011-05-19 15:38:14 -07002225 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002226 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002227
Mathias Agopianca4d3602011-05-19 15:38:14 -07002228 // Here we're guaranteed that some transaction flags are set
2229 // so we can call handleTransactionLocked() unconditionally.
2230 // We call getTransactionFlags(), which will also clear the flags,
2231 // with mStateLock held to guarantee that mCurrentState won't change
2232 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002233
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002234 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002235 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002236 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002237
Mathias Agopianca4d3602011-05-19 15:38:14 -07002238 mDebugInTransaction = 0;
2239 invalidateHwcGeometry();
2240 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002241}
2242
Lloyd Piqueba04e622017-12-14 17:11:26 -08002243void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2244 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 const std::optional<DisplayIdentificationInfo> info =
2246 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002247
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002249 continue;
2250 }
2251
Dominik Laskowski55c85402020-01-21 16:25:47 -08002252 const DisplayId displayId = info->id;
2253 const auto it = mPhysicalDisplayTokens.find(displayId);
2254
Lloyd Piqueba04e622017-12-14 17:11:26 -08002255 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002256 if (it == mPhysicalDisplayTokens.end()) {
2257 ALOGV("Creating display %s", to_string(displayId).c_str());
2258
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002259 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002260 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002261 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002262
Dominik Laskowski075d3172018-05-24 15:50:06 -07002263 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002264 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 state.isSecure = true; // All physical displays are currently considered secure.
2266 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002267
2268 sp<IBinder> token = new BBinder();
2269 mCurrentState.displays.add(token, state);
2270 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2271
Dominik Laskowski075d3172018-05-24 15:50:06 -07002272 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002273 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002274 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002275 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002276
Dominik Laskowski55c85402020-01-21 16:25:47 -08002277 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002278 if (index >= 0) {
2279 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2280 mInterceptor->saveDisplayDeletion(state.sequenceId);
2281 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002282 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002283 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002284 }
2285
2286 processDisplayChangesLocked();
2287 }
2288
2289 mPendingHotplugEvents.clear();
2290}
2291
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002292void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002293 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2294 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002295}
2296
Lloyd Pique99d3da52018-01-22 17:48:03 -08002297sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002298 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002299 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300 const sp<IGraphicBufferProducer>& producer) {
2301 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002302 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002303 creationArgs.isSecure = state.isSecure;
2304 creationArgs.displaySurface = dispSurface;
2305 creationArgs.hasWideColorGamut = false;
2306 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002307 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002308
Dominik Laskowski55c85402020-01-21 16:25:47 -08002309 if (const auto& physical = state.physical) {
2310 creationArgs.connectionType = physical->type;
2311 }
2312
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002313 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002314 creationArgs.isPrimary = isInternalDisplay;
2315
2316 if (useColorManagement && displayId) {
2317 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002319 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002320 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002321 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322
Dominik Laskowski7e045462018-05-30 13:02:02 -07002323 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002324 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002325 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002326 }
tangrobin6753a022018-08-10 10:58:54 +08002327 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 if (displayId) {
2330 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002331 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002333 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002334
Lloyd Pique90c115d2018-09-18 21:39:42 -07002335 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002337 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002338
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 // Make sure that composition can never be stalled by a virtual display
2340 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002341 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002342 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002343 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2344 }
2345
Dominik Laskowski718f9602019-11-09 20:01:35 -08002346 creationArgs.physicalOrientation =
2347 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002348
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002350 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002351
Lloyd Pique90c115d2018-09-18 21:39:42 -07002352 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353
2354 if (maxFrameBufferAcquiredBuffers >= 3) {
2355 nativeWindowSurface->preallocateBuffers();
2356 }
2357
2358 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002359 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002360 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002362 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002364 display->getCompositionDisplay()->setColorProfile(
2365 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2366 RenderIntent::COLORIMETRIC,
2367 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 if (!state.isVirtual()) {
2369 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002370 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2371 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002372 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 display->setLayerStack(state.layerStack);
2375 display->setProjection(state.orientation, state.viewport, state.frame);
2376 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002378 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379}
2380
Lloyd Pique347200f2017-12-14 17:00:15 -08002381void SurfaceFlinger::processDisplayChangesLocked() {
2382 // here we take advantage of Vector's copy-on-write semantics to
2383 // improve performance by skipping the transaction entirely when
2384 // know that the lists are identical
2385 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2386 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2387 if (!curr.isIdenticalTo(draw)) {
2388 mVisibleRegionsDirty = true;
2389 const size_t cc = curr.size();
2390 size_t dc = draw.size();
2391
2392 // find the displays that were removed
2393 // (ie: in drawing state but not in current state)
2394 // also handle displays that changed
2395 // (ie: displays that are in both lists)
2396 for (size_t i = 0; i < dc;) {
2397 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2398 if (j < 0) {
2399 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002400 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002401 // Save display ID before disconnecting.
2402 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002403 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002404
2405 if (!display->isVirtual()) {
2406 LOG_ALWAYS_FATAL_IF(!displayId);
2407 dispatchDisplayHotplugEvent(displayId->value, false);
2408 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002409 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002410
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002411 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 } else {
2413 // this display is in both lists. see if something changed.
2414 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2417 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2418 if (state_binder != draw_binder) {
2419 // changing the surface is like destroying and
2420 // recreating the DisplayDevice, so we just remove it
2421 // from the drawing state, so that it get re-added
2422 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002424 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002425 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002426 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002427 mDrawingState.displays.removeItemsAt(i);
2428 dc--;
2429 // at this point we must loop to the next item
2430 continue;
2431 }
2432
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002433 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002434 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002435 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002436 }
2437 if ((state.orientation != draw[i].orientation) ||
2438 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002440 }
2441 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002443 if (display->isPrimary()) {
2444 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2445 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002446 }
2447 }
2448 }
2449 ++i;
2450 }
2451
2452 // find displays that were added
2453 // (ie: in current state but not in drawing state)
2454 for (size_t i = 0; i < cc; i++) {
2455 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2456 const DisplayDeviceState& state(curr[i]);
2457
Lloyd Pique542307f2018-10-19 13:24:08 -07002458 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 sp<IGraphicBufferProducer> producer;
2460 sp<IGraphicBufferProducer> bqProducer;
2461 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002462 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002463
Dominik Laskowski075d3172018-05-24 15:50:06 -07002464 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002465 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 // Virtual displays without a surface are dormant:
2467 // they have external state (layer stack, projection,
2468 // etc.) but no internal state (i.e. a DisplayDevice).
2469 if (state.surface != nullptr) {
2470 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 int width = 0;
2473 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2474 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2475 int height = 0;
2476 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2477 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2478 int intFormat = 0;
2479 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2480 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002481 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 displayId =
2484 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 }
2486
2487 // TODO: Plumb requested format back up to consumer
2488
2489 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002491 bqProducer, bqConsumer,
2492 state.displayName);
2493
2494 dispSurface = vds;
2495 producer = vds;
2496 }
2497 } else {
2498 ALOGE_IF(state.surface != nullptr,
2499 "adding a supported display, but rendering "
2500 "surface is provided (%p), ignoring it",
2501 state.surface.get());
2502
Dominik Laskowski55c85402020-01-21 16:25:47 -08002503 LOG_FATAL_IF(!state.physical);
2504 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 producer = bqProducer;
2507 }
2508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002511 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002512 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002513 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002514 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002516 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002518
2519 const auto displayDevice = mDisplays[displayToken];
2520 if (displayDevice->isPrimary()) {
2521 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2522 displayDevice->getHeight());
2523 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002524 }
2525 }
2526 }
2527 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528
2529 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002530}
2531
Mathias Agopian87baae12012-07-31 12:38:26 -07002532void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002533{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002534 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2535
Dan Stoza7dde5992015-05-22 09:51:44 -07002536 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002537 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002538 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002539 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541 /*
2542 * Traversal of the children
2543 * (perform the transaction for each of them if needed)
2544 */
2545
Marissa Wall06255332019-03-27 13:48:27 -07002546 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002547 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002549 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550
2551 const uint32_t flags = layer->doTransaction(0);
2552 if (flags & Layer::eVisibleRegion)
2553 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002554
2555 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002556 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002557 }
Robert Carr2047fae2016-11-28 14:09:09 -08002558 });
Marissa Wall06255332019-03-27 13:48:27 -07002559 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 }
2561
2562 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002563 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564 */
2565
Mathias Agopiane57f2922012-08-09 16:29:12 -07002566 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002568 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002569 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002571 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002572 // The transform hint might have changed for some layers
2573 // (either because a display has changed, or because a layer
2574 // as changed).
2575 //
2576 // Walk through all the layers in currentLayers,
2577 // and update their transform hint.
2578 //
2579 // If a layer is visible only on a single display, then that
2580 // display is used to calculate the hint, otherwise we use the
2581 // default display.
2582 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002583 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002584 // the hint is set before we acquire a buffer from the surface texture.
2585 //
2586 // NOTE: layer transactions have taken place already, so we use their
2587 // drawing state. However, SurfaceFlinger's own transaction has not
2588 // happened yet, so we must use the current state layer list
2589 // (soon to become the drawing state list).
2590 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002591 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002592 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002593 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002594 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002595 // NOTE: we rely on the fact that layers are sorted by
2596 // layerStack first (so we don't have to traverse the list
2597 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002598 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002599 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002600 currentlayerStack = layerStack;
2601 // figure out if this layerstack is mirrored
2602 // (more than one display) if so, pick the default display,
2603 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 hintDisplay = nullptr;
2605 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002606 if (display->getCompositionDisplay()
2607 ->belongsInOutput(layer->getLayerStack(),
2608 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002609 if (hintDisplay) {
2610 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002611 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002612 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002613 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002614 }
2615 }
2616 }
2617 }
Chet Haase91d25932013-04-11 15:24:55 -07002618
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002619 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002620 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2621 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002622
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002623 // could be null when this layer is using a layerStack
2624 // that is not visible on any display. Also can occur at
2625 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002626 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002627 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002628
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002630 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002631 if (hintDisplay) {
2632 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002633 }
Robert Carr2047fae2016-11-28 14:09:09 -08002634
2635 first = false;
2636 });
Mathias Agopian84300952012-11-21 16:02:13 -08002637 }
2638
2639
Mathias Agopian3559b072012-08-15 13:46:03 -07002640 /*
2641 * Perform our own transaction if needed
2642 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643
2644 if (mLayersAdded) {
2645 mLayersAdded = false;
2646 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002647 mVisibleRegionsDirty = true;
2648 }
2649
2650 // some layers might have been removed, so
2651 // we need to update the regions they're exposing.
2652 if (mLayersRemoved) {
2653 mLayersRemoved = false;
2654 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002655 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002656 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002657 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002658 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002659 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002660 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002661 }
Robert Carr2047fae2016-11-28 14:09:09 -08002662 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 }
2664
Vishnu Nairec0ab382019-02-13 15:32:56 -08002665 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002667}
2668
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002669void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002670 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002671 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002672 return;
2673 }
2674
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002675 if (mVisibleRegionsDirty || mInputInfoChanged) {
2676 mInputInfoChanged = false;
2677 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002678 } else if (mInputWindowCommands.syncInputWindows) {
2679 // If the caller requested to sync input windows, but there are no
2680 // changes to input windows, notify immediately.
2681 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002682 }
2683
Arthur Hung6cbb9752019-09-05 16:38:18 +08002684 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002685}
2686
2687void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002688 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002689
2690 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2691 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002692 // When calculating the screen bounds we ignore the transparent region since it may
2693 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002694 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002695 }
2696 });
chaviw291d88a2019-02-14 10:33:58 -08002697
2698 mInputFlinger->setInputWindows(inputHandles,
2699 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2700 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002701}
2702
Vishnu Nairec0ab382019-02-13 15:32:56 -08002703void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002704 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002705 mPendingInputWindowCommands.clear();
2706}
2707
Riley Andrews03414a12014-07-01 14:22:59 -07002708void SurfaceFlinger::updateCursorAsync()
2709{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002710 compositionengine::CompositionRefreshArgs refreshArgs;
2711 for (const auto& [_, display] : mDisplays) {
2712 if (display->getId()) {
2713 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002714 }
2715 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002716
2717 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718}
2719
Ady Abraham2139f732019-11-13 18:56:40 -08002720void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002721 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2722 // If this is called from the main thread mStateLock must be locked before
2723 // Currently the only way to call this function from the main thread is from
2724 // Sheduler::chooseRefreshRateForContent
2725
2726 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002727 changeRefreshRateLocked(refreshRate, event);
2728}
2729
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002730void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2731 if (mScheduler) {
2732 // In practice it's not allowed to hotplug in/out the primary display once it's been
2733 // connected during startup, but some tests do it, so just warn and return.
2734 ALOGW("Can't re-init scheduler");
2735 return;
2736 }
2737
Ady Abraham2139f732019-11-13 18:56:40 -08002738 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002739 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002740 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002741 primaryDisplayId),
2742 currentConfig);
2743 mRefreshRateStats =
2744 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2745 currentConfig, HWC_POWER_MODE_OFF);
2746 mRefreshRateStats->setConfigMode(currentConfig);
2747
Ady Abraham9e16a482019-12-03 17:19:41 -08002748 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2749
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002750 // start the EventThread
2751 mScheduler =
2752 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002753 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002754 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002755 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002756 impl::EventThread::InterceptVSyncsCallback());
2757 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002758 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002759 [this](nsecs_t timestamp) {
2760 mInterceptor->saveVSyncEvent(timestamp);
2761 });
2762
2763 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2764 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002765 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002766
2767 mRegionSamplingThread =
2768 new RegionSamplingThread(*this, *mScheduler,
2769 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002770 // Dispatch a config change request for the primary display on scheduler
2771 // initialization, so that the EventThreads always contain a reference to a
2772 // prior configuration.
2773 //
2774 // This is a bit hacky, but this avoids a back-pointer into the main SF
2775 // classes from EventThread, and there should be no run-time binder cost
2776 // anyway since there are no connected apps at this point.
2777 const nsecs_t vsyncPeriod =
2778 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2779 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2780 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002781}
2782
Mathias Agopian4fec8732012-06-29 14:12:52 -07002783void SurfaceFlinger::commitTransaction()
2784{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002785 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002786
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002787 mTransactionPending = false;
2788 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002789 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790}
2791
Lloyd Pique58e24a32019-08-01 15:50:14 -07002792void SurfaceFlinger::commitTransactionLocked() {
2793 if (!mLayersPendingRemoval.isEmpty()) {
2794 // Notify removed layers now that they can't be drawn from
2795 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002796 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002797
2798 // Ensure any buffers set to display on any children are released.
2799 if (l->isRemovedFromCurrentState()) {
2800 l->latchAndReleaseBuffer();
2801 }
2802
2803 // If the layer has been removed and has no parent, then it will not be reachable
2804 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2805 // ensure we can copy its current to drawing state.
2806 if (!l->getParent()) {
2807 mOffscreenLayers.emplace(l.get());
2808 }
2809 }
2810 mLayersPendingRemoval.clear();
2811 }
2812
2813 // If this transaction is part of a window animation then the next frame
2814 // we composite should be considered an animation as well.
2815 mAnimCompositionPending = mAnimTransactionPending;
2816
2817 mDrawingState = mCurrentState;
2818 // clear the "changed" flags in current state
2819 mCurrentState.colorMatrixChanged = false;
2820
Edgar Arriaga844fa672020-01-16 14:21:42 -08002821 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002822 layer->commitChildList();
2823
2824 // If the layer can be reached when traversing mDrawingState, then the layer is no
2825 // longer offscreen. Remove the layer from the offscreenLayer set.
2826 if (mOffscreenLayers.count(layer)) {
2827 mOffscreenLayers.erase(layer);
2828 }
2829 });
2830
2831 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002832 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002833}
2834
Nataniel Borges2b796da2019-02-15 13:32:18 -08002835void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2836 if (mTracingEnabledChanged) {
2837 mTracingEnabled = mTracing.isEnabled();
2838 mTracingEnabledChanged = false;
2839 }
2840
2841 // Synchronize with Tracing thread
2842 std::unique_lock<std::mutex> lock;
2843 if (mTracingEnabled) {
2844 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2845 }
2846
2847 lockedOperation();
2848
2849 // Synchronize with Tracing thread
2850 if (mTracingEnabled) {
2851 lock.unlock();
2852 }
2853}
2854
chaviw74d90ad2019-04-26 14:45:26 -07002855void SurfaceFlinger::commitOffscreenLayers() {
2856 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002857 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002858 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2859 if (!trFlags) return;
2860
2861 layer->doTransaction(0);
2862 layer->commitChildList();
2863 });
2864 }
2865}
2866
Chia-I Wuab0c3192017-08-01 11:29:00 -07002867void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002868 for (const auto& [token, displayDevice] : mDisplays) {
2869 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002870 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002871 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002872 }
2873 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002874}
2875
Dan Stoza6b9454d2014-11-07 16:00:59 -08002876bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877{
Ady Abraham09bd3922019-04-08 10:44:56 -07002878 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002879 ALOGV("handlePageFlip");
2880
Brian Andersond6927fb2016-07-23 23:37:30 -07002881 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Mathias Agopian4fec8732012-06-29 14:12:52 -07002883 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002884 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002885 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002886
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002887 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2888
Eric Penner51c59cd2014-07-28 19:51:58 -07002889 // Store the set of layers that need updates. This set must not change as
2890 // buffers are being latched, as this could result in a deadlock.
2891 // Example: Two producers share the same command stream and:
2892 // 1.) Layer 0 is latched
2893 // 2.) Layer 0 gets a new frame
2894 // 2.) Layer 1 gets a new frame
2895 // 3.) Layer 1 is latched.
2896 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2897 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002898 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002899 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002900 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002901 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002902 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002903 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002904 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002905 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002907 } else {
2908 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002909 }
Robert Carr2047fae2016-11-28 14:09:09 -08002910 });
2911
chaviw49a108c2019-08-12 11:23:06 -07002912 // The client can continue submitting buffers for offscreen layers, but they will not
2913 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2914 // layers to ensure dequeueBuffer doesn't block indefinitely.
2915 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002916 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002917 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2918 }
2919
Lloyd Piquef2c79392018-12-20 16:23:33 -08002920 if (!mLayersWithQueuedFrames.empty()) {
2921 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2922 // writes to Layer current state. See also b/119481871
2923 Mutex::Autolock lock(mStateLock);
2924
2925 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002926 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002927 mLayersPendingRefresh.push_back(layer);
2928 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002929 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002930 if (layer->isBufferLatched()) {
2931 newDataLatched = true;
2932 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002933 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002934 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002935
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002936 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002937
2938 // If we will need to wake up at some time in the future to deal with a
2939 // queued frame that shouldn't be displayed during this vsync period, wake
2940 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002941 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002942 signalLayerUpdate();
2943 }
2944
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002945 // enter boot animation on first buffer latch
2946 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2947 ALOGI("Enter boot animation");
2948 mBootStage = BootStage::BOOTANIMATION;
2949 }
2950
Edgar Arriaga844fa672020-01-16 14:21:42 -08002951 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002952
Dan Stoza6b9454d2014-11-07 16:00:59 -08002953 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002954 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955}
2956
Mathias Agopianad456f92011-01-13 17:53:01 -08002957void SurfaceFlinger::invalidateHwcGeometry()
2958{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002959 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002960}
2961
Robert Carrc0df3122019-04-11 13:18:21 -07002962status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2963 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2964 const sp<IBinder>& parentHandle,
2965 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002966 // add this layer to the current state list
2967 {
2968 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002969 sp<Layer> parent;
2970 if (parentHandle != nullptr) {
2971 parent = fromHandle(parentHandle);
2972 if (parent == nullptr) {
2973 return NAME_NOT_FOUND;
2974 }
2975 } else {
2976 parent = parentLayer;
2977 }
2978
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002980 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002981 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002982 return NO_MEMORY;
2983 }
Robert Carrc0df3122019-04-11 13:18:21 -07002984
2985 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2986
Robert Carrb89ea9d2018-12-10 13:01:14 -08002987 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002989 } else if (parent == nullptr) {
2990 lbc->onRemovedFromCurrentState();
2991 } else if (parent->isRemovedFromCurrentState()) {
2992 parent->addChild(lbc);
2993 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002994 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002995 parent->addChild(lbc);
2996 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002997
Yiwei Zhang243b3782018-05-15 17:40:04 -07002998 if (gbc != nullptr) {
2999 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3000 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3001 mMaxGraphicBufferProducerListSize,
3002 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3003 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003004 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003005 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003007 }
3008
Mathias Agopian96f08192010-06-02 23:28:45 -07003009 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003010 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003011
Dan Stoza7d89d062015-04-30 13:29:25 -07003012 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003013}
3014
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003015uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003016 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003017}
3018
Mathias Agopian3f844832013-08-07 21:24:32 -07003019uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003020 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021}
3022
Mathias Agopian3f844832013-08-07 21:24:32 -07003023uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003024 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003025}
3026
3027uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003028 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003029 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003030 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003031 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003032 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033 }
3034 return old;
3035}
3036
Marissa Wall713b63f2018-10-17 15:42:43 -07003037bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003038 // to prevent onHandleDestroyed from being called while the lock is held,
3039 // we must keep a copy of the transactions (specifically the composer
3040 // states) around outside the scope of the lock
3041 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003042 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003043 {
3044 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003045
Valerie Haufce31b82019-04-30 16:41:14 -07003046 auto it = mTransactionQueues.begin();
3047 while (it != mTransactionQueues.end()) {
3048 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003049
Valerie Haufce31b82019-04-30 16:41:14 -07003050 while (!transactionQueue.empty()) {
3051 const auto& transaction = transactionQueue.front();
3052 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003053 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003054 transaction.states)) {
3055 setTransactionFlags(eTransactionFlushNeeded);
3056 break;
3057 }
3058 transactions.push_back(transaction);
3059 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3060 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003061 transaction.buffer, transaction.postTime,
3062 transaction.privileged, transaction.hasListenerCallbacks,
3063 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003064 transactionQueue.pop();
3065 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003066 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003067
Valerie Haufce31b82019-04-30 16:41:14 -07003068 if (transactionQueue.empty()) {
3069 it = mTransactionQueues.erase(it);
3070 mTransactionCV.broadcast();
3071 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003072 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003073 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003074 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003075 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003076 return flushedATransaction;
3077}
3078
3079bool SurfaceFlinger::transactionFlushNeeded() {
3080 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003081}
3082
chaviwca27f252018-02-06 16:46:39 -08003083
Marissa Wall17b4e452018-12-26 16:32:34 -08003084bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003085 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003086 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003087 if (!useCachedExpectedPresentTime)
3088 populateExpectedPresentTime();
3089
3090 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003091 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3092 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3093 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3094 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3095 return false;
3096 }
3097
Marissa Wall713b63f2018-10-17 15:42:43 -07003098 for (const ComposerState& state : states) {
3099 const layer_state_t& s = state.state;
3100 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3101 continue;
3102 }
3103 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003104 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003105 }
3106 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003107 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003108}
3109
Valerie Hau9dab9732019-08-20 09:29:25 -07003110void SurfaceFlinger::setTransactionState(
3111 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3112 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3113 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3114 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003115 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003116
Valerie Haubc6ddb12019-03-08 11:10:15 -08003117 const int64_t postTime = systemTime();
3118
Robert Carr14167e02019-02-13 13:50:55 -08003119 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3120
Mathias Agopian698c0872011-06-28 19:09:31 -07003121 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003122
Marissa Wall713b63f2018-10-17 15:42:43 -07003123 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003124 auto itr = mTransactionQueues.find(applyToken);
3125 // if this is an animation frame, wait until prior animation frame has
3126 // been applied by SF
3127 if (flags & eAnimation) {
3128 while (itr != mTransactionQueues.end()) {
3129 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3130 if (CC_UNLIKELY(err != NO_ERROR)) {
3131 ALOGW_IF(err == TIMED_OUT,
3132 "setTransactionState timed out "
3133 "waiting for animation frame to apply");
3134 break;
3135 }
3136 itr = mTransactionQueues.find(applyToken);
3137 }
3138 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003139
3140 // Expected present time is computed and cached on invalidate, so it may be stale.
3141 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3142 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003143 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003144 uncacheBuffer, postTime, privileged,
3145 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003146 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003147 return;
3148 }
3149
Valerie Haubc6ddb12019-03-08 11:10:15 -08003150 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003151 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3152 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003153}
3154
Valerie Hau9dab9732019-08-20 09:29:25 -07003155void SurfaceFlinger::applyTransactionState(
3156 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3157 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3158 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3159 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3160 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003161 uint32_t transactionFlags = 0;
3162
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003163 if (flags & eAnimation) {
3164 // For window updates that are part of an animation we must wait for
3165 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003166 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003167 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003168 if (CC_UNLIKELY(err != NO_ERROR)) {
3169 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003170 // caller after a few seconds.
3171 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3172 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003173 mAnimTransactionPending = false;
3174 break;
3175 }
3176 }
3177 }
3178
chaviwca27f252018-02-06 16:46:39 -08003179 for (const DisplayState& display : displays) {
3180 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003181 }
3182
Valerie Hau9dab9732019-08-20 09:29:25 -07003183 // start and end registration for listeners w/ no surface so they can get their callback. Note
3184 // that listeners with SurfaceControls will start registration during setClientStateLocked
3185 // below.
3186 for (const auto& listener : listenerCallbacks) {
3187 mTransactionCompletedThread.startRegistration(listener);
3188 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003189 }
3190
Valerie Hau9dab9732019-08-20 09:29:25 -07003191 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003192 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003193 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003194 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3195 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003196 }
3197
Valerie Hau9dab9732019-08-20 09:29:25 -07003198 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003199 mTransactionCompletedThread.endRegistration(listenerCallback);
3200 }
3201
Marissa Walle2ffb422018-10-12 11:33:52 -07003202 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003203 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003204 mTransactionCompletedThread.sendCallbacks();
3205 }
3206 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003207
chaviw273171b2018-12-26 11:46:30 -08003208 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3209
Marissa Wall947d34e2019-03-29 14:03:53 -07003210 if (uncacheBuffer.isValid()) {
3211 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003212 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003213 }
3214
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003215 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3216 // anyway. This can be used as a flush mechanism for previous async transactions.
3217 // Empty animation transaction can be used to simulate back-pressure, so also force a
3218 // transaction for empty animation transactions.
3219 if (transactionFlags == 0 &&
3220 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003221 transactionFlags = eTransactionNeeded;
3222 }
3223
Marissa Wall06255332019-03-27 13:48:27 -07003224 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3225 // so we don't have to wake up again next frame to preform an uneeded traversal.
3226 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3227 transactionFlags = transactionFlags & (~eTraversalNeeded);
3228 mTraversalNeededMainThread = true;
3229 }
3230
Mathias Agopian386aa982011-11-07 21:58:03 -08003231 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003232 if (mInterceptor->isEnabled()) {
3233 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003234 }
Irvel468051e2016-06-13 16:44:44 -07003235
Mathias Agopian386aa982011-11-07 21:58:03 -08003236 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003237 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3238 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003239 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003240
3241 // if this is a synchronous transaction, wait for it to take effect
3242 // before returning.
3243 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003245 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003246 if (flags & eAnimation) {
3247 mAnimTransactionPending = true;
3248 }
chaviw4fe36852019-04-15 16:25:49 -07003249 if (mPendingInputWindowCommands.syncInputWindows) {
3250 mPendingSyncInputWindows = true;
3251 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003252
3253 // applyTransactionState can be called by either the main SF thread or by
3254 // another process through setTransactionState. While a given process may wish
3255 // to wait on synchronous transactions, the main SF thread should never
3256 // be blocked. Therefore, we only wait if isMainThread is false.
3257 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003258 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3259 if (CC_UNLIKELY(err != NO_ERROR)) {
3260 // just in case something goes wrong in SF, return to the
3261 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3263 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003264 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003265 break;
3266 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003267 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 }
3269}
3270
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003271uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3272 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3273 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003274
Mathias Agopiane57f2922012-08-09 16:29:12 -07003275 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003276 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3277
3278 const uint32_t what = s.what;
3279 if (what & DisplayState::eSurfaceChanged) {
3280 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3281 state.surface = s.surface;
3282 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003283 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003284 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003285 if (what & DisplayState::eLayerStackChanged) {
3286 if (state.layerStack != s.layerStack) {
3287 state.layerStack = s.layerStack;
3288 flags |= eDisplayTransactionNeeded;
3289 }
3290 }
3291 if (what & DisplayState::eDisplayProjectionChanged) {
3292 if (state.orientation != s.orientation) {
3293 state.orientation = s.orientation;
3294 flags |= eDisplayTransactionNeeded;
3295 }
3296 if (state.frame != s.frame) {
3297 state.frame = s.frame;
3298 flags |= eDisplayTransactionNeeded;
3299 }
3300 if (state.viewport != s.viewport) {
3301 state.viewport = s.viewport;
3302 flags |= eDisplayTransactionNeeded;
3303 }
3304 }
3305 if (what & DisplayState::eDisplaySizeChanged) {
3306 if (state.width != s.width) {
3307 state.width = s.width;
3308 flags |= eDisplayTransactionNeeded;
3309 }
3310 if (state.height != s.height) {
3311 state.height = s.height;
3312 flags |= eDisplayTransactionNeeded;
3313 }
3314 }
3315
Mathias Agopiane57f2922012-08-09 16:29:12 -07003316 return flags;
3317}
3318
Robert Carr14167e02019-02-13 13:50:55 -08003319bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003320 IPCThreadState* ipc = IPCThreadState::self();
3321 const int pid = ipc->getCallingPid();
3322 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003323 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003324 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003325 return false;
3326 }
3327 return true;
3328}
3329
Marissa Wall3dad52d2019-03-22 14:03:19 -07003330uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003331 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3332 bool privileged,
3333 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003334 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003335
Valerie Hau9dab9732019-08-20 09:29:25 -07003336 for (auto& listener : s.listeners) {
3337 // note that startRegistration will not re-register if the listener has
3338 // already be registered for a prior surface control
3339 mTransactionCompletedThread.startRegistration(listener);
3340 listenerCallbacks.insert(listener);
3341 }
3342
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003343 sp<Layer> layer = nullptr;
3344 if (s.surface) {
3345 layer = fromHandle(s.surface);
3346 } else {
3347 // The client may provide us a null handle. Treat it as if the layer was removed.
3348 ALOGW("Attempt to set client state with a null layer handle");
3349 }
chaviw8b3871a2017-11-01 17:41:01 -07003350 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003351 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003352 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003353 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003354 }
chaviw8b3871a2017-11-01 17:41:01 -07003355 return 0;
3356 }
3357
chaviw8b3871a2017-11-01 17:41:01 -07003358 uint32_t flags = 0;
3359
Garfield Tan8a3083e2018-12-03 13:21:07 -08003360 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003361
3362 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3363 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003364 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003365 layer->pushPendingState();
3366 }
3367
Valerie Hau871d6352020-01-29 08:44:02 -08003368 // Only set by BLAST adapter layers
3369 if (what & layer_state_t::eProducerDisconnect) {
3370 layer->onDisconnect();
3371 }
3372
chaviw8b3871a2017-11-01 17:41:01 -07003373 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003374 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003375 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003376 }
chaviw8b3871a2017-11-01 17:41:01 -07003377 }
3378 if (what & layer_state_t::eLayerChanged) {
3379 // NOTE: index needs to be calculated before we update the state
3380 const auto& p = layer->getParent();
3381 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003382 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003383 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003384 mCurrentState.layersSortedByZ.removeAt(idx);
3385 mCurrentState.layersSortedByZ.add(layer);
3386 // we need traversal (state changed)
3387 // AND transaction (list changed)
3388 flags |= eTransactionNeeded|eTraversalNeeded;
3389 }
chaviw8b3871a2017-11-01 17:41:01 -07003390 } else {
3391 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003392 flags |= eTransactionNeeded|eTraversalNeeded;
3393 }
3394 }
chaviw8b3871a2017-11-01 17:41:01 -07003395 }
3396 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003397 // NOTE: index needs to be calculated before we update the state
3398 const auto& p = layer->getParent();
3399 if (p == nullptr) {
3400 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3401 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3402 mCurrentState.layersSortedByZ.removeAt(idx);
3403 mCurrentState.layersSortedByZ.add(layer);
3404 // we need traversal (state changed)
3405 // AND transaction (list changed)
3406 flags |= eTransactionNeeded|eTraversalNeeded;
3407 }
3408 } else {
3409 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3410 flags |= eTransactionNeeded|eTraversalNeeded;
3411 }
chaviw8b3871a2017-11-01 17:41:01 -07003412 }
3413 }
3414 if (what & layer_state_t::eSizeChanged) {
3415 if (layer->setSize(s.w, s.h)) {
3416 flags |= eTraversalNeeded;
3417 }
3418 }
3419 if (what & layer_state_t::eAlphaChanged) {
3420 if (layer->setAlpha(s.alpha))
3421 flags |= eTraversalNeeded;
3422 }
3423 if (what & layer_state_t::eColorChanged) {
3424 if (layer->setColor(s.color))
3425 flags |= eTraversalNeeded;
3426 }
Peiyong Lind3788632018-09-18 16:01:31 -07003427 if (what & layer_state_t::eColorTransformChanged) {
3428 if (layer->setColorTransform(s.colorTransform)) {
3429 flags |= eTraversalNeeded;
3430 }
3431 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003432 if (what & layer_state_t::eBackgroundColorChanged) {
3433 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3434 flags |= eTraversalNeeded;
3435 }
3436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003438 // TODO: b/109894387
3439 //
3440 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3441 // rotation. To see the problem observe that if we have a square parent, and a child
3442 // of the same size, then we rotate the child 45 degrees around it's center, the child
3443 // must now be cropped to a non rectangular 8 sided region.
3444 //
3445 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3446 // private API, and the WindowManager only uses rotation in one case, which is on a top
3447 // level layer in which cropping is not an issue.
3448 //
3449 // However given that abuse of rotation matrices could lead to surfaces extending outside
3450 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3451 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3452 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003453 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003454 flags |= eTraversalNeeded;
3455 }
3456 if (what & layer_state_t::eTransparentRegionChanged) {
3457 if (layer->setTransparentRegionHint(s.transparentRegion))
3458 flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eFlagsChanged) {
3461 if (layer->setFlags(s.flags, s.mask))
3462 flags |= eTraversalNeeded;
3463 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003464 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003465 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003466 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003467 if (what & layer_state_t::eCornerRadiusChanged) {
3468 if (layer->setCornerRadius(s.cornerRadius))
3469 flags |= eTraversalNeeded;
3470 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003471 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3472 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 if (what & layer_state_t::eLayerStackChanged) {
3475 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3476 // We only allow setting layer stacks for top level layers,
3477 // everything else inherits layer stack from its parent.
3478 if (layer->hasParent()) {
3479 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003480 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003481 } else if (idx < 0) {
3482 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003483 "that also does not appear in the top level layer list. Something"
3484 " has gone wrong.",
3485 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003486 } else if (layer->setLayerStack(s.layerStack)) {
3487 mCurrentState.layersSortedByZ.removeAt(idx);
3488 mCurrentState.layersSortedByZ.add(layer);
3489 // we need traversal (state changed)
3490 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003491 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003492 }
3493 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003494 if (what & layer_state_t::eDeferTransaction_legacy) {
3495 if (s.barrierHandle_legacy != nullptr) {
3496 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3497 } else if (s.barrierGbp_legacy != nullptr) {
3498 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003499 if (authenticateSurfaceTextureLocked(gbp)) {
3500 const auto& otherLayer =
3501 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003502 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003503 } else {
3504 ALOGE("Attempt to defer transaction to to an"
3505 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003506 }
3507 }
chaviw8b3871a2017-11-01 17:41:01 -07003508 // We don't trigger a traversal here because if no other state is
3509 // changed, we don't want this to cause any more work
3510 }
chaviw8b3871a2017-11-01 17:41:01 -07003511 if (what & layer_state_t::eReparentChildren) {
3512 if (layer->reparentChildren(s.reparentHandle)) {
3513 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003514 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003515 }
chaviw8b3871a2017-11-01 17:41:01 -07003516 if (what & layer_state_t::eDetachChildren) {
3517 layer->detachChildren();
3518 }
3519 if (what & layer_state_t::eOverrideScalingModeChanged) {
3520 layer->setOverrideScalingMode(s.overrideScalingMode);
3521 // We don't trigger a traversal here because if no other state is
3522 // changed, we don't want this to cause any more work
3523 }
Marissa Wall61c58622018-07-18 10:12:20 -07003524 if (what & layer_state_t::eTransformChanged) {
3525 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3526 }
3527 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3528 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3529 flags |= eTraversalNeeded;
3530 }
3531 if (what & layer_state_t::eCropChanged) {
3532 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3533 }
Marissa Wall861616d2018-10-22 12:52:23 -07003534 if (what & layer_state_t::eFrameChanged) {
3535 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3536 }
Marissa Wall61c58622018-07-18 10:12:20 -07003537 if (what & layer_state_t::eAcquireFenceChanged) {
3538 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3539 }
3540 if (what & layer_state_t::eDataspaceChanged) {
3541 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3542 }
3543 if (what & layer_state_t::eHdrMetadataChanged) {
3544 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3545 }
3546 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3547 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3548 }
3549 if (what & layer_state_t::eApiChanged) {
3550 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3551 }
3552 if (what & layer_state_t::eSidebandStreamChanged) {
3553 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3554 }
Robert Carr720e5062018-07-30 17:45:14 -07003555 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003556 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003557 layer->setInputInfo(s.inputInfo);
3558 flags |= eTraversalNeeded;
3559 } else {
3560 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3561 }
Robert Carr720e5062018-07-30 17:45:14 -07003562 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003563 if (what & layer_state_t::eMetadataChanged) {
3564 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3565 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003566 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3567 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3568 flags |= eTraversalNeeded;
3569 }
3570 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003571 if (what & layer_state_t::eShadowRadiusChanged) {
3572 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3573 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003574 if (what & layer_state_t::eFrameRateSelectionPriority) {
3575 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3576 flags |= eTraversalNeeded;
3577 }
3578 }
Steven Thomas3172e202020-01-06 19:25:30 -08003579 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003580 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3581 "SurfaceFlinger::setClientStateLocked") &&
3582 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3583 Layer::FrameRate::convertCompatibility(
3584 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003585 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003586 }
Steven Thomas3172e202020-01-06 19:25:30 -08003587 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003588 // This has to happen after we reparent children because when we reparent to null we remove
3589 // child layers from current state and remove its relative z. If the children are reparented in
3590 // the same transaction, then we have to make sure we reparent the children first so we do not
3591 // lose its relative z order.
3592 if (what & layer_state_t::eReparent) {
3593 bool hadParent = layer->hasParent();
3594 if (layer->reparent(s.parentHandleForChild)) {
3595 if (!hadParent) {
3596 mCurrentState.layersSortedByZ.remove(layer);
3597 }
3598 flags |= eTransactionNeeded | eTraversalNeeded;
3599 }
3600 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003601 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003602 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3603 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003604 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3605 }
3606 }
Marissa Wall78b72202019-03-15 14:58:34 -07003607 bool bufferChanged = what & layer_state_t::eBufferChanged;
3608 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3609 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003610 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003611 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003612 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3613 if (success) {
3614 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3615 success = ClientCache::getInstance()
3616 .registerErasedRecipient(s.cachedBuffer,
3617 wp<ClientCache::ErasedRecipient>(this));
3618 if (!success) {
3619 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3620 }
3621 }
Marissa Wall78b72202019-03-15 14:58:34 -07003622 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003623 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003624 } else if (bufferChanged) {
3625 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003626 }
Marissa Wall78b72202019-03-15 14:58:34 -07003627 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003628 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3629 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003630 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003631 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003632 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003633 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3634 // Do not put anything that updates layer state or modifies flags after
3635 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003636 return flags;
3637}
3638
chaviw273171b2018-12-26 11:46:30 -08003639uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3640 uint32_t flags = 0;
3641 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3642 flags |= eTraversalNeeded;
3643 }
3644
chaviwa911b102019-02-14 10:18:33 -08003645 if (inputWindowCommands.syncInputWindows) {
3646 flags |= eTraversalNeeded;
3647 }
3648
Vishnu Nairec0ab382019-02-13 15:32:56 -08003649 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003650 return flags;
3651}
3652
chaviwfe94a222019-08-21 13:52:59 -07003653status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3654 sp<IBinder>* outHandle) {
3655 if (!mirrorFromHandle) {
3656 return NAME_NOT_FOUND;
3657 }
3658
3659 sp<Layer> mirrorLayer;
3660 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003661 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003662
3663 {
3664 Mutex::Autolock _l(mStateLock);
3665 mirrorFrom = fromHandle(mirrorFromHandle);
3666 if (!mirrorFrom) {
3667 return NAME_NOT_FOUND;
3668 }
3669
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003670 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3671 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003672 if (result != NO_ERROR) {
3673 return result;
3674 }
3675
3676 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3677 }
3678
3679 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3680}
3681
Marissa Wall2d814fb2019-04-09 18:52:57 +00003682status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3683 uint32_t h, PixelFormat format, uint32_t flags,
3684 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003685 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003686 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3687 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003688 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003689 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003690 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003692 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003693
Robert Carrc0df3122019-04-11 13:18:21 -07003694 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3695 "Expected only one of parentLayer or parentHandle to be non-null. "
3696 "Programmer error?");
3697
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003698 status_t result = NO_ERROR;
3699
3700 sp<Layer> layer;
3701
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003702 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003703
Evan Roskya1f1e152019-01-24 16:17:46 -08003704 bool primaryDisplayOnly = false;
3705
3706 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3707 // TODO b/64227542
3708 if (metadata.has(METADATA_WINDOW_TYPE)) {
3709 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3710 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003711 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003712 primaryDisplayOnly = true;
3713 }
3714 }
3715
Mathias Agopian3165cc22012-08-08 19:42:09 -07003716 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003717 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003718 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3719 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003720
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003721 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003722 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003723 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003724 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003725 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003726 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003727 // check if buffer size is set for color layer.
3728 if (w > 0 || h > 0) {
3729 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3730 int(w), int(h));
3731 return BAD_VALUE;
3732 }
3733
Vishnu Nairfa247b12020-02-11 08:58:26 -08003734 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3735 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003736 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003737 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003738 // check if buffer size is set for container layer.
3739 if (w > 0 || h > 0) {
3740 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3741 int(w), int(h));
3742 return BAD_VALUE;
3743 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003744 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3745 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003746 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003747 default:
3748 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003749 break;
3750 }
3751
Dan Stoza7d89d062015-04-30 13:29:25 -07003752 if (result != NO_ERROR) {
3753 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003754 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003755
Evan Roskya1f1e152019-01-24 16:17:46 -08003756 if (primaryDisplayOnly) {
3757 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003758 }
3759
Robert Carrb89ea9d2018-12-10 13:01:14 -08003760 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003761 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3762 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003763 if (result != NO_ERROR) {
3764 return result;
3765 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003766 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003767
3768 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003769 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003770}
3771
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003772std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3773 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003774
3775 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003776 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003777
Dan Stoza436ccf32018-06-21 12:10:12 -07003778 // Grab the state lock since we're accessing mCurrentState
3779 Mutex::Autolock lock(mStateLock);
3780
Cody Northropbc755282017-03-31 12:00:08 -06003781 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003782 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003783 while (matchFound) {
3784 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003785 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003786 if (layer->getName() == uniqueName) {
3787 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003788 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003789 }
3790 });
3791 }
3792
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003793 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003794 return uniqueName;
3795}
3796
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003797status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003798 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003799 LayerMetadata metadata, PixelFormat& format,
3800 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003801 sp<IGraphicBufferProducer>* gbp,
3802 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003803 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003804 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 case PIXEL_FORMAT_TRANSPARENT:
3806 case PIXEL_FORMAT_TRANSLUCENT:
3807 format = PIXEL_FORMAT_RGBA_8888;
3808 break;
3809 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003810 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 break;
3812 }
3813
chaviwb4c6e582019-08-16 14:35:07 -07003814 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003815 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003816 args.textureName = getNewTexture();
3817 {
3818 // Grab the SF state lock during this since it's the only safe way to access
3819 // RenderEngine when creating a BufferLayerConsumer
3820 // TODO: Check if this lock is still needed here
3821 Mutex::Autolock lock(mStateLock);
3822 layer = getFactory().createBufferQueueLayer(args);
3823 }
3824
Marissa Wallfd668622018-05-10 10:21:13 -07003825 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003826 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003827 *handle = layer->getHandle();
3828 *gbp = layer->getProducer();
3829 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003831
Marissa Wallfd668622018-05-10 10:21:13 -07003832 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003833 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003834}
3835
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003836status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003837 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003838 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003839 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003840 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003841 args.displayDevice = getDefaultDisplayDevice();
3842 args.textureName = getNewTexture();
3843 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003844 if (outTransformHint) {
3845 *outTransformHint = layer->getTransformHint();
3846 }
Marissa Wall61c58622018-07-18 10:12:20 -07003847 *handle = layer->getHandle();
3848 *outLayer = layer;
3849
3850 return NO_ERROR;
3851}
3852
Vishnu Nairfa247b12020-02-11 08:58:26 -08003853status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3854 uint32_t h, uint32_t flags, LayerMetadata metadata,
3855 sp<IBinder>* handle, sp<Layer>* outLayer) {
3856 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003857 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003858 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003859 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003860}
3861
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003862status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003863 uint32_t w, uint32_t h, uint32_t flags,
3864 LayerMetadata metadata, sp<IBinder>* handle,
3865 sp<Layer>* outLayer) {
3866 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003867 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003868 *handle = (*outLayer)->getHandle();
3869 return NO_ERROR;
3870}
3871
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003872void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003873 mLayersPendingRemoval.add(layer);
3874 mLayersRemoved = true;
3875 setTransactionFlags(eTransactionNeeded);
3876}
3877
Robert Carr695d5282018-12-18 15:27:58 -08003878void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003879{
Robert Carr2e102c92018-10-23 12:11:15 -07003880 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003881 // If a layer has a parent, we allow it to out-live it's handle
3882 // with the idea that the parent holds a reference and will eventually
3883 // be cleaned up. However no one cleans up the top-level so we do so
3884 // here.
3885 if (layer->getParent() == nullptr) {
3886 mCurrentState.layersSortedByZ.remove(layer);
3887 }
3888 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003889
3890 auto it = mLayersByLocalBinderToken.begin();
3891 while (it != mLayersByLocalBinderToken.end()) {
3892 if (it->second == layer) {
3893 it = mLayersByLocalBinderToken.erase(it);
3894 } else {
3895 it++;
3896 }
3897 }
3898
Robert Carr695d5282018-12-18 15:27:58 -08003899 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003900}
3901
Mathias Agopianb60314a2012-04-10 22:09:54 -07003902// ---------------------------------------------------------------------------
3903
Andy McFadden13a082e2012-08-24 10:16:42 -07003904void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003905 const auto display = getDefaultDisplayDeviceLocked();
3906 if (!display) return;
3907
3908 const sp<IBinder> token = display->getDisplayToken().promote();
3909 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003910
Jesse Hall01e29052013-02-19 16:13:35 -08003911 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003912 Vector<ComposerState> state;
3913 Vector<DisplayState> displays;
3914 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003915 d.what = DisplayState::eDisplayProjectionChanged |
3916 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003917 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003918 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003919 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003920 d.frame.makeInvalid();
3921 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003922 d.width = 0;
3923 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003924 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003925 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3926 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003927
Dominik Laskowskie9774092018-12-11 10:04:24 -08003928 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003929
Dominik Laskowski83b88212018-12-11 13:34:06 -08003930 const nsecs_t vsyncPeriod = getVsyncPeriod();
3931 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003932
Brian Andersond0010582017-03-07 13:20:31 -08003933 // Use phase of 0 since phase is not known.
3934 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003935 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003936 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003937}
3938
3939void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003940 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003941 postMessageAsync(
3942 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003943}
3944
Ady Abraham27c70212019-06-11 10:52:26 -07003945void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3946 if (mHWCVsyncState != enabled) {
3947 getHwComposer().setVsyncEnabled(displayId, enabled);
3948 mHWCVsyncState = enabled;
3949 }
3950}
3951
Dominik Laskowskie9774092018-12-11 10:04:24 -08003952void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003953 if (display->isVirtual()) {
3954 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003955 return;
3956 }
3957
Dominik Laskowski075d3172018-05-24 15:50:06 -07003958 const auto displayId = display->getId();
3959 LOG_ALWAYS_FATAL_IF(!displayId);
3960
Dominik Laskowski34157762018-10-31 13:07:19 -07003961 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003962
3963 int currentMode = display->getPowerMode();
3964 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003965 return;
3966 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003967
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003968 display->setPowerMode(mode);
3969
Lloyd Pique4dccc412018-01-22 17:21:36 -08003970 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003971 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003972 }
3973
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003974 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003975 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003976 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003977 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003978 mScheduler->onScreenAcquired(mAppConnectionHandle);
3979 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003982 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003983 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003984 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003985
3986 struct sched_param param = {0};
3987 param.sched_priority = 1;
3988 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3989 ALOGW("Couldn't set SCHED_FIFO on display on");
3990 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003991 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003992 // Turn off the display
3993 struct sched_param param = {0};
3994 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3995 ALOGW("Couldn't set SCHED_OTHER on display off");
3996 }
3997
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003998 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003999 mScheduler->disableHardwareVsync(true);
4000 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004001 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002
Ady Abraham27c70212019-06-11 10:52:26 -07004003 // Make sure HWVsync is disabled before turning off the display
4004 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4005
Dominik Laskowski075d3172018-05-24 15:50:06 -07004006 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004007 mVisibleRegionsDirty = true;
4008 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004009 } else if (mode == HWC_POWER_MODE_DOZE ||
4010 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004011 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004012 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004013 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004014 mScheduler->onScreenAcquired(mAppConnectionHandle);
4015 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004016 }
4017 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4018 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004019 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004020 mScheduler->disableHardwareVsync(true);
4021 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004022 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004023 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004024 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004025 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004026 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004027 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004028
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004029 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004030 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004031 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004032 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004033 }
4034
Dominik Laskowski34157762018-10-31 13:07:19 -07004035 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004036}
4037
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004038void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004039 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004040 const auto display = getDisplayDevice(displayToken);
4041 if (!display) {
4042 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4043 displayToken.get());
4044 } else if (display->isVirtual()) {
4045 ALOGW("Attempt to set power mode %d for virtual display", mode);
4046 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004047 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004048 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004049 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004050}
4051
4052// ---------------------------------------------------------------------------
4053
Dominik Laskowskic2867142019-01-21 11:33:38 -08004054status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4055 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004056 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004057
Mathias Agopianbd115332013-04-18 16:41:04 -07004058 IPCThreadState* ipc = IPCThreadState::self();
4059 const int pid = ipc->getCallingPid();
4060 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004061
Mathias Agopianbd115332013-04-18 16:41:04 -07004062 if ((uid != AID_SHELL) &&
4063 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004064 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4065 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004067 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004068 // (this would indicate SF is stuck, but we want to be able to
4069 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004070 status_t err = mStateLock.timedLock(s2ns(1));
4071 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004072 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004073 StringAppendF(&result,
4074 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4075 "(no locks held)\n",
4076 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004077 }
4078
Dominik Laskowskic2867142019-01-21 11:33:38 -08004079 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004080 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004081 {"--dispsync"s,
4082 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004083 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004084 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4085 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4086 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4087 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4088 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4089 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004090 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004091 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4092 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004093
Dominik Laskowskic2867142019-01-21 11:33:38 -08004094 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004095
Dominik Laskowski46470112019-08-02 13:13:11 -07004096 const auto it = dumpers.find(flag);
4097 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004098 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004099 } else if (!asProto) {
4100 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004101 }
4102
Mathias Agopian9795c422009-08-26 16:36:26 -07004103 if (locked) {
4104 mStateLock.unlock();
4105 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004106
Dominik Laskowski46470112019-08-02 13:13:11 -07004107 if (it == dumpers.end()) {
4108 const LayersProto layersProto = dumpProtoFromMainThread();
4109 if (asProto) {
4110 result.append(layersProto.SerializeAsString());
4111 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004112 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004113 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4114 result.append(LayerProtoParser::layerTreeToString(layerTree));
4115 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004116 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004117 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004118 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004119 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004120 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 return NO_ERROR;
4122}
4123
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004124status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4125 if (asProto && mTracing.isEnabled()) {
4126 mTracing.writeToFileAsync();
4127 }
4128
4129 return doDump(fd, DumpArgs(), asProto);
4130}
4131
Dominik Laskowskic2867142019-01-21 11:33:38 -08004132void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004133 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004134 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004135}
4136
Dominik Laskowskic2867142019-01-21 11:33:38 -08004137void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004138 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004139
Dominik Laskowskic2867142019-01-21 11:33:38 -08004140 if (args.size() > 1) {
4141 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004142 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004143 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004144 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004145 }
Robert Carr2047fae2016-11-28 14:09:09 -08004146 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004147 } else {
4148 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 }
4150}
4151
Dominik Laskowskic2867142019-01-21 11:33:38 -08004152void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004153 const bool clearAll = args.size() < 2;
4154 const auto name = clearAll ? String8() : String8(args[1]);
4155
Edgar Arriaga844fa672020-01-16 14:21:42 -08004156 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004157 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004158 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004159 }
Robert Carr2047fae2016-11-28 14:09:09 -08004160 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004161
Svetoslavd85084b2014-03-20 10:28:31 -07004162 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004163}
4164
Dominik Laskowskic2867142019-01-21 11:33:38 -08004165void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4166 mTimeStats->parseArgs(asProto, args, result);
4167}
4168
Jamie Gennis6547ff42013-07-16 20:12:42 -07004169// This should only be called from the main thread. Otherwise it would need
4170// the lock and should use mCurrentState rather than mDrawingState.
4171void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004172 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004173 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004174 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004175
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004176 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004177}
4178
Yiwei Zhang5434a782018-12-05 18:06:32 -08004179void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004180 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004181
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004182 if (isLayerTripleBufferingDisabled())
4183 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004184
Yiwei Zhang5434a782018-12-05 18:06:32 -08004185 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4186 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4187 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4188 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4189 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4190 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004191 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004192}
4193
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004194void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004195 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004196
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004197 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004198 result.append("\n");
4199
Ady Abraham9e16a482019-12-03 17:19:41 -08004200 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004201 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004202 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004203 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004204
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004205 HwcConfigIndexType defaultConfig;
4206 float minFps, maxFps;
4207 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004208 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004209 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004210 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004211 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004212 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4213 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004214
Ana Krulecc2870422019-01-29 19:00:58 -08004215 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004216}
4217
Yiwei Zhang5434a782018-12-05 18:06:32 -08004218void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4219 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004220 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4221 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004222 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004223 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004224 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004225 }
David Sodman4a36e932017-11-07 14:29:47 -08004226 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004227 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004228 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004229 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4230 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004231}
4232
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004233void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4234 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004235 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4236 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004237 for (const auto& segment : history) {
4238 if (!segment.usedThirdBuffer) {
4239 stats.twoBufferTime += segment.totalTime;
4240 }
4241 if (segment.occupancyAverage < 1.0f) {
4242 stats.doubleBufferedTime += segment.totalTime;
4243 } else if (segment.occupancyAverage < 2.0f) {
4244 stats.tripleBufferedTime += segment.totalTime;
4245 }
4246 ++stats.numSegments;
4247 stats.totalTime += segment.totalTime;
4248 }
4249}
4250
Yiwei Zhang5434a782018-12-05 18:06:32 -08004251void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4252 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004253
4254 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4255 const size_t count = currentLayers.size();
4256 for (size_t i=0 ; i<count ; i++) {
4257 currentLayers[i]->dumpFrameEvents(result);
4258 }
4259}
4260
Yiwei Zhang5434a782018-12-05 18:06:32 -08004261void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004262 result.append("Buffering stats:\n");
4263 result.append(" [Layer name] <Active time> <Two buffer> "
4264 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004265 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004266 typedef std::tuple<std::string, float, float, float> BufferTuple;
4267 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004268 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004269 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004270 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004271 if (stats.numSegments == 0) {
4272 continue;
4273 }
4274 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4275 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4276 stats.totalTime;
4277 float doubleBufferRatio = static_cast<float>(
4278 stats.doubleBufferedTime) / stats.totalTime;
4279 float tripleBufferRatio = static_cast<float>(
4280 stats.tripleBufferedTime) / stats.totalTime;
4281 sorted.insert({activeTime, {name, twoBufferRatio,
4282 doubleBufferRatio, tripleBufferRatio}});
4283 }
4284 for (const auto& sortedPair : sorted) {
4285 float activeTime = sortedPair.first;
4286 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004287 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4288 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004289 }
4290 result.append("\n");
4291}
4292
Yiwei Zhang5434a782018-12-05 18:06:32 -08004293void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004294 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004295 const auto displayId = display->getId();
4296 if (!displayId) {
4297 continue;
4298 }
4299 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004300 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004301 continue;
4302 }
4303
Yiwei Zhang5434a782018-12-05 18:06:32 -08004304 StringAppendF(&result,
4305 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4306 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004307 uint8_t port;
4308 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004309 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004310 result.append("no identification data\n");
4311 continue;
4312 }
4313
4314 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004315 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004316 continue;
4317 }
4318
4319 const auto edid = parseEdid(data);
4320 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004321 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004322 continue;
4323 }
4324
Yiwei Zhang5434a782018-12-05 18:06:32 -08004325 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004326 result.append(edid->displayName.data(), edid->displayName.length());
4327 result.append("\"\n");
4328 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004329}
4330
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004331void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4332 std::string& result) const {
4333 hwc2_display_t hwcDisplayId;
4334 uint8_t port;
4335 DisplayIdentificationData data;
4336
4337 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4338 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4339 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4340 }
4341}
4342
Yiwei Zhang5434a782018-12-05 18:06:32 -08004343void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004344 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4346 StringAppendF(&result, "DisplayColorSetting: %s\n",
4347 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004348
4349 // TODO: print out if wide-color mode is active or not
4350
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004351 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004352 const auto displayId = display->getId();
4353 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004354 continue;
4355 }
4356
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004358 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004359 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004360 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004361 }
4362
Lloyd Pique32cbe282018-10-19 13:09:22 -07004363 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 StringAppendF(&result, " Current color mode: %s (%d)\n",
4365 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004366 }
4367 result.append("\n");
4368}
4369
Vishnu Nair8406fd72019-07-30 11:29:31 -07004370LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004371 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004372 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4373 layer->writeToProto(layersProto, traceFlags);
4374 }
chaviw1d044282017-09-27 12:19:28 -07004375 return layersProto;
4376}
4377
Vishnu Nair0f085c62019-08-30 08:49:12 -07004378void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4379 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4380 // it.
4381 LayerProto* rootProto = layersProto.add_layers();
4382 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4383 rootProto->set_id(offscreenRootLayerId);
4384 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004385 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004386
4387 for (Layer* offscreenLayer : mOffscreenLayers) {
4388 // Add layer as child of the fake root
4389 rootProto->add_children(offscreenLayer->sequence);
4390
4391 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004392 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004393 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004394 }
4395}
4396
Vishnu Nair8406fd72019-07-30 11:29:31 -07004397LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4398 LayersProto layersProto;
4399 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4400 return layersProto;
4401}
4402
Vishnu Nair0f085c62019-08-30 08:49:12 -07004403void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4404 result.append("Offscreen Layers:\n");
4405 postMessageSync(new LambdaMessage([&]() {
4406 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004407 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004408 layer->dumpCallingUidPid(result);
4409 });
4410 }
4411 }));
4412}
4413
Dominik Laskowskic2867142019-01-21 11:33:38 -08004414void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4415 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 Colorizer colorizer(colorize);
4417
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418 // figure out if we're stuck somewhere
4419 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004421 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4422
4423 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004424 * Dump library configuration.
4425 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004426
4427 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004428 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004429 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004430 appendSfConfigString(result);
4431 appendUiConfigString(result);
4432 appendGuiConfigString(result);
4433 result.append("\n");
4434
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004435 result.append("\nDisplay identification data:\n");
4436 dumpDisplayIdentificationData(result);
4437
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004438 result.append("\nWide-Color information:\n");
4439 dumpWideColorInfo(result);
4440
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004441 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004442 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004443 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004444 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004445 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004446
Andy McFadden41d67d72014-04-25 16:58:34 -07004447 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004448 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004449 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004450 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004451 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004452
Dan Stozab90cf072015-03-05 11:05:59 -08004453 dumpStaticScreenStats(result);
4454 result.append("\n");
4455
Alec Mouri40189b02019-03-05 15:07:54 -08004456 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4457 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4458 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004459
Dan Stozae77c7662016-05-13 11:37:28 -07004460 dumpBufferingStats(result);
4461
Andy McFadden4803b742012-09-24 19:07:20 -07004462 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004463 * Dump the visible layer list
4464 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004466 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4468 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004469 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004470
Chia-I Wu2f884132018-09-13 15:17:58 -07004471 {
Lloyd Pique207def92019-02-28 16:09:52 -08004472 StringAppendF(&result, "Composition layers\n");
4473 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004474 auto* compositionState = layer->getCompositionState();
4475 if (!compositionState) return;
4476
4477 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4478 layer->getDebugName() ? layer->getDebugName()
4479 : "<unknown>");
4480 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004481 });
4482 }
4483
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004485 * Dump Display state
4486 */
4487
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004490 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004491 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004492 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004493 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004494 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004495
4496 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004497 * Dump CompositionEngine state
4498 */
4499
4500 mCompositionEngine->dump(result);
4501
4502 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004503 * Dump SurfaceFlinger global state
4504 */
4505
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004507 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004508 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004510 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004511
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004512 DebugEGLImageTracker::getInstance()->dump(result);
4513
Dominik Laskowski075d3172018-05-24 15:50:06 -07004514 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004515 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4516 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004517 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4518 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004519 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result,
4521 " transaction-flags : %08x\n"
4522 " gpu_to_cpu_unsupported : %d\n",
4523 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004524
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004525 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004526 displayId && getHwComposer().isConnected(*displayId)) {
4527 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 StringAppendF(&result,
4529 " refresh-rate : %f fps\n"
4530 " x-dpi : %f\n"
4531 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004532 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4533 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004534 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537
Dan Stozae22aec72016-08-01 13:20:59 -07004538 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004539 * Tracing state
4540 */
4541 mTracing.dump(result);
4542 result.append("\n");
4543
4544 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004545 * HWC layer minidump
4546 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004547 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004548 const auto displayId = display->getId();
4549 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004550 continue;
4551 }
4552
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004554 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004555 const sp<DisplayDevice> displayDevice = display;
4556 mCurrentState.traverseInZOrder(
4557 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004558 result.append("\n");
4559 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560
4561 /*
4562 * Dump HWComposer state
4563 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004564 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004565 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004566 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004567 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004568 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004569 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004570
4571 /*
4572 * Dump gralloc state
4573 */
4574 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4575 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004576
4577 /*
4578 * Dump VrFlinger state if in use.
4579 */
4580 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4581 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004583 result.append("\n");
4584 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004585
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004586 result.append(mTimeStats->miniDump());
4587 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004588}
4589
Chia-I Wu28f320b2018-05-03 11:02:56 -07004590void SurfaceFlinger::updateColorMatrixLocked() {
4591 mat4 colorMatrix;
4592 if (mGlobalSaturationFactor != 1.0f) {
4593 // Rec.709 luma coefficients
4594 float3 luminance{0.213f, 0.715f, 0.072f};
4595 luminance *= 1.0f - mGlobalSaturationFactor;
4596 mat4 saturationMatrix = mat4(
4597 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4598 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4599 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4600 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4601 );
4602 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4603 } else {
4604 colorMatrix = mClientColorMatrix * mDaltonizer();
4605 }
4606
4607 if (mCurrentState.colorMatrix != colorMatrix) {
4608 mCurrentState.colorMatrix = colorMatrix;
4609 mCurrentState.colorMatrixChanged = true;
4610 setTransactionFlags(eTransactionNeeded);
4611 }
4612}
4613
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004614status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004615#pragma clang diagnostic push
4616#pragma clang diagnostic error "-Wswitch-enum"
4617 switch (static_cast<ISurfaceComposerTag>(code)) {
4618 // These methods should at minimum make sure that the client requested
4619 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004620 case BOOT_FINISHED:
4621 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004622 case CREATE_DISPLAY:
4623 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004624 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004625 case GET_ANIMATION_FRAME_STATS:
4626 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004627 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004628 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004629 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004630 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4631 case SET_AUTO_LOW_LATENCY_MODE:
4632 case GET_GAME_CONTENT_TYPE_SUPPORT:
4633 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004634 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004635 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004636 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004637 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004638 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004639 case NOTIFY_POWER_HINT:
4640 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004641 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4642 IPCThreadState* ipc = IPCThreadState::self();
4643 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4644 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004645 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004646 }
Robert Carr1db73f62016-12-21 12:58:51 -08004647 return OK;
4648 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004649 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004650 IPCThreadState* ipc = IPCThreadState::self();
4651 const int pid = ipc->getCallingPid();
4652 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004653 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4654 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004655 return PERMISSION_DENIED;
4656 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004657 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004659 // Used by apps to hook Choreographer to SurfaceFlinger.
4660 case CREATE_DISPLAY_EVENT_CONNECTION:
4661 // The following calls are currently used by clients that do not
4662 // request necessary permissions. However, they do not expose any secret
4663 // information, so it is OK to pass them.
4664 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004665 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004666 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004667 case GET_PHYSICAL_DISPLAY_IDS:
4668 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004669 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004670 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004671 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004672 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004673 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004674 case GET_DISPLAY_STATS:
4675 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4676 // Calling setTransactionState is safe, because you need to have been
4677 // granted a reference to Client* and Handle* to do anything with it.
4678 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004679 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004680 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004681 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004682 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004683 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004684 // setFrameRate() is deliberately available for apps to call without any
4685 // special permissions.
4686 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004687 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4688 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004689 return OK;
4690 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004691 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004692 case CAPTURE_SCREEN:
4693 case ADD_REGION_SAMPLING_LISTENER:
4694 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004695 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004696 IPCThreadState* ipc = IPCThreadState::self();
4697 const int pid = ipc->getCallingPid();
4698 const int uid = ipc->getCallingUid();
4699 if ((uid != AID_GRAPHICS) &&
4700 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4701 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4702 return PERMISSION_DENIED;
4703 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704 return OK;
4705 }
chaviw93df2ea2019-04-30 16:45:12 -07004706 case CAPTURE_SCREEN_BY_ID: {
4707 IPCThreadState* ipc = IPCThreadState::self();
4708 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004709 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004710 return OK;
4711 }
4712 return PERMISSION_DENIED;
4713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004715
4716 // These codes are used for the IBinder protocol to either interrogate the recipient
4717 // side of the transaction for its canonical interface descriptor or to dump its state.
4718 // We let them pass by default.
4719 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4720 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4721 code == IBinder::SYSPROPS_TRANSACTION) {
4722 return OK;
4723 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004724 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004725 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004726 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004727 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4728 return OK;
4729 }
4730 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4731 return PERMISSION_DENIED;
4732#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004733}
4734
Ana Krulec13be8ad2018-08-21 02:43:56 +00004735status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4736 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004737 status_t credentialCheck = CheckTransactCodeCredentials(code);
4738 if (credentialCheck != OK) {
4739 return credentialCheck;
4740 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004741
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4743 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004744 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004745 IPCThreadState* ipc = IPCThreadState::self();
4746 const int uid = ipc->getCallingUid();
4747 if (CC_UNLIKELY(uid != AID_SYSTEM
4748 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004749 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004750 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004751 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004752 return PERMISSION_DENIED;
4753 }
4754 int n;
4755 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004756 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004757 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 return NO_ERROR;
4759 case 1002: // SHOW_UPDATES
4760 n = data.readInt32();
4761 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004762 invalidateHwcGeometry();
4763 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004764 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004766 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004767 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004768 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004769 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004770 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004771 setTransactionFlags(
4772 eTransactionNeeded|
4773 eDisplayTransactionNeeded|
4774 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004775 return NO_ERROR;
4776 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004777 case 1006:{ // send empty update
4778 signalRefresh();
4779 return NO_ERROR;
4780 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004781 case 1008: // toggle use of hw composer
4782 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004783 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004784 invalidateHwcGeometry();
4785 repaintEverything();
4786 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004787 case 1009: // toggle use of transform hint
4788 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004789 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004790 invalidateHwcGeometry();
4791 repaintEverything();
4792 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004794 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 reply->writeInt32(0);
4796 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004797 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004798 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 return NO_ERROR;
4800 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004801 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004802 if (!display) {
4803 return NAME_NOT_FOUND;
4804 }
4805
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004806 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004807 return NO_ERROR;
4808 }
4809 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004810 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004811 // daltonize
4812 n = data.readInt32();
4813 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004814 case 1:
4815 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4816 break;
4817 case 2:
4818 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4819 break;
4820 case 3:
4821 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4822 break;
4823 default:
4824 mDaltonizer.setType(ColorBlindnessType::None);
4825 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004826 }
4827 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004828 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004829 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004830 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004831 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004832
4833 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004834 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004835 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004836 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004837 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004838 // apply a color matrix
4839 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004840 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004841 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004842 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004843 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004844 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004845 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004846 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004847 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004848 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004849 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004850
4851 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4852 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004853 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004854 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4855 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4856 }
4857
Chia-I Wu28f320b2018-05-03 11:02:56 -07004858 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004859 return NO_ERROR;
4860 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004861 case 1016: { // Unused.
4862 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004863 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004864 case 1017: {
4865 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004866 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004867 return NO_ERROR;
4868 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004869 case 1018: { // Modify Choreographer's phase offset
4870 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004871 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004872 return NO_ERROR;
4873 }
4874 case 1019: { // Modify SurfaceFlinger's phase offset
4875 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004876 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004877 return NO_ERROR;
4878 }
Irvel468051e2016-06-13 16:44:44 -07004879 case 1020: { // Layer updates interceptor
4880 n = data.readInt32();
4881 if (n) {
4882 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004883 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004884 }
4885 else{
4886 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004887 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004888 }
4889 return NO_ERROR;
4890 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004891 case 1021: { // Disable HWC virtual displays
4892 n = data.readInt32();
4893 mUseHwcVirtualDisplays = !n;
4894 return NO_ERROR;
4895 }
Romain Guy0147a172017-06-01 13:53:56 -07004896 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004898 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004899
Chia-I Wu28f320b2018-05-03 11:02:56 -07004900 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004901 return NO_ERROR;
4902 }
Romain Guy54f154a2017-10-24 21:40:32 +01004903 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004904 int32_t colorMode;
4905
Chia-I Wu0d711262018-05-21 15:19:35 -07004906 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004907 if (data.readInt32(&colorMode) == NO_ERROR) {
4908 mForceColorMode = static_cast<ColorMode>(colorMode);
4909 }
Romain Guy54f154a2017-10-24 21:40:32 +01004910 invalidateHwcGeometry();
4911 repaintEverything();
4912 return NO_ERROR;
4913 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004914 // Deprecate, use 1030 to check whether the device is color managed.
4915 case 1024: {
4916 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004917 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004918 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004919 n = data.readInt32();
4920 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004921 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004922 Mutex::Autolock lock(mStateLock);
4923 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004924 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004925 reply->writeInt32(NO_ERROR);
4926 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004927 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004928 bool writeFile = false;
4929 {
4930 Mutex::Autolock lock(mStateLock);
4931 mTracingEnabledChanged = true;
4932 writeFile = mTracing.disable();
4933 }
4934
4935 if (writeFile) {
4936 reply->writeInt32(mTracing.writeToFile());
4937 } else {
4938 reply->writeInt32(NO_ERROR);
4939 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004940 }
4941 return NO_ERROR;
4942 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004943 case 1026: { // Get layer tracing status
4944 reply->writeBool(mTracing.isEnabled());
4945 return NO_ERROR;
4946 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004947 // Is a DisplayColorSetting supported?
4948 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004949 const auto display = getDefaultDisplayDevice();
4950 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004951 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004952 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004953
4954 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4955 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004956 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004957 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004958 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004959 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004960 reply->writeBool(true);
4961 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004962 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004963 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004964 break;
4965 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004966 reply->writeBool(
4967 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004968 break;
4969 }
4970 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004971 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004972 // Is VrFlinger active?
4973 case 1028: {
4974 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004975 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004976 return NO_ERROR;
4977 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004978 // Set buffer size for SF tracing (value in KB)
4979 case 1029: {
4980 n = data.readInt32();
4981 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4982 ALOGW("Invalid buffer size: %d KB", n);
4983 reply->writeInt32(BAD_VALUE);
4984 return BAD_VALUE;
4985 }
4986
4987 ALOGD("Updating trace buffer to %d KB", n);
4988 mTracing.setBufferSize(n * 1024);
4989 reply->writeInt32(NO_ERROR);
4990 return NO_ERROR;
4991 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004992 // Is device color managed?
4993 case 1030: {
4994 reply->writeBool(useColorManagement);
4995 return NO_ERROR;
4996 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004997 // Override default composition data space
4998 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4999 // && adb shell stop zygote && adb shell start zygote
5000 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5001 // adb shell stop zygote && adb shell start zygote
5002 case 1031: {
5003 Mutex::Autolock _l(mStateLock);
5004 n = data.readInt32();
5005 if (n) {
5006 n = data.readInt32();
5007 if (n) {
5008 Dataspace dataspace = static_cast<Dataspace>(n);
5009 if (!validateCompositionDataspace(dataspace)) {
5010 return BAD_VALUE;
5011 }
5012 mDefaultCompositionDataspace = dataspace;
5013 }
5014 n = data.readInt32();
5015 if (n) {
5016 Dataspace dataspace = static_cast<Dataspace>(n);
5017 if (!validateCompositionDataspace(dataspace)) {
5018 return BAD_VALUE;
5019 }
5020 mWideColorGamutCompositionDataspace = dataspace;
5021 }
5022 } else {
5023 // restore composition data space.
5024 mDefaultCompositionDataspace = defaultCompositionDataspace;
5025 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5026 }
5027 return NO_ERROR;
5028 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005029 // Set trace flags
5030 case 1033: {
5031 n = data.readUint32();
5032 ALOGD("Updating trace flags to 0x%x", n);
5033 mTracing.setTraceFlags(n);
5034 reply->writeInt32(NO_ERROR);
5035 return NO_ERROR;
5036 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005037 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005038 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005039 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005040 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005041 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5042 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005043 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005044 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005045 } else {
5046 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005047 }
5048 return NO_ERROR;
5049 }
Ady Abraham34392f72019-04-10 11:29:27 -07005050 case 1035: {
5051 n = data.readInt32();
5052 mDebugDisplayConfigSetByBackdoor = false;
5053 if (n >= 0) {
5054 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005055 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005056 if (result != NO_ERROR) {
5057 return result;
5058 }
5059 mDebugDisplayConfigSetByBackdoor = true;
5060 }
5061 return NO_ERROR;
5062 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005063 }
5064 }
5065 return err;
5066}
5067
Steven Thomas6d8110b2017-08-31 18:24:21 -07005068void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005069 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005070 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005071}
5072
Ana Krulec7d1d6832018-12-27 11:10:09 -08005073void SurfaceFlinger::repaintEverythingForHWC() {
5074 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005075 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005076}
5077
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005078// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5079class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005080public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005081 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5082 ~WindowDisconnector() {
5083 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005084 }
5085
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005086private:
5087 ANativeWindow* mWindow;
5088 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005089};
5090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005091status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005092 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005093 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5094 const Rect& sourceCrop, uint32_t reqWidth,
5095 uint32_t reqHeight, bool useIdentityTransform,
5096 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005097 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005099 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005100
Dominik Laskowski718f9602019-11-09 20:01:35 -08005101 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5102 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5103 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5104 renderAreaRotation = ui::Transform::ROT_0;
5105 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005106
Chia-I Wu20261cb2018-08-23 12:55:44 -07005107 sp<DisplayDevice> display;
5108 {
5109 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005110
Chia-I Wu20261cb2018-08-23 12:55:44 -07005111 display = getDisplayDeviceLocked(displayToken);
5112 if (!display) return BAD_VALUE;
5113
Chia-I Wucb023152018-08-28 12:57:23 -07005114 // set the requested width/height to the logical display viewport size
5115 // by default
5116 if (reqWidth == 0 || reqHeight == 0) {
5117 reqWidth = uint32_t(display->getViewport().width());
5118 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005119 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005120 }
5121
Peiyong Lin0e003c92018-09-17 11:09:51 -07005122 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005123 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005124
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005125 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5126 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005127 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005128 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005129}
5130
chaviw93df2ea2019-04-30 16:45:12 -07005131static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5132 switch (colorMode) {
5133 case ColorMode::DISPLAY_P3:
5134 case ColorMode::BT2100_PQ:
5135 case ColorMode::BT2100_HLG:
5136 case ColorMode::DISPLAY_BT2020:
5137 return Dataspace::DISPLAY_P3;
5138 default:
5139 return Dataspace::V0_SRGB;
5140 }
5141}
5142
5143const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5144 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5145 if (displayToken) {
5146 return getDisplayDeviceLocked(displayToken);
5147 }
5148 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5149 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005150 return getDisplayByLayerStack(displayOrLayerStack);
5151}
5152
5153const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005154 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005155 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005156 return display;
5157 }
5158 }
5159 return nullptr;
5160}
5161
5162status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5163 sp<GraphicBuffer>* outBuffer) {
5164 sp<DisplayDevice> display;
5165 uint32_t width;
5166 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005167 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005168 {
5169 Mutex::Autolock _l(mStateLock);
5170 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5171 if (!display) {
5172 return BAD_VALUE;
5173 }
5174
5175 width = uint32_t(display->getViewport().width());
5176 height = uint32_t(display->getViewport().height());
5177
Dominik Laskowski718f9602019-11-09 20:01:35 -08005178 const auto orientation = display->getOrientation();
5179 captureOrientation = ui::Transform::toRotationFlags(orientation);
5180
5181 switch (captureOrientation) {
5182 case ui::Transform::ROT_90:
5183 captureOrientation = ui::Transform::ROT_270;
5184 break;
5185
5186 case ui::Transform::ROT_270:
5187 captureOrientation = ui::Transform::ROT_90;
5188 break;
5189
5190 case ui::Transform::ROT_INVALID:
5191 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5192 captureOrientation = ui::Transform::ROT_0;
5193 break;
5194
5195 default:
5196 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005197 }
chaviw93df2ea2019-04-30 16:45:12 -07005198 *outDataspace =
5199 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5200 }
5201
5202 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5203 false /* captureSecureLayers */);
5204
5205 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5206 std::placeholders::_1);
5207 bool ignored = false;
5208 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5209 false /* useIdentityTransform */,
5210 ignored /* outCapturedSecureLayers */);
5211}
5212
Robert Carr866455f2019-04-02 16:28:26 -07005213status_t SurfaceFlinger::captureLayers(
5214 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5215 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5216 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5217 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005218 ATRACE_CALL();
5219
5220 class LayerRenderArea : public RenderArea {
5221 public:
Robert Carr578038f2018-03-09 12:25:24 -08005222 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005223 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005224 bool childrenOnly, const Rect& displayViewport)
5225 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005226 mLayer(layer),
5227 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005228 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005229 mFlinger(flinger),
5230 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005231 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005232 Rect getBounds() const override {
5233 const Layer::State& layerState(mLayer->getDrawingState());
5234 return mLayer->getBufferSize(layerState);
5235 }
Marissa Wall61c58622018-07-18 10:12:20 -07005236 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005237 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005238 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005239 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005240 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005241 }
chaviwa76b2712017-09-20 12:02:26 -07005242 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005243 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005244 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005245 Rect getSourceCrop() const override {
5246 if (mCrop.isEmpty()) {
5247 return getBounds();
5248 } else {
5249 return mCrop;
5250 }
5251 }
Robert Carr578038f2018-03-09 12:25:24 -08005252 class ReparentForDrawing {
5253 public:
5254 const sp<Layer>& oldParent;
5255 const sp<Layer>& newParent;
5256
Vishnu Nair4351ad52019-02-11 14:13:02 -08005257 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5258 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005259 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005260 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005261 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5262 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005263 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005264 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005265 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005266 };
5267
5268 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005269 const Rect sourceCrop = getSourceCrop();
5270 // no need to check rotation because there is none
5271 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5272 sourceCrop.height() != getReqHeight();
5273
Robert Carr578038f2018-03-09 12:25:24 -08005274 if (!mChildrenOnly) {
5275 mTransform = mLayer->getTransform().inverse();
5276 drawLayers();
5277 } else {
5278 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005279 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5280 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005281 // In the "childrenOnly" case we reparent the children to a screenshot
5282 // layer which has no properties set and which does not draw.
5283 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005284 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5285 "Screenshot Parent"s, w, h, 0,
5286 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005287
Vishnu Nair4351ad52019-02-11 14:13:02 -08005288 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005289 drawLayers();
5290 }
5291 }
chaviwa76b2712017-09-20 12:02:26 -07005292
chaviwa76b2712017-09-20 12:02:26 -07005293 private:
chaviw7206d492017-11-10 16:16:12 -08005294 const sp<Layer> mLayer;
5295 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005296
Peiyong Linefefaac2018-08-17 12:27:51 -07005297 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005298 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005299
5300 SurfaceFlinger* mFlinger;
5301 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005302 };
5303
Robert Carrc0df3122019-04-11 13:18:21 -07005304 int reqWidth = 0;
5305 int reqHeight = 0;
5306 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005307 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005308 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005309 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005310 {
5311 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005312
Robert Carrc0df3122019-04-11 13:18:21 -07005313 parent = fromHandle(layerHandleBinder);
5314 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5315 ALOGE("captureLayers called with an invalid or removed parent");
5316 return NAME_NOT_FOUND;
5317 }
5318
5319 const int uid = IPCThreadState::self()->getCallingUid();
5320 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5321 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5322 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5323 return PERMISSION_DENIED;
5324 }
5325
Vishnu Nairefc42e22019-12-03 17:36:12 -08005326 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005327 if (sourceCrop.width() <= 0) {
5328 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005329 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005330 }
5331
5332 if (sourceCrop.height() <= 0) {
5333 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005334 crop.bottom = parentSourceBounds.getHeight();
5335 }
5336
5337 if (crop.isEmpty() || frameScale <= 0.0f) {
5338 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5339 // crop was not specified, or an invalid frame scale was provided.
5340 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005341 }
5342 reqWidth = crop.width() * frameScale;
5343 reqHeight = crop.height() * frameScale;
5344
5345 for (const auto& handle : excludeHandles) {
5346 sp<Layer> excludeLayer = fromHandle(handle);
5347 if (excludeLayer != nullptr) {
5348 excludeLayers.emplace(excludeLayer);
5349 } else {
5350 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5351 return NAME_NOT_FOUND;
5352 }
5353 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005354
5355 auto display = getDisplayByLayerStack(parent->getLayerStack());
5356 if (!display) {
5357 return BAD_VALUE;
5358 }
5359
5360 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005361 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005362
Chia-I Wu20261cb2018-08-23 12:55:44 -07005363 // really small crop or frameScale
5364 if (reqWidth <= 0) {
5365 reqWidth = 1;
5366 }
5367 if (reqHeight <= 0) {
5368 reqHeight = 1;
5369 }
5370
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005371 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5372 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005373 auto traverseLayers = [parent, childrenOnly,
5374 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005375 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5376 if (!layer->isVisible()) {
5377 return;
Robert Carr578038f2018-03-09 12:25:24 -08005378 } else if (childrenOnly && layer == parent.get()) {
5379 return;
chaviwa76b2712017-09-20 12:02:26 -07005380 }
Robert Carr866455f2019-04-02 16:28:26 -07005381
5382 sp<Layer> p = layer;
5383 while (p != nullptr) {
5384 if (excludeLayers.count(p) != 0) {
5385 return;
5386 }
5387 p = p->getParent();
5388 }
5389
chaviwa76b2712017-09-20 12:02:26 -07005390 visitor(layer);
5391 });
5392 };
Robert Carr108b2c72019-04-02 16:32:58 -07005393
5394 bool outCapturedSecureLayers = false;
5395 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5396 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005397}
5398
5399status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5400 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005401 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005402 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005403 bool useIdentityTransform,
5404 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005405 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005406
Peiyong Lin0e003c92018-09-17 11:09:51 -07005407 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005408 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5409 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005410 *outBuffer =
5411 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5412 static_cast<android_pixel_format>(reqPixelFormat), 1,
5413 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005414
Robert Carr108b2c72019-04-02 16:32:58 -07005415 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5416 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005417}
5418
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005419status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5420 TraverseLayersFunction traverseLayers,
5421 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005422 bool useIdentityTransform,
5423 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 // This mutex protects syncFd and captureResult for communication of the return values from the
5425 // main thread back to this Binder thread
5426 std::mutex captureMutex;
5427 std::condition_variable captureCondition;
5428 std::unique_lock<std::mutex> captureLock(captureMutex);
5429 int syncFd = -1;
5430 std::optional<status_t> captureResult;
5431
Robert Carr03480e22018-01-04 16:02:06 -08005432 const int uid = IPCThreadState::self()->getCallingUid();
5433 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5434
Dominik Laskowski8c001672018-05-30 16:52:06 -07005435 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005436 // If there is a refresh pending, bug out early and tell the binder thread to try again
5437 // after the refresh.
5438 if (mRefreshPending) {
5439 ATRACE_NAME("Skipping screenshot for now");
5440 std::unique_lock<std::mutex> captureLock(captureMutex);
5441 captureResult = std::make_optional<status_t>(EAGAIN);
5442 captureCondition.notify_one();
5443 return;
5444 }
5445
5446 status_t result = NO_ERROR;
5447 int fd = -1;
5448 {
5449 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005450 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005451 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005452 useIdentityTransform, forSystem, &fd,
5453 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005454 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005455 }
5456
5457 {
5458 std::unique_lock<std::mutex> captureLock(captureMutex);
5459 syncFd = fd;
5460 captureResult = std::make_optional<status_t>(result);
5461 captureCondition.notify_one();
5462 }
5463 });
5464
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005465 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005466 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005467 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005468 while (*captureResult == EAGAIN) {
5469 captureResult.reset();
5470 result = postMessageAsync(message);
5471 if (result != NO_ERROR) {
5472 return result;
5473 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005474 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005475 }
5476 result = *captureResult;
5477 }
5478
5479 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005480 sync_wait(syncFd, -1);
5481 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005482 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005483
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005485}
5486
chaviwa76b2712017-09-20 12:02:26 -07005487void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005488 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005489 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5490 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005491 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005492
chaviwa76b2712017-09-20 12:02:26 -07005493 const auto reqWidth = renderArea.getReqWidth();
5494 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005495 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005496 const auto transform = renderArea.getTransform();
5497 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005498 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005499
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005500 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005501 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005502
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005503 // assume that bounds are never offset, and that they are the same as the
5504 // buffer bounds.
5505 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005506 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005507 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005508
5509 // Now take into account the rotation flag. We append a transform that
5510 // rotates the layer stack about the origin, then translate by buffer
5511 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005512 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005513 int displacementX = 0;
5514 int displacementY = 0;
5515 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5516 switch (rotation) {
5517 case ui::Transform::ROT_90:
5518 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005519 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005520 break;
5521 case ui::Transform::ROT_180:
5522 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005523 displacementY = renderArea.getBounds().getWidth();
5524 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005525 break;
5526 case ui::Transform::ROT_270:
5527 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005528 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005529 break;
5530 default:
5531 break;
5532 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005533
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005534 // We need to transform the clipping window into the right spot.
5535 // First, rotate the clipping rectangle by the rotation hint to get the
5536 // right orientation
5537 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5538 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5539 const vec4 rotClipTL = rotMatrix * clipTL;
5540 const vec4 rotClipBR = rotMatrix * clipBR;
5541 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5542 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5543 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5544 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5545
5546 // Now reposition the clipping rectangle with the displacement vector
5547 // computed above.
5548 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549 clientCompositionDisplay.clip =
5550 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5551 newClipRight + displacementX, newClipBottom + displacementY);
5552
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005553 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005554 clientCompositionDisplay.globalTransform =
5555 clipTransform * clientCompositionDisplay.globalTransform;
5556
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005557 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5558 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005559
chaviw50da5042018-04-09 13:49:37 -07005560 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005561
Vishnu Nair9b079a22020-01-21 14:36:08 -08005562 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005563 fillLayer.source.buffer.buffer = nullptr;
5564 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5565 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5566 fillLayer.alpha = half(alpha);
5567 clientCompositionLayers.push_back(fillLayer);
5568
5569 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005570 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005571 const bool supportProtectedContent = false;
5572 Region clip(renderArea.getBounds());
5573 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5574 clip,
5575 useIdentityTransform,
5576 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5577 renderArea.isSecure(),
5578 supportProtectedContent,
5579 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005580 displayViewport,
5581 clientCompositionDisplay.outputDataspace,
5582 true, /* realContentIsVisible */
5583 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005584 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005585 std::vector<compositionengine::LayerFE::LayerSettings> results =
5586 layer->prepareClientCompositionList(targetSettings);
5587 clientCompositionLayers.insert(clientCompositionLayers.end(),
5588 std::make_move_iterator(results.begin()),
5589 std::make_move_iterator(results.end()));
5590 results.clear();
5591
chaviwa76b2712017-09-20 12:02:26 -07005592 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005593
Vishnu Nair9b079a22020-01-21 14:36:08 -08005594 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5595 clientCompositionLayers.reserve(clientCompositionLayers.size());
5596 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5597 std::back_inserter(clientCompositionLayerPointers),
5598 [](compositionengine::LayerFE::LayerSettings& settings)
5599 -> renderengine::LayerSettings* { return &settings; });
5600
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005601 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005602 // Use an empty fence for the buffer fence, since we just created the buffer so
5603 // there is no need for synchronization with the GPU.
5604 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005605 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005606 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005607 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005608 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005609
5610 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005611}
5612
chaviwa76b2712017-09-20 12:02:26 -07005613status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5614 TraverseLayersFunction traverseLayers,
5615 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005616 bool useIdentityTransform, bool forSystem,
5617 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005618 ATRACE_CALL();
5619
chaviwa76b2712017-09-20 12:02:26 -07005620 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005621 outCapturedSecureLayers =
5622 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005623 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005624
Robert Carr03480e22018-01-04 16:02:06 -08005625 // We allow the system server to take screenshots of secure layers for
5626 // use in situations like the Screen-rotation animation and place
5627 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005628 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005629 ALOGW("FB is protected: PERMISSION_DENIED");
5630 return PERMISSION_DENIED;
5631 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005632 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005633 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005634}
5635
chaviw95ef3c42019-02-14 10:55:09 -08005636void SurfaceFlinger::setInputWindowsFinished() {
5637 Mutex::Autolock _l(mStateLock);
5638
5639 mPendingSyncInputWindows = false;
5640 mTransactionCV.broadcast();
5641}
chaviw5f21a5e2019-02-14 10:00:34 -08005642
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005643// ---------------------------------------------------------------------------
5644
Edgar Arriaga844fa672020-01-16 14:21:42 -08005645void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5646 layersSortedByZ.traverse(visitor);
5647}
5648
Dan Stoza412903f2017-04-27 13:42:17 -07005649void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5650 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005651}
5652
Dan Stoza412903f2017-04-27 13:42:17 -07005653void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5654 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005655}
5656
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005657void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005658 const LayerVector::Visitor& visitor) {
5659 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005660 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005661 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005662 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005663 continue;
5664 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005665 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005666 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005667 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005668 return;
5669 }
chaviwa76b2712017-09-20 12:02:26 -07005670 if (!layer->isVisible()) {
5671 return;
5672 }
5673 visitor(layer);
5674 });
5675 }
5676}
5677
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005678status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5679 HwcConfigIndexType defaultConfig,
5680 float minRefreshRate,
5681 float maxRefreshRate) {
5682 Mutex::Autolock lock(mStateLock);
5683
Dominik Laskowski22488f62019-03-28 09:53:04 -07005684 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005685 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5686 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5687 // it should go thru setDesiredActiveConfig, similar to primary display.
5688 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5689 const auto displayId = display->getId();
5690 LOG_ALWAYS_FATAL_IF(!displayId);
5691
5692 HWC2::VsyncPeriodChangeConstraints constraints;
5693 constraints.desiredTimeNanos = systemTime();
5694 constraints.seamlessRequired = false;
5695
5696 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005697 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5698 constraints, &timeline) < 0) {
5699 return BAD_VALUE;
5700 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005701 if (timeline.refreshRequired) {
5702 repaintEverythingForHWC();
5703 }
5704
Ady Abrahamdfa37362020-01-21 18:02:39 -08005705 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005706 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005707 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5708 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005709 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005710 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005711 }
5712
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005713 if (mDebugDisplayConfigSetByBackdoor) {
5714 // ignore this request as config is overridden by backdoor
5715 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005716 }
5717
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005718 bool policyChanged;
5719 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5720 &policyChanged) < 0) {
5721 return BAD_VALUE;
5722 }
5723 if (!policyChanged) {
5724 return NO_ERROR;
5725 }
5726
5727 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5728 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005729
5730 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5731 // that listeners that care about a change in allowed configs can get the notification.
5732 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005733 const nsecs_t vsyncPeriod =
5734 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005735 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005736 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005737
Ana Krulec3f6a2062020-01-23 15:48:01 -08005738 auto configId = mScheduler->getPreferredConfigId();
5739 auto preferredRefreshRate = configId
5740 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5741 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5742 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5743 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5744 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5745
5746 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5747 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5748 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005749 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005750 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005751 }
5752
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005753 return NO_ERROR;
5754}
5755
Ana Krulec0782b882019-10-15 17:34:54 -07005756status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005757 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005758 float maxRefreshRate) {
5759 ATRACE_CALL();
5760
5761 if (!displayToken) {
5762 return BAD_VALUE;
5763 }
5764
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005765 status_t result = NO_ERROR;
5766
Ana Krulec234bb162019-11-10 22:55:55 +01005767 postMessageSync(new LambdaMessage([&]() {
5768 const auto display = getDisplayDeviceLocked(displayToken);
5769 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005770 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005771 ALOGE("Attempt to set desired display configs for invalid display token %p",
5772 displayToken.get());
5773 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005774 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005775 ALOGW("Attempt to set desired display configs for virtual display");
5776 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005777 result =
5778 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5779 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005780 }
5781 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005782
5783 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005784}
5785
5786status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005787 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005788 float* outMinRefreshRate,
5789 float* outMaxRefreshRate) {
5790 ATRACE_CALL();
5791
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005792 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005793 return BAD_VALUE;
5794 }
5795
5796 Mutex::Autolock lock(mStateLock);
5797 const auto display = getDisplayDeviceLocked(displayToken);
5798 if (!display) {
5799 return NAME_NOT_FOUND;
5800 }
5801
5802 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005803 HwcConfigIndexType defaultConfig;
5804 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5805 *outDefaultConfig = defaultConfig.value();
5806 return NO_ERROR;
5807 } else if (display->isVirtual()) {
5808 return BAD_VALUE;
5809 } else {
5810 const auto displayId = display->getId();
5811 if (!displayId) {
5812 return BAD_VALUE;
5813 }
5814 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5815 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5816 *outMinRefreshRate = 1e9f / vsyncPeriod;
5817 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5818 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005819 }
Ana Krulec0782b882019-10-15 17:34:54 -07005820}
5821
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005822void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005823 mFlinger->setInputWindowsFinished();
5824}
5825
Robert Carrc0df3122019-04-11 13:18:21 -07005826sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005827 BBinder* b = nullptr;
5828 if (handle) {
5829 b = handle->localBinder();
5830 }
Robert Carrc0df3122019-04-11 13:18:21 -07005831 if (b == nullptr) {
5832 return nullptr;
5833 }
5834 auto it = mLayersByLocalBinderToken.find(b);
5835 if (it != mLayersByLocalBinderToken.end()) {
5836 return it->second.promote();
5837 }
5838 return nullptr;
5839}
5840
Dominik Laskowski75848362019-11-11 17:57:20 -08005841void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005842 mNumLayers++;
5843 mScheduler->registerLayer(layer);
5844}
5845
5846void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5847 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005848 removeFromOffscreenLayers(layer);
5849}
5850
5851// WARNING: ONLY CALL THIS FROM LAYER DTOR
5852// Here we add children in the current state to offscreen layers and remove the
5853// layer itself from the offscreen layer list. Since
5854// this is the dtor, it is safe to access the current state. This keeps us
5855// from dangling children layers such that they are not reachable from the
5856// Drawing state nor the offscreen layer list
5857// See b/141111965
5858void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5859 for (auto& child : layer->getCurrentChildren()) {
5860 mOffscreenLayers.emplace(child.get());
5861 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005862 mOffscreenLayers.erase(layer);
5863}
5864
Alec Mouri4545a8a2019-08-08 20:05:32 -07005865void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5866 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5867}
5868
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005869status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5870 float lightPosY, float lightPosZ,
5871 float lightRadius) {
5872 Mutex::Autolock _l(mStateLock);
5873 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5874 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5875 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5876 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5877 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5878
5879 // these values are overridden when calculating the shadow settings for a layer.
5880 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5881 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005882 return NO_ERROR;
5883}
5884
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005885const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5886 const {
5887 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5888 // on the work to remove the table in that bug rather than adding more to
5889 // it.
5890 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5891 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5892 // supported, and exposed via the
5893 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5894 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5895 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5896 };
5897 return genericLayerMetadataKeyMap;
5898}
5899
Steven Thomas62a4cf82020-01-31 12:04:03 -08005900status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5901 int8_t compatibility) {
5902 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5903 return BAD_VALUE;
5904 }
5905
5906 Mutex::Autolock lock(mStateLock);
5907 if (authenticateSurfaceTextureLocked(surface)) {
5908 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5909 if (layer->setFrameRate(
5910 Layer::FrameRate(frameRate,
5911 Layer::FrameRate::convertCompatibility(compatibility)))) {
5912 setTransactionFlags(eTraversalNeeded);
5913 }
5914 } else {
5915 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5916 return BAD_VALUE;
5917 }
5918 return NO_ERROR;
5919}
5920
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005921} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005922
Mathias Agopian3f844832013-08-07 21:24:32 -07005923#if defined(__gl_h_)
5924#error "don't include gl/gl.h in this file"
5925#endif
5926
5927#if defined(__gl2_h_)
5928#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005929#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005930
5931// TODO(b/129481165): remove the #pragma below and fix conversion issues
5932#pragma clang diagnostic pop // ignored "-Wconversion"