blob: a98ff4fe7c63da65fe60f200780a98791f1369b5 [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080037#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070038#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070043
Lloyd Pique70d91362018-10-18 16:02:55 -070044#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080045#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070047#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080052#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070054#include <gui/DebugEGLImageTracker.h>
55
Andy McFadden4803b742012-09-24 19:07:20 -070056#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070057#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080058#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080059#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080060#include <gui/LayerMetadata.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080061#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070062#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070063#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070064#include <ui/ColorSpace.h>
65#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080066#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/DisplayInfo.h>
68#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070070#include <ui/GraphicBufferAllocator.h>
71#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070072#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070074#include <utils/String16.h>
75#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070076#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080077#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070078#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Mathias Agopian921e6ac2012-07-23 23:11:29 -070080#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070081#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Robert Carr578038f2018-03-09 12:25:24 -080083#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070084#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070085#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020086#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020087#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080088#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080089#include "DisplayDevice.h"
Vishnu Nairfa247b12020-02-11 08:58:26 -080090#include "EffectLayer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070092#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080093#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070094#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070095#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070096#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070098#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099
Steven Thomasb02664d2017-07-26 18:48:28 -0700100#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700101#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700102#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700103#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700104#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700107#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700109#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700110#include "Scheduler/EventControlThread.h"
111#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700112#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700113#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700114#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800115#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700116
Mathias Agopianff2ed702013-09-01 21:36:12 -0700117#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700118
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700119#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800120#include "android-base/stringprintf.h"
121
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800122#include <android/configuration.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800124#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
125#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700126#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900127#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128
chaviw1d044282017-09-27 12:19:28 -0700129#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900130#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700133
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700134using namespace std::string_literals;
135
Jaesoo Lee43518572017-01-23 19:03:16 +0900136using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900137using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900138using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800139
Ady Abraham8532d012019-05-08 14:50:56 -0700140using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800141using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700142using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700143using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800144using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700145using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700146using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900147
Steven Thomasb02664d2017-07-26 18:48:28 -0700148namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700149
150#pragma clang diagnostic push
151#pragma clang diagnostic error "-Wswitch-enum"
152
153bool isWideColorMode(const ColorMode colorMode) {
154 switch (colorMode) {
155 case ColorMode::DISPLAY_P3:
156 case ColorMode::ADOBE_RGB:
157 case ColorMode::DCI_P3:
158 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700159 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700160 case ColorMode::BT2100_PQ:
161 case ColorMode::BT2100_HLG:
162 return true;
163 case ColorMode::NATIVE:
164 case ColorMode::STANDARD_BT601_625:
165 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
166 case ColorMode::STANDARD_BT601_525:
167 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
168 case ColorMode::STANDARD_BT709:
169 case ColorMode::SRGB:
170 return false;
171 }
172 return false;
173}
174
175#pragma clang diagnostic pop
176
Steven Thomasb02664d2017-07-26 18:48:28 -0700177class ConditionalLock {
178public:
179 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
180 if (lock) {
181 mMutex.lock();
182 }
183 }
184 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
185private:
186 Mutex& mMutex;
187 bool mLocked;
188};
Peiyong Linfca547f2018-07-09 13:03:33 -0700189
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800190// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
191constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
192
193float getDensityFromProperty(const char* property, bool required) {
194 char value[PROPERTY_VALUE_MAX];
195 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
196 if (!density && required) {
197 ALOGE("%s must be defined as a build property", property);
198 return FALLBACK_DENSITY;
199 }
200 return density / 160.f;
201}
202
Peiyong Lin9d846a52018-11-05 13:18:20 -0800203// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
204bool validateCompositionDataspace(Dataspace dataspace) {
205 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
206}
207
Steven Thomasb02664d2017-07-26 18:48:28 -0700208} // namespace anonymous
209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210// ---------------------------------------------------------------------------
211
Mathias Agopian99b49842011-06-27 16:05:52 -0700212const String16 sHardwareTest("android.permission.HARDWARE_TEST");
213const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
214const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
215const String16 sDump("android.permission.DUMP");
216
217// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700218int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700219bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800220uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800221bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800222bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800223int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600224bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800225ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700226bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700227bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700228Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
230Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
231ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800232bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700233
Kalle Raitaa099a242017-01-11 11:17:29 -0800234std::string getHwcServiceName() {
235 char value[PROPERTY_VALUE_MAX] = {};
236 property_get("debug.sf.hwc_service_name", value, "default");
237 ALOGI("Using HWComposer service: '%s'", value);
238 return std::string(value);
239}
240
241bool useTrebleTestingOverride() {
242 char value[PROPERTY_VALUE_MAX] = {};
243 property_get("debug.sf.treble_testing_override", value, "false");
244 ALOGI("Treble testing override: '%s'", value);
245 return std::string(value) == "true";
246}
247
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800248std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
249 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800254 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Enhanced");
256 default:
257 return std::string("Unknown ") +
258 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800260}
261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800263
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
265 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700267 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700268 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700269 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700270 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800271 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
272 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800273
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700274SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800275 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800284
Steven Thomas050b2c82017-03-06 11:45:16 -0800285 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 mDefaultCompositionDataspace =
295 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700296 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
297 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 defaultCompositionDataspace = mDefaultCompositionDataspace;
299 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
300 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
301 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
302 wideColorGamutCompositionPixelFormat =
303 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700304
Yichi Chenda901bf2019-06-28 14:58:27 +0800305 mColorSpaceAgnosticDataspace =
306 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800309
Dominik Laskowski718f9602019-11-09 20:01:35 -0800310 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
311 switch (primary_display_orientation(Values::ORIENTATION_0)) {
312 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800314 case Values::ORIENTATION_90:
315 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800317 case Values::ORIENTATION_180:
318 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 case Values::ORIENTATION_270:
321 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
323 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800324 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800325
Sundong Ahn85131bd2019-02-18 15:51:53 +0900326 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 // debugging stuff...
329 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianb4b17302013-03-20 18:36:41 -0700331 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700332 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 property_get("debug.sf.showupdates", value, "0");
335 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700337 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000338
339 // DDMS debugging deprecated (b/120782499)
340 property_get("debug.sf.ddms", value, "0");
341 int debugDdms = atoi(value);
342 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700343
344 property_get("debug.sf.disable_backpressure", value, "0");
345 mPropagateBackpressure = !atoi(value);
346 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700347
Ady Abrahamadb9a992019-09-19 21:21:55 +0000348 property_get("debug.sf.enable_gl_backpressure", value, "0");
349 mPropagateBackpressureClientComposition = atoi(value);
350 ALOGI_IF(mPropagateBackpressureClientComposition,
351 "Enabling backpressure propagation for Client Composition");
352
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800353 property_get("debug.sf.enable_hwc_vds", value, "0");
354 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800355 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800356
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800357 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800358 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800359 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700360
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800361 property_get("ro.surface_flinger.supports_background_blur", value, "0");
362 bool supportsBlurs = atoi(value);
363 property_get("debug.sf.disableBlurs", value, "0");
364 bool disableBlurs = atoi(value);
365 mEnableBlurs = supportsBlurs && !disableBlurs;
366 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
367 disableBlurs);
368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372
Dan Stozaec460082018-12-17 15:35:09 -0800373 property_get("debug.sf.luma_sampling", value, "1");
374 mLumaSampling = atoi(value);
375
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800376 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800377 mDisableClientCompositionCache = atoi(value);
378
Romain Guy11d63f42017-07-20 12:47:14 -0700379 // We should be reading 'persist.sys.sf.color_saturation' here
380 // but since /data may be encrypted, we need to wait until after vold
381 // comes online to attempt to read the property. The property is
382 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800383
384 if (useTrebleTestingOverride()) {
385 // Without the override SurfaceFlinger cannot connect to HIDL
386 // services that are not listed in the manifests. Considered
387 // deriving the setting from the set service name, but it
388 // would be brittle if the name that's not 'default' is used
389 // for production purposes later on.
390 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
391 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800392
393 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800394}
395
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800396void SurfaceFlinger::onFirstRef()
397{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800398 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399}
400
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700401SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402
Dan Stozac7014012014-02-14 15:03:43 -0800403void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404{
405 // the window manager died on us. prepare its eulogy.
406
Andy McFadden13a082e2012-08-24 10:16:42 -0700407 // restore initial conditions (default device unblank, etc)
408 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409
410 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700411 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412}
413
Robert Carr1db73f62016-12-21 12:58:51 -0800414static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700415 status_t err = client->initCheck();
416 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800417 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418 }
Robert Carr1db73f62016-12-21 12:58:51 -0800419 return nullptr;
420}
421
422sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
423 return initClient(new Client(this));
424}
425
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700426sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
427 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700428{
429 class DisplayToken : public BBinder {
430 sp<SurfaceFlinger> flinger;
431 virtual ~DisplayToken() {
432 // no more references, this display must be terminated
433 Mutex::Autolock _l(flinger->mStateLock);
434 flinger->mCurrentState.displays.removeItem(this);
435 flinger->setTransactionFlags(eDisplayTransactionNeeded);
436 }
437 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700438 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 : flinger(flinger) {
440 }
441 };
442
443 sp<BBinder> token = new DisplayToken(this);
444
445 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700446 // Display ID is assigned when virtual display is allocated by HWC.
447 DisplayDeviceState state;
448 state.isSecure = secure;
449 state.displayName = displayName;
450 mCurrentState.displays.add(token, state);
451 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700452 return token;
453}
454
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700455void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700456 Mutex::Autolock _l(mStateLock);
457
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
459 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700460 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 return;
462 }
463
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
465 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700466 ALOGE("destroyDisplay called for non-virtual display");
467 return;
468 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 mInterceptor->saveDisplayDeletion(state.sequenceId);
470 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700471 setTransactionFlags(eDisplayTransactionNeeded);
472}
473
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800474std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
475 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800477 const auto internalDisplayId = getInternalDisplayIdLocked();
478 if (!internalDisplayId) {
479 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480 }
481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482 std::vector<PhysicalDisplayId> displayIds;
483 displayIds.reserve(mPhysicalDisplayTokens.size());
484 displayIds.push_back(internalDisplayId->value);
485
486 for (const auto& [id, token] : mPhysicalDisplayTokens) {
487 if (id != *internalDisplayId) {
488 displayIds.push_back(id.value);
489 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700490 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800492 return displayIds;
493}
494
495sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
496 Mutex::Autolock lock(mStateLock);
497 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498}
499
Ady Abraham37965d42018-11-01 13:43:32 -0700500status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
501 if (!outGetColorManagement) {
502 return BAD_VALUE;
503 }
504 *outGetColorManagement = useColorManagement;
505 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700506}
507
Lloyd Pique441d5042018-10-18 16:49:51 -0700508HWComposer& SurfaceFlinger::getHwComposer() const {
509 return mCompositionEngine->getHwComposer();
510}
511
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700512renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
513 return mCompositionEngine->getRenderEngine();
514}
515
Lloyd Pique70d91362018-10-18 16:02:55 -0700516compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
517 return *mCompositionEngine.get();
518}
519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520void SurfaceFlinger::bootFinished()
521{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700522 if (mStartPropertySetThread->join() != NO_ERROR) {
523 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525 const nsecs_t now = systemTime();
526 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000527 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528
Mikael Pessa90092f42019-08-26 17:22:04 -0700529 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000530 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700531
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700532 // wait patiently for the window manager death
533 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700534 mWindowManager = defaultServiceManager()->getService(name);
535 if (mWindowManager != 0) {
536 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537 }
Robert Carr720e5062018-07-30 17:45:14 -0700538 sp<IBinder> input(defaultServiceManager()->getService(
539 String16("inputflinger")));
540 if (input == nullptr) {
541 ALOGE("Failed to link to input service");
542 } else {
543 mInputFlinger = interface_cast<IInputFlinger>(input);
544 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700545
Steven Thomas050b2c82017-03-06 11:45:16 -0800546 if (mVrFlinger) {
547 mVrFlinger->OnBootFinished();
548 }
549
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700551 // formerly we would just kill the process, but we now ask it to exit so it
552 // can choose where to stop the animation.
553 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700554
555 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
556 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
557 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700558
Ana Krulecbd6654b2019-02-15 15:18:15 -0800559 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800560 readPersistentProperties();
561 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800562
Ady Abraham8a82ba62020-01-17 12:43:17 -0800563 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
564 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
565 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
566 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800567 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568}
569
Dan Stoza436ccf32018-06-21 12:10:12 -0700570uint32_t SurfaceFlinger::getNewTexture() {
571 {
572 std::lock_guard lock(mTexturePoolMutex);
573 if (!mTexturePool.empty()) {
574 uint32_t name = mTexturePool.back();
575 mTexturePool.pop_back();
576 ATRACE_INT("TexturePoolSize", mTexturePool.size());
577 return name;
578 }
579
580 // The pool was too small, so increase it for the future
581 ++mTexturePoolSize;
582 }
583
584 // The pool was empty, so we need to get a new texture name directly using a
585 // blocking call to the main thread
586 uint32_t name = 0;
587 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
588 return name;
589}
590
Mathias Agopian3f844832013-08-07 21:24:32 -0700591void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700592 std::lock_guard lock(mTexturePoolMutex);
593 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
594 // to actually delete this or not based on mTexturePoolSize
595 mTexturePool.push_back(texture);
596 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700597}
598
Wei Wangf9b05ee2017-07-19 20:59:39 -0700599// Do not call property_set on main thread which will be blocked by init
600// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700601void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700602 ALOGI( "SurfaceFlinger's main thread ready to run. "
603 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700604 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800605
Steven Thomasb02664d2017-07-26 18:48:28 -0700606 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700607 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800608 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700609 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
610 renderengine::RenderEngineCreationArgs::Builder()
611 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
612 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
613 .setUseColorManagerment(useColorManagement)
614 .setEnableProtectedContext(enable_protected_contents(false))
615 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800616 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700617 .setContextPriority(useContextPriority
618 ? renderengine::RenderEngine::ContextPriority::HIGH
619 : renderengine::RenderEngine::ContextPriority::MEDIUM)
620 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800621 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700622
623 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
624 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700625 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800626 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800627 // Process any initial hotplug and resulting display changes.
628 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700629 const auto display = getDefaultDisplayDeviceLocked();
630 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700631 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700632 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800633
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700636 // This callback is called from the vr flinger dispatch thread. We
637 // need to call signalTransaction(), which requires holding
638 // mStateLock when we're not on the main thread. Acquiring
639 // mStateLock from the vr flinger dispatch thread might trigger a
640 // deadlock in surface flinger (see b/66916578), so post a message
641 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700642 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700643 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
644 mVrFlingerRequestsDisplay = requestDisplay;
645 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700646 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
649 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700650 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 .value_or(0),
652 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800653 if (!mVrFlinger) {
654 ALOGE("Failed to start vrflinger");
655 }
656 }
657
Mathias Agopian92a979a2012-08-02 18:32:23 -0700658 // initialize our drawing state
659 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700660
Andy McFadden13a082e2012-08-24 10:16:42 -0700661 // set initial conditions (e.g. unblank default device)
662 initializeDisplays();
663
Steven Thomas137d4bc2019-07-25 16:55:14 -0700664 char primeShaderCache[PROPERTY_VALUE_MAX];
665 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
666 if (atoi(primeShaderCache)) {
667 getRenderEngine().primeCache();
668 }
Dan Stoza4e637772016-07-28 13:31:51 -0700669
Wei Wangf9b05ee2017-07-19 20:59:39 -0700670 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700671
672 const bool presentFenceReliable =
673 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
674 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700675
676 if (mStartPropertySetThread->Start() != NO_ERROR) {
677 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800678 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700681}
682
Romain Guy11d63f42017-07-20 12:47:14 -0700683void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700684 Mutex::Autolock _l(mStateLock);
685
Romain Guy11d63f42017-07-20 12:47:14 -0700686 char value[PROPERTY_VALUE_MAX];
687
688 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800689 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700690 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800691 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100692
693 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700694 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800695
696 property_get("persist.sys.sf.color_mode", value, "0");
697 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700698}
699
Mathias Agopiana67e4182012-06-19 17:26:12 -0700700void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800701 // Start boot animation service by setting a property mailbox
702 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800704 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705 if (mStartPropertySetThread->join() != NO_ERROR) {
706 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800707 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700708}
709
Mathias Agopian875d8e12013-06-07 15:35:48 -0700710size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700711 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700712}
713
Mathias Agopian875d8e12013-06-07 15:35:48 -0700714size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700715 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700716}
717
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800718// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800719
Jamie Gennis582270d2011-08-17 18:19:00 -0700720bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800721 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800722 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800723 return authenticateSurfaceTextureLocked(bufferProducer);
724}
725
726bool SurfaceFlinger::authenticateSurfaceTextureLocked(
727 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800728 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800729 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800730}
731
Brian Anderson6b376712017-04-04 10:51:39 -0700732status_t SurfaceFlinger::getSupportedFrameTimestamps(
733 std::vector<FrameEvent>* outSupported) const {
734 *outSupported = {
735 FrameEvent::REQUESTED_PRESENT,
736 FrameEvent::ACQUIRE,
737 FrameEvent::LATCH,
738 FrameEvent::FIRST_REFRESH_START,
739 FrameEvent::LAST_REFRESH_START,
740 FrameEvent::GPU_COMPOSITION_DONE,
741 FrameEvent::DEQUEUE_READY,
742 FrameEvent::RELEASE,
743 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700744 ConditionalLock _l(mStateLock,
745 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700746 if (!getHwComposer().hasCapability(
747 HWC2::Capability::PresentFenceIsNotReliable)) {
748 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
749 }
750 return NO_ERROR;
751}
752
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800753status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
754 if (!displayToken || !state) {
755 return BAD_VALUE;
756 }
757
758 Mutex::Autolock lock(mStateLock);
759
760 const auto display = getDisplayDeviceLocked(displayToken);
761 if (!display) {
762 return NAME_NOT_FOUND;
763 }
764
765 state->layerStack = display->getLayerStack();
766 state->orientation = display->getOrientation();
767
768 const Rect viewport = display->getViewport();
769 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
770
771 return NO_ERROR;
772}
773
774status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
775 if (!displayToken || !info) {
776 return BAD_VALUE;
777 }
778
779 Mutex::Autolock lock(mStateLock);
780
781 const auto display = getDisplayDeviceLocked(displayToken);
782 if (!display) {
783 return NAME_NOT_FOUND;
784 }
785
Dominik Laskowski55c85402020-01-21 16:25:47 -0800786 if (const auto connectionType = display->getConnectionType())
787 info->connectionType = *connectionType;
788 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800789 return INVALID_OPERATION;
790 }
791
792 if (mEmulatedDisplayDensity) {
793 info->density = mEmulatedDisplayDensity;
794 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800795 info->density = info->connectionType == DisplayConnectionType::Internal
796 ? mInternalDisplayDensity
797 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800798 }
799
800 info->secure = display->isSecure();
801
802 return NO_ERROR;
803}
804
Dominik Laskowski22488f62019-03-28 09:53:04 -0700805status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800806 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 return BAD_VALUE;
809 }
810
Dominik Laskowski22488f62019-03-28 09:53:04 -0700811 Mutex::Autolock lock(mStateLock);
812
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800813 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800818 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700819
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700824
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 auto width = hwConfig->getWidth();
826 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800828 auto xDpi = hwConfig->getDpiX();
829 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 if (isInternal &&
832 (internalDisplayOrientation == ui::ROTATION_90 ||
833 internalDisplayOrientation == ui::ROTATION_270)) {
834 std::swap(width, height);
835 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 }
837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800839
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 if (mEmulatedDisplayDensity) {
841 config.xDpi = mEmulatedDisplayDensity;
842 config.yDpi = mEmulatedDisplayDensity;
843 } else {
844 config.xDpi = xDpi;
845 config.yDpi = yDpi;
846 }
847
848 const nsecs_t period = hwConfig->getVsyncPeriod();
849 config.refreshRate = 1e9f / period;
850
851 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
852 config.appVsyncOffset = offsets.late.app;
853 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854
Andy McFadden91b2ca82014-06-13 14:04:23 -0700855 // This is how far in advance a buffer must be queued for
856 // presentation at a given time. If you want a buffer to appear
857 // on the screen at time N, you must submit the buffer before
858 // (N - presentationDeadline).
859 //
860 // Normally it's one full refresh period (to give SF a chance to
861 // latch the buffer), but this can be reduced by configuring a
862 // DispSync offset. Any additional delays introduced by the hardware
863 // composer or panel must be accounted for here.
864 //
865 // We add an additional 1ms to allow for processing time and
866 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700868
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800869 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700870 }
871
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 return NO_ERROR;
873}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700874
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700875status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
876 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700877 return BAD_VALUE;
878 }
879
Ana Krulecc2870422019-01-29 19:00:58 -0800880 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700881 return NO_ERROR;
882}
883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
885 const auto display = getDisplayDevice(displayToken);
886 if (!display) {
887 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800888 return BAD_VALUE;
889 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700890
Steven Thomasc9098452019-09-30 17:15:05 -0700891 if (display->isPrimary()) {
892 std::lock_guard<std::mutex> lock(mActiveConfigLock);
893 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800894 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700895 }
Steven Thomasc9098452019-09-30 17:15:05 -0700896 }
Ady Abraham2139f732019-11-13 18:56:40 -0800897
898 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700899}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700900
Ady Abraham03b02dd2019-03-21 15:40:11 -0700901void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800902 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800903 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
904 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800905
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800906 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800907 // config twice. However event generation config might have changed so we need to update it
908 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800909 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700910 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
911 mDesiredActiveConfig = info;
912 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800913
914 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800915 // This will trigger HWC refresh without resetting the idle timer.
916 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700917 // Start receiving vsync samples now, so that we can detect a period
918 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800919 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700920 // As we called to set period, we will call to onRefreshRateChangeCompleted once
921 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700922 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800923
Ady Abraham9e16a482019-12-03 17:19:41 -0800924 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
925 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700928
929 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800930 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700931 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932}
933
934status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
935 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800936
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100937 if (!displayToken) {
938 return BAD_VALUE;
939 }
Ady Abraham838de062019-02-04 10:24:03 -0800940
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100941 status_t result = NO_ERROR;
942
943 postMessageSync(new LambdaMessage([&]() {
944 const auto display = getDisplayDeviceLocked(displayToken);
945 if (!display) {
946 ALOGE("Attempt to set allowed display configs for invalid display token %p",
947 displayToken.get());
948 result = BAD_VALUE;
949 } else if (display->isVirtual()) {
950 ALOGW("Attempt to set allowed display configs for virtual display");
951 result = BAD_VALUE;
952 } else {
953 HwcConfigIndexType config(mode);
954 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
955 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
956 refreshRate.fps);
957 }
958 }));
959
960 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961}
962
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963void SurfaceFlinger::setActiveConfigInternal() {
964 ATRACE_CALL();
965
Dominik Laskowski22488f62019-03-28 09:53:04 -0700966 const auto display = getDefaultDisplayDeviceLocked();
967 if (!display) {
968 return;
969 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970
Dominik Laskowski22488f62019-03-28 09:53:04 -0700971 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800972 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700973 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 display->setActiveConfig(mUpcomingActiveConfig.configId);
975
Ady Abraham2139f732019-11-13 18:56:40 -0800976 auto refreshRate =
977 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800978 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
979 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800980 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700981
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800982 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700983 const nsecs_t vsyncPeriod =
984 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
985 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800986 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700987 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800988 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
Ady Abraham53852a52019-05-28 18:07:44 -0700991void SurfaceFlinger::desiredActiveConfigChangeDone() {
992 std::lock_guard<std::mutex> lock(mActiveConfigLock);
993 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
994 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700995
Kevin DuBois5988f482020-01-17 09:03:32 -0800996 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800997 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800998 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800999 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1000 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001001}
1002
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001004 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001005 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001007 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001009 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 return true;
1011 }
1012
1013 // We received the present fence from the HWC, so we assume it successfully updated
1014 // the config, hence we update SF.
1015 mCheckPendingFence = false;
1016 setActiveConfigInternal();
1017 }
1018
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 // Store the local variable to release the lock.
1020 ActiveConfigInfo desiredActiveConfig;
1021 {
1022 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001023 if (!mDesiredActiveConfigChanged) {
1024 return false;
1025 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026 desiredActiveConfig = mDesiredActiveConfig;
1027 }
1028
Ady Abraham2139f732019-11-13 18:56:40 -08001029 auto refreshRate =
1030 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1031 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1032 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001033 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1035 // display is not valid or we are already in the requested mode
1036 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001037 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040
Ady Abraham838de062019-02-04 10:24:03 -08001041 // Desired active config was set, it is different than the config currently in use, however
1042 // allowed configs might have change by the time we process the refresh.
1043 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001044 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001045 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001046 return false;
1047 }
Alec Mouri7f015182019-07-11 13:56:22 -07001048
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049 mUpcomingActiveConfig = desiredActiveConfig;
1050 const auto displayId = display->getId();
1051 LOG_ALWAYS_FATAL_IF(!displayId);
1052
Ady Abraham2139f732019-11-13 18:56:40 -08001053 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001055 // TODO(b/142753666) use constrains
1056 HWC2::VsyncPeriodChangeConstraints constraints;
1057 constraints.desiredTimeNanos = systemTime();
1058 constraints.seamlessRequired = false;
1059
1060 HWC2::VsyncPeriodChangeTimeline outTimeline;
1061 auto status =
1062 getHwComposer().setActiveConfigWithConstraints(*displayId,
1063 mUpcomingActiveConfig.configId.value(),
1064 constraints, &outTimeline);
1065 if (status != NO_ERROR) {
1066 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1067 return false;
1068 }
1069
1070 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1071 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001072 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001073 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001074}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1077 Vector<ColorMode>* outColorModes) {
1078 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001079 return BAD_VALUE;
1080 }
1081
Peiyong Lina52f0292018-03-14 17:26:31 -07001082 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001083 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001084 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001085 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1086
1087 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1088 if (!displayId) {
1089 return NAME_NOT_FOUND;
1090 }
1091
Dominik Laskowski075d3172018-05-24 15:50:06 -07001092 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001093 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001094 }
Michael Wright28f24d02016-07-12 13:30:53 -07001095 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001096
1097 // If it's built-in display and the configuration claims it's not wide color capable,
1098 // filter out all wide color modes. The typical reason why this happens is that the
1099 // hardware is not good enough to support GPU composition of wide color, and thus the
1100 // OEMs choose to disable this capability.
1101 if (isInternalDisplay && !hasWideColorDisplay) {
1102 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1103 isWideColorMode);
1104 } else {
1105 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1106 }
Michael Wright28f24d02016-07-12 13:30:53 -07001107
1108 return NO_ERROR;
1109}
1110
Daniel Solomon42d04562019-01-20 21:03:19 -08001111status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1112 ui::DisplayPrimaries &primaries) {
1113 if (!displayToken) {
1114 return BAD_VALUE;
1115 }
1116
1117 // Currently we only support this API for a single internal display.
1118 if (getInternalDisplayToken() != displayToken) {
1119 return BAD_VALUE;
1120 }
1121
1122 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1123 return NO_ERROR;
1124}
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1127 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001128 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001129 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001130 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001131}
1132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001134 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 Vector<ColorMode> modes;
1136 getDisplayColorModes(displayToken, &modes);
1137 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1138 if (mode < ColorMode::NATIVE || !exists) {
1139 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1140 decodeColorMode(mode).c_str(), mode, displayToken.get());
1141 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001142 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143 const auto display = getDisplayDevice(displayToken);
1144 if (!display) {
1145 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1146 decodeColorMode(mode).c_str(), mode, displayToken.get());
1147 } else if (display->isVirtual()) {
1148 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1149 decodeColorMode(mode).c_str(), mode);
1150 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001151 display->getCompositionDisplay()->setColorProfile(
1152 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1153 RenderIntent::COLORIMETRIC,
1154 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 }
1156 }));
1157
Michael Wright28f24d02016-07-12 13:30:53 -07001158 return NO_ERROR;
1159}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001160
Galia Peycheva5492cb52019-10-30 14:13:16 +01001161status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1162 bool* outSupport) const {
1163 Mutex::Autolock _l(mStateLock);
1164
1165 if (!displayToken) {
1166 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1167 return BAD_VALUE;
1168 }
1169 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1170 if (!displayId) {
1171 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1172 displayToken.get());
1173 return NAME_NOT_FOUND;
1174 }
1175 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1176 HWC2::DisplayCapability::AutoLowLatencyMode);
1177 return NO_ERROR;
1178}
1179
1180void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1181 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1182}
1183
1184void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1185 if (!displayToken) {
1186 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1187 return;
1188 }
1189 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1190 if (!displayId) {
1191 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1192 displayToken.get());
1193 return;
1194 }
1195
1196 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1197}
1198
1199status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1200 bool* outSupport) const {
1201 Mutex::Autolock _l(mStateLock);
1202
1203 if (!displayToken) {
1204 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1205 return BAD_VALUE;
1206 }
1207 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1208 if (!displayId) {
1209 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1210 displayToken.get());
1211 return NAME_NOT_FOUND;
1212 }
1213
1214 std::vector<HWC2::ContentType> outSupportedContentTypes;
1215 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1216 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1217 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1218 return NO_ERROR;
1219}
1220
1221void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1222 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1223}
1224
1225void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1226 if (!displayToken) {
1227 ALOGE("setGameContentType() failed. Missing display token.");
1228 return;
1229 }
1230 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1231 if (!displayId) {
1232 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1233 displayToken.get());
1234 return;
1235 }
1236
1237 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1238 getHwComposer().setContentType(*displayId, type);
1239}
1240
Svetoslavd85084b2014-03-20 10:28:31 -07001241status_t SurfaceFlinger::clearAnimationFrameStats() {
1242 Mutex::Autolock _l(mStateLock);
1243 mAnimFrameTracker.clearStats();
1244 return NO_ERROR;
1245}
1246
1247status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1248 Mutex::Autolock _l(mStateLock);
1249 mAnimFrameTracker.getStats(outStats);
1250 return NO_ERROR;
1251}
1252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001253status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1254 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001255 Mutex::Autolock _l(mStateLock);
1256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001257 const auto display = getDisplayDeviceLocked(displayToken);
1258 if (!display) {
1259 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001260 return BAD_VALUE;
1261 }
1262
Peiyong Linfb069302018-04-25 14:34:31 -07001263 // At this point the DisplayDeivce should already be set up,
1264 // meaning the luminance information is already queried from
1265 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001266 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001267 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1268 capabilities.getDesiredMaxLuminance(),
1269 capabilities.getDesiredMaxAverageLuminance(),
1270 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001271
1272 return NO_ERROR;
1273}
1274
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001275status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1276 ui::PixelFormat* outFormat,
1277 ui::Dataspace* outDataspace,
1278 uint8_t* outComponentMask) const {
1279 if (!outFormat || !outDataspace || !outComponentMask) {
1280 return BAD_VALUE;
1281 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001282 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001283 if (!display || !display->getId()) {
1284 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1285 return BAD_VALUE;
1286 }
1287 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1288 outDataspace, outComponentMask);
1289}
1290
Kevin DuBois74e53772018-11-19 10:52:38 -08001291status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1292 bool enable, uint8_t componentMask,
1293 uint64_t maxFrames) const {
1294 const auto display = getDisplayDevice(displayToken);
1295 if (!display || !display->getId()) {
1296 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1297 return BAD_VALUE;
1298 }
1299
1300 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1301 componentMask, maxFrames);
1302}
1303
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001304status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1305 uint64_t maxFrames, uint64_t timestamp,
1306 DisplayedFrameStats* outStats) const {
1307 const auto display = getDisplayDevice(displayToken);
1308 if (!display || !display->getId()) {
1309 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1310 return BAD_VALUE;
1311 }
1312
1313 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1314 outStats);
1315}
1316
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001317status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1318 if (!outSupported) {
1319 return BAD_VALUE;
1320 }
1321 *outSupported = getRenderEngine().supportsProtectedContent();
1322 return NO_ERROR;
1323}
1324
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001325status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1326 bool* outIsWideColorDisplay) const {
1327 if (!displayToken || !outIsWideColorDisplay) {
1328 return BAD_VALUE;
1329 }
1330 Mutex::Autolock _l(mStateLock);
1331 const auto display = getDisplayDeviceLocked(displayToken);
1332 if (!display) {
1333 return BAD_VALUE;
1334 }
Peiyong Linff84a152019-05-17 18:36:19 -07001335
1336 // Use hasWideColorDisplay to override built-in display.
1337 const auto displayId = display->getId();
1338 if (displayId && displayId == getInternalDisplayIdLocked()) {
1339 *outIsWideColorDisplay = hasWideColorDisplay;
1340 return NO_ERROR;
1341 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001342 *outIsWideColorDisplay = display->hasWideColorGamut();
1343 return NO_ERROR;
1344}
1345
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001346status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001347 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001348 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001349
Dominik Laskowski6505f792019-09-18 11:10:05 -07001350 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1351 mEventQueue->setEventConnection(
1352 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001353 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001354 }));
1355
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001356 return NO_ERROR;
1357}
1358
1359status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001360 Mutex::Autolock lock(mStateLock);
1361 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001362}
1363
Lloyd Pique755e3192018-01-31 16:46:15 -08001364status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1365 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001366 // Try to acquire a lock for 1s, fail gracefully
1367 const status_t err = mStateLock.timedLock(s2ns(1));
1368 const bool locked = (err == NO_ERROR);
1369 if (!locked) {
1370 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1371 return TIMED_OUT;
1372 }
1373
1374 outLayers->clear();
1375 mCurrentState.traverseInZOrder([&](Layer* layer) {
1376 outLayers->push_back(layer->getLayerDebugInfo());
1377 });
1378
1379 mStateLock.unlock();
1380 return NO_ERROR;
1381}
1382
Peiyong Linc6780972018-10-28 15:24:08 -07001383status_t SurfaceFlinger::getCompositionPreference(
1384 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1385 Dataspace* outWideColorGamutDataspace,
1386 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001387 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001388 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001389 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001390 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001391 return NO_ERROR;
1392}
1393
Dan Stozaec460082018-12-17 15:35:09 -08001394status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1395 const sp<IBinder>& stopLayerHandle,
1396 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001397 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001398 return BAD_VALUE;
1399 }
1400 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001401 return NO_ERROR;
1402}
1403
Dan Stozaec460082018-12-17 15:35:09 -08001404status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001405 if (!listener) {
1406 return BAD_VALUE;
1407 }
Dan Stozaec460082018-12-17 15:35:09 -08001408 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001409 return NO_ERROR;
1410}
Dan Gittik57e63c52019-01-18 16:37:54 +00001411
1412status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1413 bool* outSupport) const {
1414 if (!displayToken || !outSupport) {
1415 return BAD_VALUE;
1416 }
1417 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1418 if (!displayId) {
1419 return NAME_NOT_FOUND;
1420 }
1421 *outSupport =
1422 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1423 return NO_ERROR;
1424}
1425
1426status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1427 float brightness) const {
1428 if (!displayToken) {
1429 return BAD_VALUE;
1430 }
1431 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1432 if (!displayId) {
1433 return NAME_NOT_FOUND;
1434 }
1435 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1436}
1437
Ady Abraham8532d012019-05-08 14:50:56 -07001438status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1439 PowerHint powerHint = static_cast<PowerHint>(hintId);
1440
1441 if (powerHint == PowerHint::INTERACTION) {
1442 mScheduler->notifyTouchEvent();
1443 }
1444
1445 return NO_ERROR;
1446}
1447
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001448// ----------------------------------------------------------------------------
1449
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001450sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001451 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001452 const auto& handle =
1453 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001454
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001455 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001456}
1457
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459
1460void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001461 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001462}
1463
1464void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001465 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001466 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467}
1468
1469void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001470 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001471 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001472}
1473
1474void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001475 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001476 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001477}
1478
1479status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001480 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001481 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001482}
1483
1484status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001485 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001486 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001487 if (res == NO_ERROR) {
1488 msg->wait();
1489 }
1490 return res;
1491}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001492
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001493void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001494 do {
1495 waitForEvent();
1496 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001497}
1498
Dominik Laskowski83b88212018-12-11 13:34:06 -08001499nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001500 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001501 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1502 return 0;
1503 }
1504
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001505 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001506}
1507
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001508void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001509 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001510 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001511 ATRACE_NAME("SF onVsync");
1512
Steven Thomas3cfac282017-02-06 12:29:30 -08001513 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001514 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001515 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001516 return;
1517 }
1518
Dominik Laskowski075d3172018-05-24 15:50:06 -07001519 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001520 return;
1521 }
1522
Dominik Laskowski075d3172018-05-24 15:50:06 -07001523 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001524 // For now, we don't do anything with external display vsyncs.
1525 return;
1526 }
1527
Alec Mourif8e689c2019-05-20 18:32:22 -07001528 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001529 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001530 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001531 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001532 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001533}
1534
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001536 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1537 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538}
1539
Ady Abraham2139f732019-11-13 18:56:40 -08001540bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001541 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001542}
1543
Ady Abraham2139f732019-11-13 18:56:40 -08001544void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1545 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001546 const auto display = getDefaultDisplayDeviceLocked();
1547 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001548 return;
1549 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001550 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001551
Ana Krulec7d1d6832018-12-27 11:10:09 -08001552 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001553 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1554 ALOGV("Skipping config %d as it is not part of allowed configs",
1555 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001556 return;
1557 }
1558
Ady Abraham2139f732019-11-13 18:56:40 -08001559 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001560}
1561
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001562void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001563 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001564 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001565 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001566
Lloyd Piqueba04e622017-12-14 17:11:26 -08001567 // Ignore events that do not have the right sequenceId.
1568 if (sequenceId != getBE().mComposerSequenceId) {
1569 return;
1570 }
1571
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 // Only lock if we're not on the main thread. This function is normally
1573 // called on a hwbinder thread, but for the primary display it's called on
1574 // the main thread with the state lock already held, so don't attempt to
1575 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001576 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001577
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001578 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001579
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001580 if (std::this_thread::get_id() == mMainThreadId) {
1581 // Process all pending hot plug events immediately if we are on the main thread.
1582 processDisplayHotplugEventsLocked();
1583 }
1584
Lloyd Piqueba04e622017-12-14 17:11:26 -08001585 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001586}
1587
Ady Abraham7159f572019-10-11 11:10:18 -07001588void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001589 int32_t sequenceId, hwc2_display_t /*display*/,
1590 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1591 Mutex::Autolock lock(mStateLock);
1592 if (sequenceId != getBE().mComposerSequenceId) {
1593 return;
1594 }
1595 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001596}
1597
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001598void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1599 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1600 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1601}
1602
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001603void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001604 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001605 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001607 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001608 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001609}
1610
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001611void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001612 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001613
1614 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1615 // display power state.
1616 postMessageAsync(new LambdaMessage(
1617 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1618}
1619
1620void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1621 ATRACE_CALL();
1622
Ady Abraham27c70212019-06-11 10:52:26 -07001623 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1624
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001625 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001626 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1627 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001628 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001629 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001630 }
Mathias Agopian86303202012-07-24 22:46:10 -07001631}
1632
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001633// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001634void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001635 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001636 // Clear the drawing state so that the logic inside of
1637 // handleTransactionLocked will fire. It will determine the delta between
1638 // mCurrentState and mDrawingState and re-apply all changes when we make the
1639 // transition.
1640 mDrawingState.displays.clear();
1641 mDisplays.clear();
1642}
1643
Steven Thomas050b2c82017-03-06 11:45:16 -08001644void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001645 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001646 if (!mVrFlinger)
1647 return;
1648 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001649 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001650 return;
1651 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001652
Lloyd Pique441d5042018-10-18 16:49:51 -07001653 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001654 ALOGE("Vr flinger is only supported for remote hardware composer"
1655 " service connections. Ignoring request to transition to vr"
1656 " flinger.");
1657 mVrFlingerRequestsDisplay = false;
1658 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001659 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001660
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001661 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001662
Steven Thomas0123ac62018-07-12 11:32:34 -07001663 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001664 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001665
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001666 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001667
1668 // Clear out all the output layers from the composition engine for all
1669 // displays before destroying the hardware composer interface. This ensures
1670 // any HWC layers are destroyed through that interface before it becomes
1671 // invalid.
1672 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001673 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001674 }
1675
Steven Thomas0123ac62018-07-12 11:32:34 -07001676 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1677 // called below. Clear the reference now so we don't accidentally use it
1678 // later.
1679 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001680
Steven Thomasb02664d2017-07-26 18:48:28 -07001681 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001682 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001683 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001684
Steven Thomasb02664d2017-07-26 18:48:28 -07001685 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001686 // Delete the current instance before creating the new one
1687 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1688 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1689 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001690 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001691
Lloyd Pique441d5042018-10-18 16:49:51 -07001692 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001693 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001694
1695 if (vrFlingerRequestsDisplay) {
1696 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001697 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001698
1699 mVisibleRegionsDirty = true;
1700 invalidateHwcGeometry();
1701
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001702 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001703 display = getDefaultDisplayDeviceLocked();
1704 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001705 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001706
Steven Thomasb02664d2017-07-26 18:48:28 -07001707 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001708 const nsecs_t vsyncPeriod = getVsyncPeriod();
1709 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001710
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001711 // The present fences returned from vr_hwc are not an accurate
1712 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001713 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001714
Steven Thomasb02664d2017-07-26 18:48:28 -07001715 // Use phase of 0 since phase is not known.
1716 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001717 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001718 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001719
Ana Krulecc2870422019-01-29 19:00:58 -08001720 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001721
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001722 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001723 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001724}
1725
Ady Abraham11579302019-09-19 12:35:58 -07001726bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1727 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001728 // We are storing the last 2 present fences. If sf's phase offset is to be
1729 // woken up before the actual vsync but targeting the next vsync, we need to check
1730 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001731 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1732 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001733
Ady Abraham11579302019-09-19 12:35:58 -07001734 if (fence == Fence::NO_FENCE) {
1735 return false;
1736 }
1737
1738 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1739 fence->wait(graceTimeMs);
1740 }
1741
1742 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001743}
1744
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001745void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001746 DisplayStatInfo stats;
1747 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001748 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001749 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001750 mExpectedPresentTime.store(
1751 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001752}
1753
Dominik Laskowski22488f62019-03-28 09:53:04 -07001754void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001755 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001756 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001757 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001758 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001759 // calculate the expected present time once and use the cached
1760 // value throughout this frame to make sure all layers are
1761 // seeing this same value.
1762 populateExpectedPresentTime();
1763
Ady Abraham11579302019-09-19 12:35:58 -07001764 // When Backpressure propagation is enabled we want to give a small grace period
1765 // for the present fence to fire instead of just giving up on this frame to handle cases
1766 // where present fence is just about to get signaled.
1767 const int graceTimeForPresentFenceMs =
1768 (mPropagateBackpressure &&
1769 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1770 ? 1
1771 : 0;
1772 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1773 previousFrameMissed(
1774 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001775 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1776 mHadDeviceComposition && frameMissed};
1777 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1778 mHadClientComposition && frameMissed};
1779
Alec Mouricc0fc602019-02-26 21:45:19 -08001780 if (frameMissed) {
1781 mFrameMissedCount++;
1782 mTimeStats->incrementMissedFrames();
1783 }
1784
Alec Mouri40189b02019-03-05 15:07:54 -08001785 if (hwcFrameMissed) {
1786 mHwcFrameMissedCount++;
1787 }
1788
1789 if (gpuFrameMissed) {
1790 mGpuFrameMissedCount++;
1791 }
1792
Ady Abrahamadb9a992019-09-19 21:21:55 +00001793 if (frameMissed && mPropagateBackpressure) {
1794 if ((hwcFrameMissed && !gpuFrameMissed) ||
1795 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001796 signalLayerUpdate();
1797 break;
1798 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001799 }
Dan Stoza50182882016-07-08 12:02:20 -07001800
Steven Thomas050b2c82017-03-06 11:45:16 -08001801 // Now that we're going to make it to the handleMessageTransaction()
1802 // call below it's safe to call updateVrFlinger(), which will
1803 // potentially trigger a display handoff.
1804 updateVrFlinger();
1805
Dan Stoza6b9454d2014-11-07 16:00:59 -08001806 bool refreshNeeded = handleMessageTransaction();
1807 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001808
Ana Krulecc84d09b2019-11-02 23:10:29 +01001809 // Layers need to get updated (in the previous line) before we can use them for
1810 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001811 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1812 // and may eventually call to ~Layer() if it holds the last reference
1813 {
1814 Mutex::Autolock _l(mStateLock);
1815 mScheduler->chooseRefreshRateForContent();
1816 }
1817
Ana Krulecc84d09b2019-11-02 23:10:29 +01001818 if (performSetActiveConfig()) {
1819 break;
1820 }
1821
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001822 updateCursorAsync();
1823 updateInputFlinger();
1824
Dan Stoza58784442014-12-02 16:58:17 -08001825 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001826 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001827 // Signal a refresh if a transaction modified the window state,
1828 // a new buffer was latched, or if HWC has requested a full
1829 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001830 if (mFrameStartTime <= 0) {
1831 // We should only use the time of the first invalidate
1832 // message that signals a refresh as the beginning of the
1833 // frame. Otherwise the real frame time will be
1834 // underestimated.
1835 mFrameStartTime = frameStart;
1836 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001837 signalRefresh();
1838 }
1839 break;
1840 }
1841 case MessageQueue::REFRESH: {
1842 handleMessageRefresh();
1843 break;
1844 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001845 }
1846}
1847
Dan Stoza6b9454d2014-11-07 16:00:59 -08001848bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001849 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001850 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001851
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001852 bool flushedATransaction = flushTransactionQueues();
1853
1854 bool runHandleTransaction = transactionFlags &&
1855 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1856
1857 if (runHandleTransaction) {
1858 handleTransaction(eTransactionMask);
1859 } else {
1860 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001861 }
1862
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001863 if (transactionFlushNeeded()) {
1864 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001865 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001866
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001867 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001868}
1869
Mathias Agopian4fec8732012-06-29 14:12:52 -07001870void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001872
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001873 mRefreshPending = false;
1874
Lloyd Piqueab039b52019-02-13 14:22:42 -08001875 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001876 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001877 for (const auto& [_, display] : mDisplays) {
1878 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1879 }
1880 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001881 if (auto layerFE = layer->getCompositionEngineLayerFE())
1882 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001883 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001884 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1885 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001886 if (auto layerFE = layer->getCompositionEngineLayerFE())
1887 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001888 }
1889
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001890 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001891 refreshArgs.outputColorSetting = useColorManagement
1892 ? mDisplayColorSetting
1893 : compositionengine::OutputColorSetting::kUnmanaged;
1894 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1895 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001896
1897 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1898 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001899
1900 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1901 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1902 mDrawingState.colorMatrixChanged = false;
1903 }
1904
1905 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1906
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001907 if (mDebugRegion != 0) {
1908 refreshArgs.devOptFlashDirtyRegionsDelay =
1909 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1910 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001911
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001912 mGeometryInvalid = false;
1913
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001914 // Store the present time just before calling to the composition engine so we could notify
1915 // the scheduler.
1916 const auto presentTime = systemTime();
1917
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001918 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001919 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1920 // Reset the frame start time now that we've recorded this frame.
1921 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001922
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001923 mScheduler->onDisplayRefreshed(presentTime);
1924
David Sodmanfa9b2af2017-12-24 13:28:59 -08001925 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001926 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001927
Lloyd Pique66d68602019-02-13 14:23:31 -08001928 mHadClientComposition =
1929 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1930 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001931 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1932 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001933 });
1934 mHadDeviceComposition =
1935 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1936 auto& displayDevice = tokenDisplayPair.second;
1937 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1938 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001939 mReusedClientComposition =
1940 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1941 auto& displayDevice = tokenDisplayPair.second;
1942 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1943 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001944
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001945 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001946
David Sodman7e4ae112018-02-09 15:02:28 -08001947 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001948 if (mVisibleRegionsDirty) {
1949 mVisibleRegionsDirty = false;
1950 if (mTracingEnabled) {
1951 mTracing.notify("visibleRegionsDirty");
1952 }
1953 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001954
1955 if (mCompositionEngine->needsAnotherUpdate()) {
1956 signalLayerUpdate();
1957 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001959
David Sodmanfa9b2af2017-12-24 13:28:59 -08001960
1961bool SurfaceFlinger::handleMessageInvalidate() {
1962 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001963 bool refreshNeeded = handlePageFlip();
1964
Vishnu Nair4351ad52019-02-11 14:13:02 -08001965 if (mVisibleRegionsDirty) {
1966 computeLayerBounds();
1967 }
1968
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001969 for (auto& layer : mLayersPendingRefresh) {
1970 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001971 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001972 invalidateLayerStack(layer, visibleReg);
1973 }
1974 mLayersPendingRefresh.clear();
1975 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001976}
1977
Ana Krulece588e312018-09-18 12:32:24 -07001978void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1979 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980 // Update queue of past composite+present times and determine the
1981 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001982 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001984 while (!getBE().mCompositePresentTimes.empty()) {
1985 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986 // Cached values should have been updated before calling this method,
1987 // which helps avoid duplicate syscalls.
1988 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1989 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1990 break;
1991 }
1992 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001993 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994 }
1995
1996 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001997 while (getBE().mCompositePresentTimes.size() > 16) {
1998 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001999 }
2000
Ana Krulece588e312018-09-18 12:32:24 -07002001 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002002}
2003
Ana Krulece588e312018-09-18 12:32:24 -07002004void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2005 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002006 // Integer division and modulo round toward 0 not -inf, so we need to
2007 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002008 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2009 ? (stats.vsyncPeriod -
2010 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2011 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002012
Ady Abraham9e16a482019-12-03 17:19:41 -08002013 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002014 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002015 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002016 }
2017
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 // Snap the latency to a value that removes scheduling jitter from the
2019 // composition and present times, which often have >1ms of jitter.
2020 // Reducing jitter is important if an app attempts to extrapolate
2021 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002022 // Snapping also allows an app to precisely calculate
2023 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002024 nsecs_t bias = stats.vsyncPeriod / 2;
2025 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2026 nsecs_t snappedCompositeToPresentLatency =
2027 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028
David Sodman99974d22017-11-28 12:04:33 -08002029 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002030 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2031 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002032 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033}
2034
David Sodman2b406362017-12-15 13:33:47 -08002035void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002036{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 ATRACE_CALL();
2038 ALOGV("postComposition");
2039
Brian Andersonf6386862016-10-31 16:34:13 -07002040 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002041 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002042 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002043 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002044 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002045 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046
David Sodman73beded2017-11-15 11:56:06 -08002047 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002048 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002049 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002050 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002051 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2052 ->getRenderSurface()
2053 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002054 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055 } else {
2056 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2057 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002058
David Sodman73beded2017-11-15 11:56:06 -08002059 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002060 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2061 mPreviousPresentFences[0] = displayDevice
2062 ? getHwComposer().getPresentFence(*displayDevice->getId())
2063 : Fence::NO_FENCE;
2064 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002065 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002066
Ana Krulece588e312018-09-18 12:32:24 -07002067 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002068 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069
Lloyd Piqueab039b52019-02-13 14:22:42 -08002070 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2071 // be sampled a little later than when we started doing work for this frame,
2072 // but that should be okay since updateCompositorTiming has snapping logic.
2073 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2074 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002075 CompositorTiming compositorTiming;
2076 {
David Sodman99974d22017-11-28 12:04:33 -08002077 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2078 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002079 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002080
Edgar Arriaga844fa672020-01-16 14:21:42 -08002081 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002082 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2083 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002084 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002085 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002086 }
Robert Carr2047fae2016-11-28 14:09:09 -08002087 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088
Ady Abraham92fa2f42020-02-11 15:33:56 -08002089 if (displayDevice && displayDevice->isPrimary() &&
2090 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002091 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002092 }
2093
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002094 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002095 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2096 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002097 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002098 }
2099 }
2100
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002101 if (mAnimCompositionPending) {
2102 mAnimCompositionPending = false;
2103
Brian Anderson4e606e32017-03-16 15:34:57 -07002104 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002105 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002106 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002107 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002108 // The HWC doesn't support present fences, so use the refresh
2109 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002110 const nsecs_t presentTime =
2111 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002112 mAnimFrameTracker.setActualPresentTime(presentTime);
2113 }
2114 mAnimFrameTracker.advanceFrame();
2115 }
Dan Stozab90cf072015-03-05 11:05:59 -08002116
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002117 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002118 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002119 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002120 }
2121
Vishnu Nair9b079a22020-01-21 14:36:08 -08002122 if (mReusedClientComposition) {
2123 mTimeStats->incrementClientCompositionReusedFrames();
2124 }
2125
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002126 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002127
Alec Mouri717bcb62020-02-10 17:07:19 -08002128 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2129 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2130 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2131
Lloyd Pique32cbe282018-10-19 13:09:22 -07002132 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2133 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002134 return;
2135 }
2136
2137 nsecs_t currentTime = systemTime();
2138 if (mHasPoweredOff) {
2139 mHasPoweredOff = false;
2140 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002141 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002142 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002143 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2144 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002145 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002146 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002147 }
David Sodman4a36e932017-11-07 14:29:47 -08002148 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002149 }
David Sodman4a36e932017-11-07 14:29:47 -08002150 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002151
2152 {
2153 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002154 if (mTexturePool.size() < mTexturePoolSize) {
2155 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002156 const size_t offset = mTexturePool.size();
2157 mTexturePool.resize(mTexturePoolSize);
2158 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2159 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002160 } else if (mTexturePool.size() > mTexturePoolSize) {
2161 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2162 const size_t offset = mTexturePoolSize;
2163 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2164 mTexturePool.resize(mTexturePoolSize);
2165 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002166 }
2167 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002168
Ady Abrahambe0f9482019-04-24 15:41:53 -07002169 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002170 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002171
Kevin DuBois413287f2019-02-25 08:46:47 -08002172 if (mLumaSampling && mRegionSamplingThread) {
2173 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002174 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002175
2176 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2177 // side-effect of getTotalSize(), so we check that again here
2178 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002179 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002180 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2181 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002182}
2183
Vishnu Nair4351ad52019-02-11 14:13:02 -08002184void SurfaceFlinger::computeLayerBounds() {
2185 for (const auto& pair : mDisplays) {
2186 const auto& displayDevice = pair.second;
2187 const auto display = displayDevice->getCompositionDisplay();
2188 for (const auto& layer : mDrawingState.layersSortedByZ) {
2189 // only consider the layers on the given layer stack
2190 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002191 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002192 }
2193
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002194 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2195 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002196 }
2197 }
2198}
2199
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200void SurfaceFlinger::postFrame()
2201{
2202 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002203 const auto display = getDefaultDisplayDeviceLocked();
2204 if (display && getHwComposer().isConnected(*display->getId())) {
2205 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002206 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2207 logFrameStats();
2208 }
2209 }
2210}
2211
Mathias Agopian87baae12012-07-31 12:38:26 -07002212void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002213{
Mathias Agopian841cde52012-03-01 15:44:37 -08002214 ATRACE_CALL();
2215
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002216 // here we keep a copy of the drawing state (that is the state that's
2217 // going to be overwritten by handleTransactionLocked()) outside of
2218 // mStateLock so that the side-effects of the State assignment
2219 // don't happen with mStateLock held (which can cause deadlocks).
2220 State drawingState(mDrawingState);
2221
Mathias Agopianca4d3602011-05-19 15:38:14 -07002222 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002223 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224
Mathias Agopianca4d3602011-05-19 15:38:14 -07002225 // Here we're guaranteed that some transaction flags are set
2226 // so we can call handleTransactionLocked() unconditionally.
2227 // We call getTransactionFlags(), which will also clear the flags,
2228 // with mStateLock held to guarantee that mCurrentState won't change
2229 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002230
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002231 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002232 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002233 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002234
Mathias Agopianca4d3602011-05-19 15:38:14 -07002235 mDebugInTransaction = 0;
2236 invalidateHwcGeometry();
2237 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002238}
2239
Lloyd Piqueba04e622017-12-14 17:11:26 -08002240void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2241 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002242 const std::optional<DisplayIdentificationInfo> info =
2243 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002244
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002246 continue;
2247 }
2248
Dominik Laskowski55c85402020-01-21 16:25:47 -08002249 const DisplayId displayId = info->id;
2250 const auto it = mPhysicalDisplayTokens.find(displayId);
2251
Lloyd Piqueba04e622017-12-14 17:11:26 -08002252 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002253 if (it == mPhysicalDisplayTokens.end()) {
2254 ALOGV("Creating display %s", to_string(displayId).c_str());
2255
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002256 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002257 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002258 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002259
Dominik Laskowski075d3172018-05-24 15:50:06 -07002260 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002261 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 state.isSecure = true; // All physical displays are currently considered secure.
2263 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002264
2265 sp<IBinder> token = new BBinder();
2266 mCurrentState.displays.add(token, state);
2267 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2268
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002270 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002271 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002272 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002273
Dominik Laskowski55c85402020-01-21 16:25:47 -08002274 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002275 if (index >= 0) {
2276 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2277 mInterceptor->saveDisplayDeletion(state.sequenceId);
2278 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002279 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002280 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002281 }
2282
2283 processDisplayChangesLocked();
2284 }
2285
2286 mPendingHotplugEvents.clear();
2287}
2288
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002289void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002290 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2291 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002292}
2293
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002295 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002296 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002297 const sp<IGraphicBufferProducer>& producer) {
2298 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002299 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002300 creationArgs.isSecure = state.isSecure;
2301 creationArgs.displaySurface = dispSurface;
2302 creationArgs.hasWideColorGamut = false;
2303 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002304 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305
Dominik Laskowski55c85402020-01-21 16:25:47 -08002306 if (const auto& physical = state.physical) {
2307 creationArgs.connectionType = physical->type;
2308 }
2309
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002310 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002311 creationArgs.isPrimary = isInternalDisplay;
2312
2313 if (useColorManagement && displayId) {
2314 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002316 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002317 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319
Dominik Laskowski7e045462018-05-30 13:02:02 -07002320 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002321 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002322 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323 }
tangrobin6753a022018-08-10 10:58:54 +08002324 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325
Dominik Laskowski075d3172018-05-24 15:50:06 -07002326 if (displayId) {
2327 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002328 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002330 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002331
Lloyd Pique90c115d2018-09-18 21:39:42 -07002332 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002334 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335
Lloyd Pique99d3da52018-01-22 17:48:03 -08002336 // Make sure that composition can never be stalled by a virtual display
2337 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002338 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002339 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2341 }
2342
Dominik Laskowski718f9602019-11-09 20:01:35 -08002343 creationArgs.physicalOrientation =
2344 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002345
Lloyd Pique99d3da52018-01-22 17:48:03 -08002346 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002347 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002348
Lloyd Pique90c115d2018-09-18 21:39:42 -07002349 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002350
2351 if (maxFrameBufferAcquiredBuffers >= 3) {
2352 nativeWindowSurface->preallocateBuffers();
2353 }
2354
2355 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002356 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002357 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002359 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002361 display->getCompositionDisplay()->setColorProfile(
2362 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2363 RenderIntent::COLORIMETRIC,
2364 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 if (!state.isVirtual()) {
2366 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002367 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2368 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002369 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 display->setLayerStack(state.layerStack);
2372 display->setProjection(state.orientation, state.viewport, state.frame);
2373 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002375 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002376}
2377
Lloyd Pique347200f2017-12-14 17:00:15 -08002378void SurfaceFlinger::processDisplayChangesLocked() {
2379 // here we take advantage of Vector's copy-on-write semantics to
2380 // improve performance by skipping the transaction entirely when
2381 // know that the lists are identical
2382 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2383 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2384 if (!curr.isIdenticalTo(draw)) {
2385 mVisibleRegionsDirty = true;
2386 const size_t cc = curr.size();
2387 size_t dc = draw.size();
2388
2389 // find the displays that were removed
2390 // (ie: in drawing state but not in current state)
2391 // also handle displays that changed
2392 // (ie: displays that are in both lists)
2393 for (size_t i = 0; i < dc;) {
2394 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2395 if (j < 0) {
2396 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002397 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002398 // Save display ID before disconnecting.
2399 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002400 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002401
2402 if (!display->isVirtual()) {
2403 LOG_ALWAYS_FATAL_IF(!displayId);
2404 dispatchDisplayHotplugEvent(displayId->value, false);
2405 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002407
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002408 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002409 } else {
2410 // this display is in both lists. see if something changed.
2411 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002413 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2414 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2415 if (state_binder != draw_binder) {
2416 // changing the surface is like destroying and
2417 // recreating the DisplayDevice, so we just remove it
2418 // from the drawing state, so that it get re-added
2419 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002420 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002421 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002422 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002423 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002424 mDrawingState.displays.removeItemsAt(i);
2425 dc--;
2426 // at this point we must loop to the next item
2427 continue;
2428 }
2429
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002430 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002433 }
2434 if ((state.orientation != draw[i].orientation) ||
2435 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002436 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002437 }
2438 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002440 if (display->isPrimary()) {
2441 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2442 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 }
2444 }
2445 }
2446 ++i;
2447 }
2448
2449 // find displays that were added
2450 // (ie: in current state but not in drawing state)
2451 for (size_t i = 0; i < cc; i++) {
2452 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2453 const DisplayDeviceState& state(curr[i]);
2454
Lloyd Pique542307f2018-10-19 13:24:08 -07002455 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002456 sp<IGraphicBufferProducer> producer;
2457 sp<IGraphicBufferProducer> bqProducer;
2458 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002459 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002460
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002462 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002463 // Virtual displays without a surface are dormant:
2464 // they have external state (layer stack, projection,
2465 // etc.) but no internal state (i.e. a DisplayDevice).
2466 if (state.surface != nullptr) {
2467 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002469 int width = 0;
2470 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2471 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2472 int height = 0;
2473 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2474 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2475 int intFormat = 0;
2476 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2477 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002478 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002479
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 displayId =
2481 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 }
2483
2484 // TODO: Plumb requested format back up to consumer
2485
2486 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002488 bqProducer, bqConsumer,
2489 state.displayName);
2490
2491 dispSurface = vds;
2492 producer = vds;
2493 }
2494 } else {
2495 ALOGE_IF(state.surface != nullptr,
2496 "adding a supported display, but rendering "
2497 "surface is provided (%p), ignoring it",
2498 state.surface.get());
2499
Dominik Laskowski55c85402020-01-21 16:25:47 -08002500 LOG_FATAL_IF(!state.physical);
2501 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 producer = bqProducer;
2504 }
2505
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002508 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002509 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002510 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002511 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002512 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002513 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002515
2516 const auto displayDevice = mDisplays[displayToken];
2517 if (displayDevice->isPrimary()) {
2518 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2519 displayDevice->getHeight());
2520 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 }
2522 }
2523 }
2524 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002525
2526 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002527}
2528
Mathias Agopian87baae12012-07-31 12:38:26 -07002529void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002530{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002531 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2532
Dan Stoza7dde5992015-05-22 09:51:44 -07002533 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002534 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002535 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002536 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 /*
2539 * Traversal of the children
2540 * (perform the transaction for each of them if needed)
2541 */
2542
Marissa Wall06255332019-03-27 13:48:27 -07002543 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002544 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002546 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547
2548 const uint32_t flags = layer->doTransaction(0);
2549 if (flags & Layer::eVisibleRegion)
2550 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002551
2552 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002553 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002554 }
Robert Carr2047fae2016-11-28 14:09:09 -08002555 });
Marissa Wall06255332019-03-27 13:48:27 -07002556 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 }
2558
2559 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002560 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 */
2562
Mathias Agopiane57f2922012-08-09 16:29:12 -07002563 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002565 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002568 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002569 // The transform hint might have changed for some layers
2570 // (either because a display has changed, or because a layer
2571 // as changed).
2572 //
2573 // Walk through all the layers in currentLayers,
2574 // and update their transform hint.
2575 //
2576 // If a layer is visible only on a single display, then that
2577 // display is used to calculate the hint, otherwise we use the
2578 // default display.
2579 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002580 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002581 // the hint is set before we acquire a buffer from the surface texture.
2582 //
2583 // NOTE: layer transactions have taken place already, so we use their
2584 // drawing state. However, SurfaceFlinger's own transaction has not
2585 // happened yet, so we must use the current state layer list
2586 // (soon to become the drawing state list).
2587 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002589 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002590 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002591 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002592 // NOTE: we rely on the fact that layers are sorted by
2593 // layerStack first (so we don't have to traverse the list
2594 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002595 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002596 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002597 currentlayerStack = layerStack;
2598 // figure out if this layerstack is mirrored
2599 // (more than one display) if so, pick the default display,
2600 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002601 hintDisplay = nullptr;
2602 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002603 if (display->getCompositionDisplay()
2604 ->belongsInOutput(layer->getLayerStack(),
2605 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002606 if (hintDisplay) {
2607 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002608 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002609 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002610 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002611 }
2612 }
2613 }
2614 }
Chet Haase91d25932013-04-11 15:24:55 -07002615
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002616 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002617 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2618 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002619
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002620 // could be null when this layer is using a layerStack
2621 // that is not visible on any display. Also can occur at
2622 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002623 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002624 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002625
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002626 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002627 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002628 if (hintDisplay) {
2629 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002630 }
Robert Carr2047fae2016-11-28 14:09:09 -08002631
2632 first = false;
2633 });
Mathias Agopian84300952012-11-21 16:02:13 -08002634 }
2635
2636
Mathias Agopian3559b072012-08-15 13:46:03 -07002637 /*
2638 * Perform our own transaction if needed
2639 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002640
2641 if (mLayersAdded) {
2642 mLayersAdded = false;
2643 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002644 mVisibleRegionsDirty = true;
2645 }
2646
2647 // some layers might have been removed, so
2648 // we need to update the regions they're exposing.
2649 if (mLayersRemoved) {
2650 mLayersRemoved = false;
2651 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002652 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002654 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002656 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002657 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002658 }
Robert Carr2047fae2016-11-28 14:09:09 -08002659 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 }
2661
Vishnu Nairec0ab382019-02-13 15:32:56 -08002662 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002664}
2665
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002666void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002667 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002668 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002669 return;
2670 }
2671
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002672 if (mVisibleRegionsDirty || mInputInfoChanged) {
2673 mInputInfoChanged = false;
2674 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002675 } else if (mInputWindowCommands.syncInputWindows) {
2676 // If the caller requested to sync input windows, but there are no
2677 // changes to input windows, notify immediately.
2678 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002679 }
2680
Arthur Hung6cbb9752019-09-05 16:38:18 +08002681 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002682}
2683
2684void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002685 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002686
2687 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2688 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002689 // When calculating the screen bounds we ignore the transparent region since it may
2690 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002691 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002692 }
2693 });
chaviw291d88a2019-02-14 10:33:58 -08002694
2695 mInputFlinger->setInputWindows(inputHandles,
2696 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2697 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002698}
2699
Vishnu Nairec0ab382019-02-13 15:32:56 -08002700void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002701 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002702 mPendingInputWindowCommands.clear();
2703}
2704
Riley Andrews03414a12014-07-01 14:22:59 -07002705void SurfaceFlinger::updateCursorAsync()
2706{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002707 compositionengine::CompositionRefreshArgs refreshArgs;
2708 for (const auto& [_, display] : mDisplays) {
2709 if (display->getId()) {
2710 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002711 }
2712 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002713
2714 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002715}
2716
Ady Abraham2139f732019-11-13 18:56:40 -08002717void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002718 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2719 // If this is called from the main thread mStateLock must be locked before
2720 // Currently the only way to call this function from the main thread is from
2721 // Sheduler::chooseRefreshRateForContent
2722
2723 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002724 changeRefreshRateLocked(refreshRate, event);
2725}
2726
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002727void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2728 if (mScheduler) {
2729 // In practice it's not allowed to hotplug in/out the primary display once it's been
2730 // connected during startup, but some tests do it, so just warn and return.
2731 ALOGW("Can't re-init scheduler");
2732 return;
2733 }
2734
Ady Abraham2139f732019-11-13 18:56:40 -08002735 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002736 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002737 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002738 primaryDisplayId),
2739 currentConfig);
2740 mRefreshRateStats =
2741 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2742 currentConfig, HWC_POWER_MODE_OFF);
2743 mRefreshRateStats->setConfigMode(currentConfig);
2744
Ady Abraham9e16a482019-12-03 17:19:41 -08002745 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2746
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002747 // start the EventThread
2748 mScheduler =
2749 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002750 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002751 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002752 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002753 impl::EventThread::InterceptVSyncsCallback());
2754 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002755 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002756 [this](nsecs_t timestamp) {
2757 mInterceptor->saveVSyncEvent(timestamp);
2758 });
2759
2760 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2761 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002762 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002763
2764 mRegionSamplingThread =
2765 new RegionSamplingThread(*this, *mScheduler,
2766 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002767 // Dispatch a config change request for the primary display on scheduler
2768 // initialization, so that the EventThreads always contain a reference to a
2769 // prior configuration.
2770 //
2771 // This is a bit hacky, but this avoids a back-pointer into the main SF
2772 // classes from EventThread, and there should be no run-time binder cost
2773 // anyway since there are no connected apps at this point.
2774 const nsecs_t vsyncPeriod =
2775 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2776 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2777 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002778}
2779
Mathias Agopian4fec8732012-06-29 14:12:52 -07002780void SurfaceFlinger::commitTransaction()
2781{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002782 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002783
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002784 mTransactionPending = false;
2785 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002786 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787}
2788
Lloyd Pique58e24a32019-08-01 15:50:14 -07002789void SurfaceFlinger::commitTransactionLocked() {
2790 if (!mLayersPendingRemoval.isEmpty()) {
2791 // Notify removed layers now that they can't be drawn from
2792 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002793 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002794
2795 // Ensure any buffers set to display on any children are released.
2796 if (l->isRemovedFromCurrentState()) {
2797 l->latchAndReleaseBuffer();
2798 }
2799
2800 // If the layer has been removed and has no parent, then it will not be reachable
2801 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2802 // ensure we can copy its current to drawing state.
2803 if (!l->getParent()) {
2804 mOffscreenLayers.emplace(l.get());
2805 }
2806 }
2807 mLayersPendingRemoval.clear();
2808 }
2809
2810 // If this transaction is part of a window animation then the next frame
2811 // we composite should be considered an animation as well.
2812 mAnimCompositionPending = mAnimTransactionPending;
2813
2814 mDrawingState = mCurrentState;
2815 // clear the "changed" flags in current state
2816 mCurrentState.colorMatrixChanged = false;
2817
Edgar Arriaga844fa672020-01-16 14:21:42 -08002818 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002819 layer->commitChildList();
2820
2821 // If the layer can be reached when traversing mDrawingState, then the layer is no
2822 // longer offscreen. Remove the layer from the offscreenLayer set.
2823 if (mOffscreenLayers.count(layer)) {
2824 mOffscreenLayers.erase(layer);
2825 }
2826 });
2827
2828 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002829 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002830}
2831
Nataniel Borges2b796da2019-02-15 13:32:18 -08002832void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2833 if (mTracingEnabledChanged) {
2834 mTracingEnabled = mTracing.isEnabled();
2835 mTracingEnabledChanged = false;
2836 }
2837
2838 // Synchronize with Tracing thread
2839 std::unique_lock<std::mutex> lock;
2840 if (mTracingEnabled) {
2841 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2842 }
2843
2844 lockedOperation();
2845
2846 // Synchronize with Tracing thread
2847 if (mTracingEnabled) {
2848 lock.unlock();
2849 }
2850}
2851
chaviw74d90ad2019-04-26 14:45:26 -07002852void SurfaceFlinger::commitOffscreenLayers() {
2853 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002854 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002855 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2856 if (!trFlags) return;
2857
2858 layer->doTransaction(0);
2859 layer->commitChildList();
2860 });
2861 }
2862}
2863
Chia-I Wuab0c3192017-08-01 11:29:00 -07002864void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002865 for (const auto& [token, displayDevice] : mDisplays) {
2866 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002867 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002868 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002869 }
2870 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002871}
2872
Dan Stoza6b9454d2014-11-07 16:00:59 -08002873bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874{
Ady Abraham09bd3922019-04-08 10:44:56 -07002875 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 ALOGV("handlePageFlip");
2877
Brian Andersond6927fb2016-07-23 23:37:30 -07002878 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879
Mathias Agopian4fec8732012-06-29 14:12:52 -07002880 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002881 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002882 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002883
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002884 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2885
Eric Penner51c59cd2014-07-28 19:51:58 -07002886 // Store the set of layers that need updates. This set must not change as
2887 // buffers are being latched, as this could result in a deadlock.
2888 // Example: Two producers share the same command stream and:
2889 // 1.) Layer 0 is latched
2890 // 2.) Layer 0 gets a new frame
2891 // 2.) Layer 1 gets a new frame
2892 // 3.) Layer 1 is latched.
2893 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2894 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002895 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002896 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002897 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002898 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002899 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002900 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002901 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002902 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002903 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002904 } else {
2905 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906 }
Robert Carr2047fae2016-11-28 14:09:09 -08002907 });
2908
chaviw49a108c2019-08-12 11:23:06 -07002909 // The client can continue submitting buffers for offscreen layers, but they will not
2910 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2911 // layers to ensure dequeueBuffer doesn't block indefinitely.
2912 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002913 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002914 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2915 }
2916
Lloyd Piquef2c79392018-12-20 16:23:33 -08002917 if (!mLayersWithQueuedFrames.empty()) {
2918 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2919 // writes to Layer current state. See also b/119481871
2920 Mutex::Autolock lock(mStateLock);
2921
2922 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002923 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002924 mLayersPendingRefresh.push_back(layer);
2925 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002926 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002927 if (layer->isBufferLatched()) {
2928 newDataLatched = true;
2929 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002930 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002931 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002932
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002933 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002934
2935 // If we will need to wake up at some time in the future to deal with a
2936 // queued frame that shouldn't be displayed during this vsync period, wake
2937 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002938 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002939 signalLayerUpdate();
2940 }
2941
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002942 // enter boot animation on first buffer latch
2943 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2944 ALOGI("Enter boot animation");
2945 mBootStage = BootStage::BOOTANIMATION;
2946 }
2947
Edgar Arriaga844fa672020-01-16 14:21:42 -08002948 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002949
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002951 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002952}
2953
Mathias Agopianad456f92011-01-13 17:53:01 -08002954void SurfaceFlinger::invalidateHwcGeometry()
2955{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002957}
2958
Robert Carrc0df3122019-04-11 13:18:21 -07002959status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2960 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2961 const sp<IBinder>& parentHandle,
2962 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002963 // add this layer to the current state list
2964 {
2965 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002966 sp<Layer> parent;
2967 if (parentHandle != nullptr) {
2968 parent = fromHandle(parentHandle);
2969 if (parent == nullptr) {
2970 return NAME_NOT_FOUND;
2971 }
2972 } else {
2973 parent = parentLayer;
2974 }
2975
Robert Carr1f0a16a2016-10-24 16:27:39 -07002976 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002977 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002978 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002979 return NO_MEMORY;
2980 }
Robert Carrc0df3122019-04-11 13:18:21 -07002981
2982 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2983
Robert Carrb89ea9d2018-12-10 13:01:14 -08002984 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002985 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002986 } else if (parent == nullptr) {
2987 lbc->onRemovedFromCurrentState();
2988 } else if (parent->isRemovedFromCurrentState()) {
2989 parent->addChild(lbc);
2990 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002991 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002992 parent->addChild(lbc);
2993 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002994
Yiwei Zhang243b3782018-05-15 17:40:04 -07002995 if (gbc != nullptr) {
2996 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2997 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2998 mMaxGraphicBufferProducerListSize,
2999 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3000 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003001 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003002 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003003 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003004 }
3005
Mathias Agopian96f08192010-06-02 23:28:45 -07003006 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003007 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003008
Dan Stoza7d89d062015-04-30 13:29:25 -07003009 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003010}
3011
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003012uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003013 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003014}
3015
Mathias Agopian3f844832013-08-07 21:24:32 -07003016uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003017 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018}
3019
Mathias Agopian3f844832013-08-07 21:24:32 -07003020uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003021 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003022}
3023
3024uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003025 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003026 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003027 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003029 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030 }
3031 return old;
3032}
3033
Marissa Wall713b63f2018-10-17 15:42:43 -07003034bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003035 // to prevent onHandleDestroyed from being called while the lock is held,
3036 // we must keep a copy of the transactions (specifically the composer
3037 // states) around outside the scope of the lock
3038 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003039 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003040 {
3041 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003042
Valerie Haufce31b82019-04-30 16:41:14 -07003043 auto it = mTransactionQueues.begin();
3044 while (it != mTransactionQueues.end()) {
3045 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003046
Valerie Haufce31b82019-04-30 16:41:14 -07003047 while (!transactionQueue.empty()) {
3048 const auto& transaction = transactionQueue.front();
3049 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003050 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003051 transaction.states)) {
3052 setTransactionFlags(eTransactionFlushNeeded);
3053 break;
3054 }
3055 transactions.push_back(transaction);
3056 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3057 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003058 transaction.buffer, transaction.postTime,
3059 transaction.privileged, transaction.hasListenerCallbacks,
3060 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003061 transactionQueue.pop();
3062 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003063 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003064
Valerie Haufce31b82019-04-30 16:41:14 -07003065 if (transactionQueue.empty()) {
3066 it = mTransactionQueues.erase(it);
3067 mTransactionCV.broadcast();
3068 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003069 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003070 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003071 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003072 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003073 return flushedATransaction;
3074}
3075
3076bool SurfaceFlinger::transactionFlushNeeded() {
3077 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003078}
3079
chaviwca27f252018-02-06 16:46:39 -08003080
Marissa Wall17b4e452018-12-26 16:32:34 -08003081bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003082 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003083 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003084 if (!useCachedExpectedPresentTime)
3085 populateExpectedPresentTime();
3086
3087 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003088 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3089 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3090 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3091 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3092 return false;
3093 }
3094
Marissa Wall713b63f2018-10-17 15:42:43 -07003095 for (const ComposerState& state : states) {
3096 const layer_state_t& s = state.state;
3097 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3098 continue;
3099 }
3100 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003101 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003102 }
3103 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003104 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003105}
3106
Valerie Hau9dab9732019-08-20 09:29:25 -07003107void SurfaceFlinger::setTransactionState(
3108 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3109 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3110 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3111 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003112 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003113
Valerie Haubc6ddb12019-03-08 11:10:15 -08003114 const int64_t postTime = systemTime();
3115
Robert Carr14167e02019-02-13 13:50:55 -08003116 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3117
Mathias Agopian698c0872011-06-28 19:09:31 -07003118 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003119
Marissa Wall713b63f2018-10-17 15:42:43 -07003120 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003121 auto itr = mTransactionQueues.find(applyToken);
3122 // if this is an animation frame, wait until prior animation frame has
3123 // been applied by SF
3124 if (flags & eAnimation) {
3125 while (itr != mTransactionQueues.end()) {
3126 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3127 if (CC_UNLIKELY(err != NO_ERROR)) {
3128 ALOGW_IF(err == TIMED_OUT,
3129 "setTransactionState timed out "
3130 "waiting for animation frame to apply");
3131 break;
3132 }
3133 itr = mTransactionQueues.find(applyToken);
3134 }
3135 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003136
3137 // Expected present time is computed and cached on invalidate, so it may be stale.
3138 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3139 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003140 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003141 uncacheBuffer, postTime, privileged,
3142 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003143 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003144 return;
3145 }
3146
Valerie Haubc6ddb12019-03-08 11:10:15 -08003147 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003148 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3149 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003150}
3151
Valerie Hau9dab9732019-08-20 09:29:25 -07003152void SurfaceFlinger::applyTransactionState(
3153 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3154 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3155 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3156 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3157 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003158 uint32_t transactionFlags = 0;
3159
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003160 if (flags & eAnimation) {
3161 // For window updates that are part of an animation we must wait for
3162 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003163 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003164 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003165 if (CC_UNLIKELY(err != NO_ERROR)) {
3166 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003167 // caller after a few seconds.
3168 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3169 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003170 mAnimTransactionPending = false;
3171 break;
3172 }
3173 }
3174 }
3175
chaviwca27f252018-02-06 16:46:39 -08003176 for (const DisplayState& display : displays) {
3177 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003178 }
3179
Valerie Hau9dab9732019-08-20 09:29:25 -07003180 // start and end registration for listeners w/ no surface so they can get their callback. Note
3181 // that listeners with SurfaceControls will start registration during setClientStateLocked
3182 // below.
3183 for (const auto& listener : listenerCallbacks) {
3184 mTransactionCompletedThread.startRegistration(listener);
3185 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003186 }
3187
Valerie Hau9dab9732019-08-20 09:29:25 -07003188 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003189 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003190 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003191 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3192 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003193 }
3194
Valerie Hau9dab9732019-08-20 09:29:25 -07003195 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003196 mTransactionCompletedThread.endRegistration(listenerCallback);
3197 }
3198
Marissa Walle2ffb422018-10-12 11:33:52 -07003199 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003200 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003201 mTransactionCompletedThread.sendCallbacks();
3202 }
3203 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003204
chaviw273171b2018-12-26 11:46:30 -08003205 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3206
Marissa Wall947d34e2019-03-29 14:03:53 -07003207 if (uncacheBuffer.isValid()) {
3208 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003209 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003210 }
3211
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003212 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3213 // anyway. This can be used as a flush mechanism for previous async transactions.
3214 // Empty animation transaction can be used to simulate back-pressure, so also force a
3215 // transaction for empty animation transactions.
3216 if (transactionFlags == 0 &&
3217 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003218 transactionFlags = eTransactionNeeded;
3219 }
3220
Marissa Wall06255332019-03-27 13:48:27 -07003221 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3222 // so we don't have to wake up again next frame to preform an uneeded traversal.
3223 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3224 transactionFlags = transactionFlags & (~eTraversalNeeded);
3225 mTraversalNeededMainThread = true;
3226 }
3227
Mathias Agopian386aa982011-11-07 21:58:03 -08003228 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003229 if (mInterceptor->isEnabled()) {
3230 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003231 }
Irvel468051e2016-06-13 16:44:44 -07003232
Mathias Agopian386aa982011-11-07 21:58:03 -08003233 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003234 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3235 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003236 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003237
3238 // if this is a synchronous transaction, wait for it to take effect
3239 // before returning.
3240 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003241 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003242 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003243 if (flags & eAnimation) {
3244 mAnimTransactionPending = true;
3245 }
chaviw4fe36852019-04-15 16:25:49 -07003246 if (mPendingInputWindowCommands.syncInputWindows) {
3247 mPendingSyncInputWindows = true;
3248 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003249
3250 // applyTransactionState can be called by either the main SF thread or by
3251 // another process through setTransactionState. While a given process may wish
3252 // to wait on synchronous transactions, the main SF thread should never
3253 // be blocked. Therefore, we only wait if isMainThread is false.
3254 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003255 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3256 if (CC_UNLIKELY(err != NO_ERROR)) {
3257 // just in case something goes wrong in SF, return to the
3258 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003259 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3260 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003261 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003262 break;
3263 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003264 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 }
3266}
3267
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003268uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3269 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3270 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003271
Mathias Agopiane57f2922012-08-09 16:29:12 -07003272 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003273 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3274
3275 const uint32_t what = s.what;
3276 if (what & DisplayState::eSurfaceChanged) {
3277 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3278 state.surface = s.surface;
3279 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003280 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003281 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003282 if (what & DisplayState::eLayerStackChanged) {
3283 if (state.layerStack != s.layerStack) {
3284 state.layerStack = s.layerStack;
3285 flags |= eDisplayTransactionNeeded;
3286 }
3287 }
3288 if (what & DisplayState::eDisplayProjectionChanged) {
3289 if (state.orientation != s.orientation) {
3290 state.orientation = s.orientation;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 if (state.frame != s.frame) {
3294 state.frame = s.frame;
3295 flags |= eDisplayTransactionNeeded;
3296 }
3297 if (state.viewport != s.viewport) {
3298 state.viewport = s.viewport;
3299 flags |= eDisplayTransactionNeeded;
3300 }
3301 }
3302 if (what & DisplayState::eDisplaySizeChanged) {
3303 if (state.width != s.width) {
3304 state.width = s.width;
3305 flags |= eDisplayTransactionNeeded;
3306 }
3307 if (state.height != s.height) {
3308 state.height = s.height;
3309 flags |= eDisplayTransactionNeeded;
3310 }
3311 }
3312
Mathias Agopiane57f2922012-08-09 16:29:12 -07003313 return flags;
3314}
3315
Robert Carr14167e02019-02-13 13:50:55 -08003316bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003317 IPCThreadState* ipc = IPCThreadState::self();
3318 const int pid = ipc->getCallingPid();
3319 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003320 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003321 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003322 return false;
3323 }
3324 return true;
3325}
3326
Marissa Wall3dad52d2019-03-22 14:03:19 -07003327uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003328 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3329 bool privileged,
3330 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003331 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003332
Valerie Hau9dab9732019-08-20 09:29:25 -07003333 for (auto& listener : s.listeners) {
3334 // note that startRegistration will not re-register if the listener has
3335 // already be registered for a prior surface control
3336 mTransactionCompletedThread.startRegistration(listener);
3337 listenerCallbacks.insert(listener);
3338 }
3339
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003340 sp<Layer> layer = nullptr;
3341 if (s.surface) {
3342 layer = fromHandle(s.surface);
3343 } else {
3344 // The client may provide us a null handle. Treat it as if the layer was removed.
3345 ALOGW("Attempt to set client state with a null layer handle");
3346 }
chaviw8b3871a2017-11-01 17:41:01 -07003347 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003348 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003349 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003350 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003351 }
chaviw8b3871a2017-11-01 17:41:01 -07003352 return 0;
3353 }
3354
chaviw8b3871a2017-11-01 17:41:01 -07003355 uint32_t flags = 0;
3356
Garfield Tan8a3083e2018-12-03 13:21:07 -08003357 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003358
3359 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3360 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003361 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003362 layer->pushPendingState();
3363 }
3364
Valerie Hau871d6352020-01-29 08:44:02 -08003365 // Only set by BLAST adapter layers
3366 if (what & layer_state_t::eProducerDisconnect) {
3367 layer->onDisconnect();
3368 }
3369
chaviw8b3871a2017-11-01 17:41:01 -07003370 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003371 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003372 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 }
chaviw8b3871a2017-11-01 17:41:01 -07003374 }
3375 if (what & layer_state_t::eLayerChanged) {
3376 // NOTE: index needs to be calculated before we update the state
3377 const auto& p = layer->getParent();
3378 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003379 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003380 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003381 mCurrentState.layersSortedByZ.removeAt(idx);
3382 mCurrentState.layersSortedByZ.add(layer);
3383 // we need traversal (state changed)
3384 // AND transaction (list changed)
3385 flags |= eTransactionNeeded|eTraversalNeeded;
3386 }
chaviw8b3871a2017-11-01 17:41:01 -07003387 } else {
3388 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003389 flags |= eTransactionNeeded|eTraversalNeeded;
3390 }
3391 }
chaviw8b3871a2017-11-01 17:41:01 -07003392 }
3393 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003394 // NOTE: index needs to be calculated before we update the state
3395 const auto& p = layer->getParent();
3396 if (p == nullptr) {
3397 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3398 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3399 mCurrentState.layersSortedByZ.removeAt(idx);
3400 mCurrentState.layersSortedByZ.add(layer);
3401 // we need traversal (state changed)
3402 // AND transaction (list changed)
3403 flags |= eTransactionNeeded|eTraversalNeeded;
3404 }
3405 } else {
3406 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3407 flags |= eTransactionNeeded|eTraversalNeeded;
3408 }
chaviw8b3871a2017-11-01 17:41:01 -07003409 }
3410 }
3411 if (what & layer_state_t::eSizeChanged) {
3412 if (layer->setSize(s.w, s.h)) {
3413 flags |= eTraversalNeeded;
3414 }
3415 }
3416 if (what & layer_state_t::eAlphaChanged) {
3417 if (layer->setAlpha(s.alpha))
3418 flags |= eTraversalNeeded;
3419 }
3420 if (what & layer_state_t::eColorChanged) {
3421 if (layer->setColor(s.color))
3422 flags |= eTraversalNeeded;
3423 }
Peiyong Lind3788632018-09-18 16:01:31 -07003424 if (what & layer_state_t::eColorTransformChanged) {
3425 if (layer->setColorTransform(s.colorTransform)) {
3426 flags |= eTraversalNeeded;
3427 }
3428 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003429 if (what & layer_state_t::eBackgroundColorChanged) {
3430 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3431 flags |= eTraversalNeeded;
3432 }
3433 }
chaviw8b3871a2017-11-01 17:41:01 -07003434 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003435 // TODO: b/109894387
3436 //
3437 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3438 // rotation. To see the problem observe that if we have a square parent, and a child
3439 // of the same size, then we rotate the child 45 degrees around it's center, the child
3440 // must now be cropped to a non rectangular 8 sided region.
3441 //
3442 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3443 // private API, and the WindowManager only uses rotation in one case, which is on a top
3444 // level layer in which cropping is not an issue.
3445 //
3446 // However given that abuse of rotation matrices could lead to surfaces extending outside
3447 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3448 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3449 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003450 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003451 flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eTransparentRegionChanged) {
3454 if (layer->setTransparentRegionHint(s.transparentRegion))
3455 flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eFlagsChanged) {
3458 if (layer->setFlags(s.flags, s.mask))
3459 flags |= eTraversalNeeded;
3460 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003461 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003462 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003463 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003464 if (what & layer_state_t::eCornerRadiusChanged) {
3465 if (layer->setCornerRadius(s.cornerRadius))
3466 flags |= eTraversalNeeded;
3467 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003468 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3469 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 if (what & layer_state_t::eLayerStackChanged) {
3472 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3473 // We only allow setting layer stacks for top level layers,
3474 // everything else inherits layer stack from its parent.
3475 if (layer->hasParent()) {
3476 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003477 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003478 } else if (idx < 0) {
3479 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003480 "that also does not appear in the top level layer list. Something"
3481 " has gone wrong.",
3482 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003483 } else if (layer->setLayerStack(s.layerStack)) {
3484 mCurrentState.layersSortedByZ.removeAt(idx);
3485 mCurrentState.layersSortedByZ.add(layer);
3486 // we need traversal (state changed)
3487 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003488 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003489 }
3490 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003491 if (what & layer_state_t::eDeferTransaction_legacy) {
3492 if (s.barrierHandle_legacy != nullptr) {
3493 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3494 } else if (s.barrierGbp_legacy != nullptr) {
3495 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003496 if (authenticateSurfaceTextureLocked(gbp)) {
3497 const auto& otherLayer =
3498 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003499 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003500 } else {
3501 ALOGE("Attempt to defer transaction to to an"
3502 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003503 }
3504 }
chaviw8b3871a2017-11-01 17:41:01 -07003505 // We don't trigger a traversal here because if no other state is
3506 // changed, we don't want this to cause any more work
3507 }
chaviw8b3871a2017-11-01 17:41:01 -07003508 if (what & layer_state_t::eReparentChildren) {
3509 if (layer->reparentChildren(s.reparentHandle)) {
3510 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003511 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003512 }
chaviw8b3871a2017-11-01 17:41:01 -07003513 if (what & layer_state_t::eDetachChildren) {
3514 layer->detachChildren();
3515 }
3516 if (what & layer_state_t::eOverrideScalingModeChanged) {
3517 layer->setOverrideScalingMode(s.overrideScalingMode);
3518 // We don't trigger a traversal here because if no other state is
3519 // changed, we don't want this to cause any more work
3520 }
Marissa Wall61c58622018-07-18 10:12:20 -07003521 if (what & layer_state_t::eTransformChanged) {
3522 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3523 }
3524 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3525 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3526 flags |= eTraversalNeeded;
3527 }
3528 if (what & layer_state_t::eCropChanged) {
3529 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3530 }
Marissa Wall861616d2018-10-22 12:52:23 -07003531 if (what & layer_state_t::eFrameChanged) {
3532 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3533 }
Marissa Wall61c58622018-07-18 10:12:20 -07003534 if (what & layer_state_t::eAcquireFenceChanged) {
3535 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3536 }
3537 if (what & layer_state_t::eDataspaceChanged) {
3538 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3539 }
3540 if (what & layer_state_t::eHdrMetadataChanged) {
3541 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3542 }
3543 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3544 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3545 }
3546 if (what & layer_state_t::eApiChanged) {
3547 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3548 }
3549 if (what & layer_state_t::eSidebandStreamChanged) {
3550 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3551 }
Robert Carr720e5062018-07-30 17:45:14 -07003552 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003553 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003554 layer->setInputInfo(s.inputInfo);
3555 flags |= eTraversalNeeded;
3556 } else {
3557 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3558 }
Robert Carr720e5062018-07-30 17:45:14 -07003559 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003560 if (what & layer_state_t::eMetadataChanged) {
3561 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3562 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003563 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3564 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3565 flags |= eTraversalNeeded;
3566 }
3567 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003568 if (what & layer_state_t::eShadowRadiusChanged) {
3569 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3570 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003571 if (what & layer_state_t::eFrameRateSelectionPriority) {
3572 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3573 flags |= eTraversalNeeded;
3574 }
3575 }
Steven Thomas3172e202020-01-06 19:25:30 -08003576 if (what & layer_state_t::eFrameRateChanged) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003577 if (layer->setFrameRate(
3578 Layer::FrameRate(s.frameRate, Layer::FrameRateCompatibility::Default)))
3579 flags |= eTraversalNeeded;
Steven Thomas3172e202020-01-06 19:25:30 -08003580 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003581 // This has to happen after we reparent children because when we reparent to null we remove
3582 // child layers from current state and remove its relative z. If the children are reparented in
3583 // the same transaction, then we have to make sure we reparent the children first so we do not
3584 // lose its relative z order.
3585 if (what & layer_state_t::eReparent) {
3586 bool hadParent = layer->hasParent();
3587 if (layer->reparent(s.parentHandleForChild)) {
3588 if (!hadParent) {
3589 mCurrentState.layersSortedByZ.remove(layer);
3590 }
3591 flags |= eTransactionNeeded | eTraversalNeeded;
3592 }
3593 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003594 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003595 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3596 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003597 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3598 }
3599 }
Marissa Wall78b72202019-03-15 14:58:34 -07003600 bool bufferChanged = what & layer_state_t::eBufferChanged;
3601 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3602 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003603 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003604 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003605 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3606 if (success) {
3607 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3608 success = ClientCache::getInstance()
3609 .registerErasedRecipient(s.cachedBuffer,
3610 wp<ClientCache::ErasedRecipient>(this));
3611 if (!success) {
3612 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3613 }
3614 }
Marissa Wall78b72202019-03-15 14:58:34 -07003615 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003616 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003617 } else if (bufferChanged) {
3618 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003619 }
Marissa Wall78b72202019-03-15 14:58:34 -07003620 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003621 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3622 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003623 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003624 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003625 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003626 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3627 // Do not put anything that updates layer state or modifies flags after
3628 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003629 return flags;
3630}
3631
chaviw273171b2018-12-26 11:46:30 -08003632uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3633 uint32_t flags = 0;
3634 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3635 flags |= eTraversalNeeded;
3636 }
3637
chaviwa911b102019-02-14 10:18:33 -08003638 if (inputWindowCommands.syncInputWindows) {
3639 flags |= eTraversalNeeded;
3640 }
3641
Vishnu Nairec0ab382019-02-13 15:32:56 -08003642 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003643 return flags;
3644}
3645
chaviwfe94a222019-08-21 13:52:59 -07003646status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3647 sp<IBinder>* outHandle) {
3648 if (!mirrorFromHandle) {
3649 return NAME_NOT_FOUND;
3650 }
3651
3652 sp<Layer> mirrorLayer;
3653 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003654 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003655
3656 {
3657 Mutex::Autolock _l(mStateLock);
3658 mirrorFrom = fromHandle(mirrorFromHandle);
3659 if (!mirrorFrom) {
3660 return NAME_NOT_FOUND;
3661 }
3662
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003663 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3664 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003665 if (result != NO_ERROR) {
3666 return result;
3667 }
3668
3669 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3670 }
3671
3672 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3673}
3674
Marissa Wall2d814fb2019-04-09 18:52:57 +00003675status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3676 uint32_t h, PixelFormat format, uint32_t flags,
3677 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003678 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003679 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3680 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003681 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003682 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003683 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003684 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003685 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003686
Robert Carrc0df3122019-04-11 13:18:21 -07003687 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3688 "Expected only one of parentLayer or parentHandle to be non-null. "
3689 "Programmer error?");
3690
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003691 status_t result = NO_ERROR;
3692
3693 sp<Layer> layer;
3694
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003695 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003696
Evan Roskya1f1e152019-01-24 16:17:46 -08003697 bool primaryDisplayOnly = false;
3698
3699 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3700 // TODO b/64227542
3701 if (metadata.has(METADATA_WINDOW_TYPE)) {
3702 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3703 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003704 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003705 primaryDisplayOnly = true;
3706 }
3707 }
3708
Mathias Agopian3165cc22012-08-08 19:42:09 -07003709 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003710 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003711 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3712 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003715 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003716 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003717 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003718 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003719 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003720 // check if buffer size is set for color layer.
3721 if (w > 0 || h > 0) {
3722 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3723 int(w), int(h));
3724 return BAD_VALUE;
3725 }
3726
Vishnu Nairfa247b12020-02-11 08:58:26 -08003727 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3728 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003729 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003730 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003731 // check if buffer size is set for container layer.
3732 if (w > 0 || h > 0) {
3733 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3734 int(w), int(h));
3735 return BAD_VALUE;
3736 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003737 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3738 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003739 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740 default:
3741 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003742 break;
3743 }
3744
Dan Stoza7d89d062015-04-30 13:29:25 -07003745 if (result != NO_ERROR) {
3746 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003748
Evan Roskya1f1e152019-01-24 16:17:46 -08003749 if (primaryDisplayOnly) {
3750 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003751 }
3752
Robert Carrb89ea9d2018-12-10 13:01:14 -08003753 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003754 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3755 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003756 if (result != NO_ERROR) {
3757 return result;
3758 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003759 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003760
3761 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003762 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763}
3764
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003765std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3766 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003767
3768 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003769 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003770
Dan Stoza436ccf32018-06-21 12:10:12 -07003771 // Grab the state lock since we're accessing mCurrentState
3772 Mutex::Autolock lock(mStateLock);
3773
Cody Northropbc755282017-03-31 12:00:08 -06003774 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003775 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003776 while (matchFound) {
3777 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003778 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003779 if (layer->getName() == uniqueName) {
3780 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003781 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003782 }
3783 });
3784 }
3785
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003786 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003787 return uniqueName;
3788}
3789
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003790status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003791 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003792 LayerMetadata metadata, PixelFormat& format,
3793 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003794 sp<IGraphicBufferProducer>* gbp,
3795 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003797 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798 case PIXEL_FORMAT_TRANSPARENT:
3799 case PIXEL_FORMAT_TRANSLUCENT:
3800 format = PIXEL_FORMAT_RGBA_8888;
3801 break;
3802 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003803 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003804 break;
3805 }
3806
chaviwb4c6e582019-08-16 14:35:07 -07003807 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003808 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003809 args.textureName = getNewTexture();
3810 {
3811 // Grab the SF state lock during this since it's the only safe way to access
3812 // RenderEngine when creating a BufferLayerConsumer
3813 // TODO: Check if this lock is still needed here
3814 Mutex::Autolock lock(mStateLock);
3815 layer = getFactory().createBufferQueueLayer(args);
3816 }
3817
Marissa Wallfd668622018-05-10 10:21:13 -07003818 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003820 *handle = layer->getHandle();
3821 *gbp = layer->getProducer();
3822 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003824
Marissa Wallfd668622018-05-10 10:21:13 -07003825 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003826 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827}
3828
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003829status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003830 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003831 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003832 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003833 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003834 args.displayDevice = getDefaultDisplayDevice();
3835 args.textureName = getNewTexture();
3836 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003837 if (outTransformHint) {
3838 *outTransformHint = layer->getTransformHint();
3839 }
Marissa Wall61c58622018-07-18 10:12:20 -07003840 *handle = layer->getHandle();
3841 *outLayer = layer;
3842
3843 return NO_ERROR;
3844}
3845
Vishnu Nairfa247b12020-02-11 08:58:26 -08003846status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3847 uint32_t h, uint32_t flags, LayerMetadata metadata,
3848 sp<IBinder>* handle, sp<Layer>* outLayer) {
3849 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003850 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003851 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003852 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003853}
3854
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003855status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003856 uint32_t w, uint32_t h, uint32_t flags,
3857 LayerMetadata metadata, sp<IBinder>* handle,
3858 sp<Layer>* outLayer) {
3859 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003860 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003861 *handle = (*outLayer)->getHandle();
3862 return NO_ERROR;
3863}
3864
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003865void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003866 mLayersPendingRemoval.add(layer);
3867 mLayersRemoved = true;
3868 setTransactionFlags(eTransactionNeeded);
3869}
3870
Robert Carr695d5282018-12-18 15:27:58 -08003871void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003872{
Robert Carr2e102c92018-10-23 12:11:15 -07003873 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003874 // If a layer has a parent, we allow it to out-live it's handle
3875 // with the idea that the parent holds a reference and will eventually
3876 // be cleaned up. However no one cleans up the top-level so we do so
3877 // here.
3878 if (layer->getParent() == nullptr) {
3879 mCurrentState.layersSortedByZ.remove(layer);
3880 }
3881 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003882
3883 auto it = mLayersByLocalBinderToken.begin();
3884 while (it != mLayersByLocalBinderToken.end()) {
3885 if (it->second == layer) {
3886 it = mLayersByLocalBinderToken.erase(it);
3887 } else {
3888 it++;
3889 }
3890 }
3891
Robert Carr695d5282018-12-18 15:27:58 -08003892 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003893}
3894
Mathias Agopianb60314a2012-04-10 22:09:54 -07003895// ---------------------------------------------------------------------------
3896
Andy McFadden13a082e2012-08-24 10:16:42 -07003897void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003898 const auto display = getDefaultDisplayDeviceLocked();
3899 if (!display) return;
3900
3901 const sp<IBinder> token = display->getDisplayToken().promote();
3902 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003903
Jesse Hall01e29052013-02-19 16:13:35 -08003904 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003905 Vector<ComposerState> state;
3906 Vector<DisplayState> displays;
3907 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003908 d.what = DisplayState::eDisplayProjectionChanged |
3909 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003910 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003911 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003912 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003913 d.frame.makeInvalid();
3914 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003915 d.width = 0;
3916 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003917 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003918 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3919 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003920
Dominik Laskowskie9774092018-12-11 10:04:24 -08003921 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003922
Dominik Laskowski83b88212018-12-11 13:34:06 -08003923 const nsecs_t vsyncPeriod = getVsyncPeriod();
3924 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003925
Brian Andersond0010582017-03-07 13:20:31 -08003926 // Use phase of 0 since phase is not known.
3927 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003928 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003929 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003930}
3931
3932void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003933 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003934 postMessageAsync(
3935 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003936}
3937
Ady Abraham27c70212019-06-11 10:52:26 -07003938void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3939 if (mHWCVsyncState != enabled) {
3940 getHwComposer().setVsyncEnabled(displayId, enabled);
3941 mHWCVsyncState = enabled;
3942 }
3943}
3944
Dominik Laskowskie9774092018-12-11 10:04:24 -08003945void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003946 if (display->isVirtual()) {
3947 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003948 return;
3949 }
3950
Dominik Laskowski075d3172018-05-24 15:50:06 -07003951 const auto displayId = display->getId();
3952 LOG_ALWAYS_FATAL_IF(!displayId);
3953
Dominik Laskowski34157762018-10-31 13:07:19 -07003954 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003955
3956 int currentMode = display->getPowerMode();
3957 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003958 return;
3959 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003960
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003961 display->setPowerMode(mode);
3962
Lloyd Pique4dccc412018-01-22 17:21:36 -08003963 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003964 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003965 }
3966
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003967 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003968 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003969 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003970 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003971 mScheduler->onScreenAcquired(mAppConnectionHandle);
3972 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003973 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003974
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003975 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003976 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003977 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003978
3979 struct sched_param param = {0};
3980 param.sched_priority = 1;
3981 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3982 ALOGW("Couldn't set SCHED_FIFO on display on");
3983 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003984 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003985 // Turn off the display
3986 struct sched_param param = {0};
3987 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3988 ALOGW("Couldn't set SCHED_OTHER on display off");
3989 }
3990
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003991 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003992 mScheduler->disableHardwareVsync(true);
3993 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003994 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003995
Ady Abraham27c70212019-06-11 10:52:26 -07003996 // Make sure HWVsync is disabled before turning off the display
3997 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3998
Dominik Laskowski075d3172018-05-24 15:50:06 -07003999 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004000 mVisibleRegionsDirty = true;
4001 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004002 } else if (mode == HWC_POWER_MODE_DOZE ||
4003 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004004 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004005 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004006 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004007 mScheduler->onScreenAcquired(mAppConnectionHandle);
4008 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004009 }
4010 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4011 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004012 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004013 mScheduler->disableHardwareVsync(true);
4014 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004015 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004016 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004017 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004018 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004019 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004020 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004022 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004023 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004024 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004025 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004026 }
4027
Dominik Laskowski34157762018-10-31 13:07:19 -07004028 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004029}
4030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004031void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004032 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004033 const auto display = getDisplayDevice(displayToken);
4034 if (!display) {
4035 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4036 displayToken.get());
4037 } else if (display->isVirtual()) {
4038 ALOGW("Attempt to set power mode %d for virtual display", mode);
4039 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004040 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004042 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004043}
4044
4045// ---------------------------------------------------------------------------
4046
Dominik Laskowskic2867142019-01-21 11:33:38 -08004047status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4048 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004049 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004050
Mathias Agopianbd115332013-04-18 16:41:04 -07004051 IPCThreadState* ipc = IPCThreadState::self();
4052 const int pid = ipc->getCallingPid();
4053 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004054
Mathias Agopianbd115332013-04-18 16:41:04 -07004055 if ((uid != AID_SHELL) &&
4056 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004057 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4058 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004060 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004061 // (this would indicate SF is stuck, but we want to be able to
4062 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004063 status_t err = mStateLock.timedLock(s2ns(1));
4064 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004065 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004066 StringAppendF(&result,
4067 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4068 "(no locks held)\n",
4069 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004070 }
4071
Dominik Laskowskic2867142019-01-21 11:33:38 -08004072 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004073 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004074 {"--dispsync"s,
4075 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004076 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004077 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4078 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4079 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4080 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4081 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4082 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004083 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004084 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4085 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004086
Dominik Laskowskic2867142019-01-21 11:33:38 -08004087 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004088
Dominik Laskowski46470112019-08-02 13:13:11 -07004089 const auto it = dumpers.find(flag);
4090 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004091 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004092 } else if (!asProto) {
4093 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004094 }
4095
Mathias Agopian9795c422009-08-26 16:36:26 -07004096 if (locked) {
4097 mStateLock.unlock();
4098 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004099
Dominik Laskowski46470112019-08-02 13:13:11 -07004100 if (it == dumpers.end()) {
4101 const LayersProto layersProto = dumpProtoFromMainThread();
4102 if (asProto) {
4103 result.append(layersProto.SerializeAsString());
4104 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004105 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004106 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4107 result.append(LayerProtoParser::layerTreeToString(layerTree));
4108 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004109 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004110 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004113 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 return NO_ERROR;
4115}
4116
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004117status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4118 if (asProto && mTracing.isEnabled()) {
4119 mTracing.writeToFileAsync();
4120 }
4121
4122 return doDump(fd, DumpArgs(), asProto);
4123}
4124
Dominik Laskowskic2867142019-01-21 11:33:38 -08004125void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004126 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004127 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004128}
4129
Dominik Laskowskic2867142019-01-21 11:33:38 -08004130void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004131 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004132
Dominik Laskowskic2867142019-01-21 11:33:38 -08004133 if (args.size() > 1) {
4134 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004135 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004136 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004137 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004138 }
Robert Carr2047fae2016-11-28 14:09:09 -08004139 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004140 } else {
4141 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 }
4143}
4144
Dominik Laskowskic2867142019-01-21 11:33:38 -08004145void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004146 const bool clearAll = args.size() < 2;
4147 const auto name = clearAll ? String8() : String8(args[1]);
4148
Edgar Arriaga844fa672020-01-16 14:21:42 -08004149 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004150 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004151 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004152 }
Robert Carr2047fae2016-11-28 14:09:09 -08004153 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004154
Svetoslavd85084b2014-03-20 10:28:31 -07004155 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004156}
4157
Dominik Laskowskic2867142019-01-21 11:33:38 -08004158void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4159 mTimeStats->parseArgs(asProto, args, result);
4160}
4161
Jamie Gennis6547ff42013-07-16 20:12:42 -07004162// This should only be called from the main thread. Otherwise it would need
4163// the lock and should use mCurrentState rather than mDrawingState.
4164void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004165 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004166 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004167 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004168
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004169 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004170}
4171
Yiwei Zhang5434a782018-12-05 18:06:32 -08004172void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004173 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004174
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004175 if (isLayerTripleBufferingDisabled())
4176 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004177
Yiwei Zhang5434a782018-12-05 18:06:32 -08004178 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4179 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4180 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4181 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4182 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4183 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004184 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004185}
4186
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004187void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004188 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004189
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004190 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004191 result.append("\n");
4192
Ady Abraham9e16a482019-12-03 17:19:41 -08004193 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004194 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004195 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004196 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004197
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004198 HwcConfigIndexType defaultConfig;
4199 float minFps, maxFps;
4200 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004201 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004202 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004203 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004204 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004205 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4206 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004207
Ana Krulecc2870422019-01-29 19:00:58 -08004208 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004209}
4210
Yiwei Zhang5434a782018-12-05 18:06:32 -08004211void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4212 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004213 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4214 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004215 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004216 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004217 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004218 }
David Sodman4a36e932017-11-07 14:29:47 -08004219 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004220 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004221 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004222 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4223 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004224}
4225
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004226void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4227 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004228 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4229 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004230 for (const auto& segment : history) {
4231 if (!segment.usedThirdBuffer) {
4232 stats.twoBufferTime += segment.totalTime;
4233 }
4234 if (segment.occupancyAverage < 1.0f) {
4235 stats.doubleBufferedTime += segment.totalTime;
4236 } else if (segment.occupancyAverage < 2.0f) {
4237 stats.tripleBufferedTime += segment.totalTime;
4238 }
4239 ++stats.numSegments;
4240 stats.totalTime += segment.totalTime;
4241 }
4242}
4243
Yiwei Zhang5434a782018-12-05 18:06:32 -08004244void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4245 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004246
4247 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4248 const size_t count = currentLayers.size();
4249 for (size_t i=0 ; i<count ; i++) {
4250 currentLayers[i]->dumpFrameEvents(result);
4251 }
4252}
4253
Yiwei Zhang5434a782018-12-05 18:06:32 -08004254void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004255 result.append("Buffering stats:\n");
4256 result.append(" [Layer name] <Active time> <Two buffer> "
4257 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004258 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004259 typedef std::tuple<std::string, float, float, float> BufferTuple;
4260 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004261 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004262 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004263 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004264 if (stats.numSegments == 0) {
4265 continue;
4266 }
4267 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4268 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4269 stats.totalTime;
4270 float doubleBufferRatio = static_cast<float>(
4271 stats.doubleBufferedTime) / stats.totalTime;
4272 float tripleBufferRatio = static_cast<float>(
4273 stats.tripleBufferedTime) / stats.totalTime;
4274 sorted.insert({activeTime, {name, twoBufferRatio,
4275 doubleBufferRatio, tripleBufferRatio}});
4276 }
4277 for (const auto& sortedPair : sorted) {
4278 float activeTime = sortedPair.first;
4279 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004280 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4281 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004282 }
4283 result.append("\n");
4284}
4285
Yiwei Zhang5434a782018-12-05 18:06:32 -08004286void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004287 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004288 const auto displayId = display->getId();
4289 if (!displayId) {
4290 continue;
4291 }
4292 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004293 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004294 continue;
4295 }
4296
Yiwei Zhang5434a782018-12-05 18:06:32 -08004297 StringAppendF(&result,
4298 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4299 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004300 uint8_t port;
4301 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004302 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004303 result.append("no identification data\n");
4304 continue;
4305 }
4306
4307 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004308 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004309 continue;
4310 }
4311
4312 const auto edid = parseEdid(data);
4313 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004314 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004315 continue;
4316 }
4317
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004319 result.append(edid->displayName.data(), edid->displayName.length());
4320 result.append("\"\n");
4321 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004322}
4323
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004324void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4325 std::string& result) const {
4326 hwc2_display_t hwcDisplayId;
4327 uint8_t port;
4328 DisplayIdentificationData data;
4329
4330 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4331 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4332 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4333 }
4334}
4335
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004337 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004338 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4339 StringAppendF(&result, "DisplayColorSetting: %s\n",
4340 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004341
4342 // TODO: print out if wide-color mode is active or not
4343
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004344 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004345 const auto displayId = display->getId();
4346 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004347 continue;
4348 }
4349
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004351 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004352 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004354 }
4355
Lloyd Pique32cbe282018-10-19 13:09:22 -07004356 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 StringAppendF(&result, " Current color mode: %s (%d)\n",
4358 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004359 }
4360 result.append("\n");
4361}
4362
Vishnu Nair8406fd72019-07-30 11:29:31 -07004363LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004364 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004365 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4366 layer->writeToProto(layersProto, traceFlags);
4367 }
chaviw1d044282017-09-27 12:19:28 -07004368 return layersProto;
4369}
4370
Vishnu Nair0f085c62019-08-30 08:49:12 -07004371void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4372 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4373 // it.
4374 LayerProto* rootProto = layersProto.add_layers();
4375 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4376 rootProto->set_id(offscreenRootLayerId);
4377 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004378 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004379
4380 for (Layer* offscreenLayer : mOffscreenLayers) {
4381 // Add layer as child of the fake root
4382 rootProto->add_children(offscreenLayer->sequence);
4383
4384 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004385 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004386 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004387 }
4388}
4389
Vishnu Nair8406fd72019-07-30 11:29:31 -07004390LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4391 LayersProto layersProto;
4392 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4393 return layersProto;
4394}
4395
Vishnu Nair0f085c62019-08-30 08:49:12 -07004396void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4397 result.append("Offscreen Layers:\n");
4398 postMessageSync(new LambdaMessage([&]() {
4399 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004400 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004401 layer->dumpCallingUidPid(result);
4402 });
4403 }
4404 }));
4405}
4406
Dominik Laskowskic2867142019-01-21 11:33:38 -08004407void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4408 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004409 Colorizer colorizer(colorize);
4410
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411 // figure out if we're stuck somewhere
4412 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004413 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4415
4416 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004417 * Dump library configuration.
4418 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004419
4420 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004421 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004422 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004423 appendSfConfigString(result);
4424 appendUiConfigString(result);
4425 appendGuiConfigString(result);
4426 result.append("\n");
4427
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 result.append("\nDisplay identification data:\n");
4429 dumpDisplayIdentificationData(result);
4430
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004431 result.append("\nWide-Color information:\n");
4432 dumpWideColorInfo(result);
4433
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004434 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004435 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004436 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004437 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004438 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004439
Andy McFadden41d67d72014-04-25 16:58:34 -07004440 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004441 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004442 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004443 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004444 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004445
Dan Stozab90cf072015-03-05 11:05:59 -08004446 dumpStaticScreenStats(result);
4447 result.append("\n");
4448
Alec Mouri40189b02019-03-05 15:07:54 -08004449 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4450 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4451 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004452
Dan Stozae77c7662016-05-13 11:37:28 -07004453 dumpBufferingStats(result);
4454
Andy McFadden4803b742012-09-24 19:07:20 -07004455 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 * Dump the visible layer list
4457 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004458 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004459 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4461 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004462 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004463
Chia-I Wu2f884132018-09-13 15:17:58 -07004464 {
Lloyd Pique207def92019-02-28 16:09:52 -08004465 StringAppendF(&result, "Composition layers\n");
4466 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004467 auto* compositionState = layer->getCompositionState();
4468 if (!compositionState) return;
4469
4470 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4471 layer->getDebugName() ? layer->getDebugName()
4472 : "<unknown>");
4473 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004474 });
4475 }
4476
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004478 * Dump Display state
4479 */
4480
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004481 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004483 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004484 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004486 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004487 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004488
4489 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004490 * Dump CompositionEngine state
4491 */
4492
4493 mCompositionEngine->dump(result);
4494
4495 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004496 * Dump SurfaceFlinger global state
4497 */
4498
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004499 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004500 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004501 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004502
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004503 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004504
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004505 DebugEGLImageTracker::getInstance()->dump(result);
4506
Dominik Laskowski075d3172018-05-24 15:50:06 -07004507 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004508 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4509 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004510 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4511 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004512 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513 StringAppendF(&result,
4514 " transaction-flags : %08x\n"
4515 " gpu_to_cpu_unsupported : %d\n",
4516 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004517
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004518 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004519 displayId && getHwComposer().isConnected(*displayId)) {
4520 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004521 StringAppendF(&result,
4522 " refresh-rate : %f fps\n"
4523 " x-dpi : %f\n"
4524 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004525 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4526 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004527 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004528
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004530
Dan Stozae22aec72016-08-01 13:20:59 -07004531 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004532 * Tracing state
4533 */
4534 mTracing.dump(result);
4535 result.append("\n");
4536
4537 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004538 * HWC layer minidump
4539 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004540 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004541 const auto displayId = display->getId();
4542 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004543 continue;
4544 }
4545
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004547 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004548 const sp<DisplayDevice> displayDevice = display;
4549 mCurrentState.traverseInZOrder(
4550 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004551 result.append("\n");
4552 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004553
4554 /*
4555 * Dump HWComposer state
4556 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004557 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004558 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004560 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004562 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563
4564 /*
4565 * Dump gralloc state
4566 */
4567 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4568 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004569
4570 /*
4571 * Dump VrFlinger state if in use.
4572 */
4573 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4574 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004576 result.append("\n");
4577 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004578
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004579 result.append(mTimeStats->miniDump());
4580 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004581}
4582
Chia-I Wu28f320b2018-05-03 11:02:56 -07004583void SurfaceFlinger::updateColorMatrixLocked() {
4584 mat4 colorMatrix;
4585 if (mGlobalSaturationFactor != 1.0f) {
4586 // Rec.709 luma coefficients
4587 float3 luminance{0.213f, 0.715f, 0.072f};
4588 luminance *= 1.0f - mGlobalSaturationFactor;
4589 mat4 saturationMatrix = mat4(
4590 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4591 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4592 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4593 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4594 );
4595 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4596 } else {
4597 colorMatrix = mClientColorMatrix * mDaltonizer();
4598 }
4599
4600 if (mCurrentState.colorMatrix != colorMatrix) {
4601 mCurrentState.colorMatrix = colorMatrix;
4602 mCurrentState.colorMatrixChanged = true;
4603 setTransactionFlags(eTransactionNeeded);
4604 }
4605}
4606
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004607status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004608#pragma clang diagnostic push
4609#pragma clang diagnostic error "-Wswitch-enum"
4610 switch (static_cast<ISurfaceComposerTag>(code)) {
4611 // These methods should at minimum make sure that the client requested
4612 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004613 case BOOT_FINISHED:
4614 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004615 case CREATE_DISPLAY:
4616 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004617 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004618 case GET_ANIMATION_FRAME_STATS:
4619 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004620 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004621 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004622 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004623 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4624 case SET_AUTO_LOW_LATENCY_MODE:
4625 case GET_GAME_CONTENT_TYPE_SUPPORT:
4626 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004627 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004628 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004629 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004630 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004631 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004632 case NOTIFY_POWER_HINT:
4633 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004634 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4635 IPCThreadState* ipc = IPCThreadState::self();
4636 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4637 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004638 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004639 }
Robert Carr1db73f62016-12-21 12:58:51 -08004640 return OK;
4641 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004642 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004643 IPCThreadState* ipc = IPCThreadState::self();
4644 const int pid = ipc->getCallingPid();
4645 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004646 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4647 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004648 return PERMISSION_DENIED;
4649 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004650 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004652 // Used by apps to hook Choreographer to SurfaceFlinger.
4653 case CREATE_DISPLAY_EVENT_CONNECTION:
4654 // The following calls are currently used by clients that do not
4655 // request necessary permissions. However, they do not expose any secret
4656 // information, so it is OK to pass them.
4657 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004658 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004659 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004660 case GET_PHYSICAL_DISPLAY_IDS:
4661 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004662 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004663 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004664 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004665 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004666 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004667 case GET_DISPLAY_STATS:
4668 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4669 // Calling setTransactionState is safe, because you need to have been
4670 // granted a reference to Client* and Handle* to do anything with it.
4671 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004672 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004673 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004674 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004675 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004676 case IS_WIDE_COLOR_DISPLAY:
4677 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4678 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004679 return OK;
4680 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004681 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004682 case CAPTURE_SCREEN:
4683 case ADD_REGION_SAMPLING_LISTENER:
4684 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004686 IPCThreadState* ipc = IPCThreadState::self();
4687 const int pid = ipc->getCallingPid();
4688 const int uid = ipc->getCallingUid();
4689 if ((uid != AID_GRAPHICS) &&
4690 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4691 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4692 return PERMISSION_DENIED;
4693 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 return OK;
4695 }
chaviw93df2ea2019-04-30 16:45:12 -07004696 case CAPTURE_SCREEN_BY_ID: {
4697 IPCThreadState* ipc = IPCThreadState::self();
4698 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004699 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004700 return OK;
4701 }
4702 return PERMISSION_DENIED;
4703 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004704 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705
4706 // These codes are used for the IBinder protocol to either interrogate the recipient
4707 // side of the transaction for its canonical interface descriptor or to dump its state.
4708 // We let them pass by default.
4709 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4710 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4711 code == IBinder::SYSPROPS_TRANSACTION) {
4712 return OK;
4713 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004714 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004715 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004716 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004717 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4718 return OK;
4719 }
4720 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4721 return PERMISSION_DENIED;
4722#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004723}
4724
Ana Krulec13be8ad2018-08-21 02:43:56 +00004725status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4726 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004727 status_t credentialCheck = CheckTransactCodeCredentials(code);
4728 if (credentialCheck != OK) {
4729 return credentialCheck;
4730 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004731
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004732 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4733 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004734 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004735 IPCThreadState* ipc = IPCThreadState::self();
4736 const int uid = ipc->getCallingUid();
4737 if (CC_UNLIKELY(uid != AID_SYSTEM
4738 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004739 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004740 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004741 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004742 return PERMISSION_DENIED;
4743 }
4744 int n;
4745 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004746 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004747 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004748 return NO_ERROR;
4749 case 1002: // SHOW_UPDATES
4750 n = data.readInt32();
4751 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004752 invalidateHwcGeometry();
4753 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004754 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004755 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004756 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004757 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004759 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004760 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004761 setTransactionFlags(
4762 eTransactionNeeded|
4763 eDisplayTransactionNeeded|
4764 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004765 return NO_ERROR;
4766 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004767 case 1006:{ // send empty update
4768 signalRefresh();
4769 return NO_ERROR;
4770 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004771 case 1008: // toggle use of hw composer
4772 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004773 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004774 invalidateHwcGeometry();
4775 repaintEverything();
4776 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004777 case 1009: // toggle use of transform hint
4778 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004779 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004780 invalidateHwcGeometry();
4781 repaintEverything();
4782 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004783 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004784 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004785 reply->writeInt32(0);
4786 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004787 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004788 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 return NO_ERROR;
4790 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004791 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004792 if (!display) {
4793 return NAME_NOT_FOUND;
4794 }
4795
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004796 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004797 return NO_ERROR;
4798 }
4799 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004800 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004801 // daltonize
4802 n = data.readInt32();
4803 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004804 case 1:
4805 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4806 break;
4807 case 2:
4808 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4809 break;
4810 case 3:
4811 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4812 break;
4813 default:
4814 mDaltonizer.setType(ColorBlindnessType::None);
4815 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004816 }
4817 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004818 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004819 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004820 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004821 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004822
4823 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004824 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004826 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004827 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004828 // apply a color matrix
4829 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004830 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004831 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004832 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004833 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004834 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004835 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004836 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004837 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004839 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004840
4841 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4842 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004843 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004844 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4845 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4846 }
4847
Chia-I Wu28f320b2018-05-03 11:02:56 -07004848 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004849 return NO_ERROR;
4850 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004851 case 1016: { // Unused.
4852 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004853 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004854 case 1017: {
4855 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004856 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004857 return NO_ERROR;
4858 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004859 case 1018: { // Modify Choreographer's phase offset
4860 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004861 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004862 return NO_ERROR;
4863 }
4864 case 1019: { // Modify SurfaceFlinger's phase offset
4865 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004866 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004867 return NO_ERROR;
4868 }
Irvel468051e2016-06-13 16:44:44 -07004869 case 1020: { // Layer updates interceptor
4870 n = data.readInt32();
4871 if (n) {
4872 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004873 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004874 }
4875 else{
4876 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004877 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004878 }
4879 return NO_ERROR;
4880 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004881 case 1021: { // Disable HWC virtual displays
4882 n = data.readInt32();
4883 mUseHwcVirtualDisplays = !n;
4884 return NO_ERROR;
4885 }
Romain Guy0147a172017-06-01 13:53:56 -07004886 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004887 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004888 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004889
Chia-I Wu28f320b2018-05-03 11:02:56 -07004890 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004891 return NO_ERROR;
4892 }
Romain Guy54f154a2017-10-24 21:40:32 +01004893 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004894 int32_t colorMode;
4895
Chia-I Wu0d711262018-05-21 15:19:35 -07004896 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004897 if (data.readInt32(&colorMode) == NO_ERROR) {
4898 mForceColorMode = static_cast<ColorMode>(colorMode);
4899 }
Romain Guy54f154a2017-10-24 21:40:32 +01004900 invalidateHwcGeometry();
4901 repaintEverything();
4902 return NO_ERROR;
4903 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004904 // Deprecate, use 1030 to check whether the device is color managed.
4905 case 1024: {
4906 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004907 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004908 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004909 n = data.readInt32();
4910 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004911 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004912 Mutex::Autolock lock(mStateLock);
4913 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004914 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004915 reply->writeInt32(NO_ERROR);
4916 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004917 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004918 bool writeFile = false;
4919 {
4920 Mutex::Autolock lock(mStateLock);
4921 mTracingEnabledChanged = true;
4922 writeFile = mTracing.disable();
4923 }
4924
4925 if (writeFile) {
4926 reply->writeInt32(mTracing.writeToFile());
4927 } else {
4928 reply->writeInt32(NO_ERROR);
4929 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004930 }
4931 return NO_ERROR;
4932 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004933 case 1026: { // Get layer tracing status
4934 reply->writeBool(mTracing.isEnabled());
4935 return NO_ERROR;
4936 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004937 // Is a DisplayColorSetting supported?
4938 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004939 const auto display = getDefaultDisplayDevice();
4940 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004941 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004942 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004943
4944 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4945 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004946 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004947 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004948 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004949 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004950 reply->writeBool(true);
4951 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004952 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004953 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004954 break;
4955 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004956 reply->writeBool(
4957 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004958 break;
4959 }
4960 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004961 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004962 // Is VrFlinger active?
4963 case 1028: {
4964 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004965 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004966 return NO_ERROR;
4967 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004968 // Set buffer size for SF tracing (value in KB)
4969 case 1029: {
4970 n = data.readInt32();
4971 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4972 ALOGW("Invalid buffer size: %d KB", n);
4973 reply->writeInt32(BAD_VALUE);
4974 return BAD_VALUE;
4975 }
4976
4977 ALOGD("Updating trace buffer to %d KB", n);
4978 mTracing.setBufferSize(n * 1024);
4979 reply->writeInt32(NO_ERROR);
4980 return NO_ERROR;
4981 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004982 // Is device color managed?
4983 case 1030: {
4984 reply->writeBool(useColorManagement);
4985 return NO_ERROR;
4986 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004987 // Override default composition data space
4988 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4989 // && adb shell stop zygote && adb shell start zygote
4990 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4991 // adb shell stop zygote && adb shell start zygote
4992 case 1031: {
4993 Mutex::Autolock _l(mStateLock);
4994 n = data.readInt32();
4995 if (n) {
4996 n = data.readInt32();
4997 if (n) {
4998 Dataspace dataspace = static_cast<Dataspace>(n);
4999 if (!validateCompositionDataspace(dataspace)) {
5000 return BAD_VALUE;
5001 }
5002 mDefaultCompositionDataspace = dataspace;
5003 }
5004 n = data.readInt32();
5005 if (n) {
5006 Dataspace dataspace = static_cast<Dataspace>(n);
5007 if (!validateCompositionDataspace(dataspace)) {
5008 return BAD_VALUE;
5009 }
5010 mWideColorGamutCompositionDataspace = dataspace;
5011 }
5012 } else {
5013 // restore composition data space.
5014 mDefaultCompositionDataspace = defaultCompositionDataspace;
5015 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5016 }
5017 return NO_ERROR;
5018 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005019 // Set trace flags
5020 case 1033: {
5021 n = data.readUint32();
5022 ALOGD("Updating trace flags to 0x%x", n);
5023 mTracing.setTraceFlags(n);
5024 reply->writeInt32(NO_ERROR);
5025 return NO_ERROR;
5026 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005027 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005028 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005029 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005030 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005031 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5032 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005033 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005034 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005035 } else {
5036 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005037 }
5038 return NO_ERROR;
5039 }
Ady Abraham34392f72019-04-10 11:29:27 -07005040 case 1035: {
5041 n = data.readInt32();
5042 mDebugDisplayConfigSetByBackdoor = false;
5043 if (n >= 0) {
5044 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005045 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005046 if (result != NO_ERROR) {
5047 return result;
5048 }
5049 mDebugDisplayConfigSetByBackdoor = true;
5050 }
5051 return NO_ERROR;
5052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005053 }
5054 }
5055 return err;
5056}
5057
Steven Thomas6d8110b2017-08-31 18:24:21 -07005058void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005059 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005060 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005061}
5062
Ana Krulec7d1d6832018-12-27 11:10:09 -08005063void SurfaceFlinger::repaintEverythingForHWC() {
5064 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005065 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005066}
5067
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005068// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5069class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005070public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005071 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5072 ~WindowDisconnector() {
5073 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005074 }
5075
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005076private:
5077 ANativeWindow* mWindow;
5078 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005079};
5080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005081status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005082 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005083 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5084 const Rect& sourceCrop, uint32_t reqWidth,
5085 uint32_t reqHeight, bool useIdentityTransform,
5086 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005087 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005089 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005090
Dominik Laskowski718f9602019-11-09 20:01:35 -08005091 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5092 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5093 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5094 renderAreaRotation = ui::Transform::ROT_0;
5095 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005096
Chia-I Wu20261cb2018-08-23 12:55:44 -07005097 sp<DisplayDevice> display;
5098 {
5099 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005100
Chia-I Wu20261cb2018-08-23 12:55:44 -07005101 display = getDisplayDeviceLocked(displayToken);
5102 if (!display) return BAD_VALUE;
5103
Chia-I Wucb023152018-08-28 12:57:23 -07005104 // set the requested width/height to the logical display viewport size
5105 // by default
5106 if (reqWidth == 0 || reqHeight == 0) {
5107 reqWidth = uint32_t(display->getViewport().width());
5108 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005109 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005110 }
5111
Peiyong Lin0e003c92018-09-17 11:09:51 -07005112 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005113 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005114
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005115 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5116 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005117 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005118 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005119}
5120
chaviw93df2ea2019-04-30 16:45:12 -07005121static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5122 switch (colorMode) {
5123 case ColorMode::DISPLAY_P3:
5124 case ColorMode::BT2100_PQ:
5125 case ColorMode::BT2100_HLG:
5126 case ColorMode::DISPLAY_BT2020:
5127 return Dataspace::DISPLAY_P3;
5128 default:
5129 return Dataspace::V0_SRGB;
5130 }
5131}
5132
5133const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5134 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5135 if (displayToken) {
5136 return getDisplayDeviceLocked(displayToken);
5137 }
5138 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5139 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005140 return getDisplayByLayerStack(displayOrLayerStack);
5141}
5142
5143const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005144 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005145 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005146 return display;
5147 }
5148 }
5149 return nullptr;
5150}
5151
5152status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5153 sp<GraphicBuffer>* outBuffer) {
5154 sp<DisplayDevice> display;
5155 uint32_t width;
5156 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005157 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005158 {
5159 Mutex::Autolock _l(mStateLock);
5160 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5161 if (!display) {
5162 return BAD_VALUE;
5163 }
5164
5165 width = uint32_t(display->getViewport().width());
5166 height = uint32_t(display->getViewport().height());
5167
Dominik Laskowski718f9602019-11-09 20:01:35 -08005168 const auto orientation = display->getOrientation();
5169 captureOrientation = ui::Transform::toRotationFlags(orientation);
5170
5171 switch (captureOrientation) {
5172 case ui::Transform::ROT_90:
5173 captureOrientation = ui::Transform::ROT_270;
5174 break;
5175
5176 case ui::Transform::ROT_270:
5177 captureOrientation = ui::Transform::ROT_90;
5178 break;
5179
5180 case ui::Transform::ROT_INVALID:
5181 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5182 captureOrientation = ui::Transform::ROT_0;
5183 break;
5184
5185 default:
5186 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005187 }
chaviw93df2ea2019-04-30 16:45:12 -07005188 *outDataspace =
5189 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5190 }
5191
5192 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5193 false /* captureSecureLayers */);
5194
5195 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5196 std::placeholders::_1);
5197 bool ignored = false;
5198 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5199 false /* useIdentityTransform */,
5200 ignored /* outCapturedSecureLayers */);
5201}
5202
Robert Carr866455f2019-04-02 16:28:26 -07005203status_t SurfaceFlinger::captureLayers(
5204 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5205 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5206 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5207 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005208 ATRACE_CALL();
5209
5210 class LayerRenderArea : public RenderArea {
5211 public:
Robert Carr578038f2018-03-09 12:25:24 -08005212 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005213 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005214 bool childrenOnly, const Rect& displayViewport)
5215 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005216 mLayer(layer),
5217 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005218 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005219 mFlinger(flinger),
5220 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005221 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005222 Rect getBounds() const override {
5223 const Layer::State& layerState(mLayer->getDrawingState());
5224 return mLayer->getBufferSize(layerState);
5225 }
Marissa Wall61c58622018-07-18 10:12:20 -07005226 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005227 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005228 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005229 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005230 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005231 }
chaviwa76b2712017-09-20 12:02:26 -07005232 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005233 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005234 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005235 Rect getSourceCrop() const override {
5236 if (mCrop.isEmpty()) {
5237 return getBounds();
5238 } else {
5239 return mCrop;
5240 }
5241 }
Robert Carr578038f2018-03-09 12:25:24 -08005242 class ReparentForDrawing {
5243 public:
5244 const sp<Layer>& oldParent;
5245 const sp<Layer>& newParent;
5246
Vishnu Nair4351ad52019-02-11 14:13:02 -08005247 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5248 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005249 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005250 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005251 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5252 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005253 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005254 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005255 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005256 };
5257
5258 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005259 const Rect sourceCrop = getSourceCrop();
5260 // no need to check rotation because there is none
5261 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5262 sourceCrop.height() != getReqHeight();
5263
Robert Carr578038f2018-03-09 12:25:24 -08005264 if (!mChildrenOnly) {
5265 mTransform = mLayer->getTransform().inverse();
5266 drawLayers();
5267 } else {
5268 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005269 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5270 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005271 // In the "childrenOnly" case we reparent the children to a screenshot
5272 // layer which has no properties set and which does not draw.
5273 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005274 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5275 "Screenshot Parent"s, w, h, 0,
5276 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005277
Vishnu Nair4351ad52019-02-11 14:13:02 -08005278 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005279 drawLayers();
5280 }
5281 }
chaviwa76b2712017-09-20 12:02:26 -07005282
chaviwa76b2712017-09-20 12:02:26 -07005283 private:
chaviw7206d492017-11-10 16:16:12 -08005284 const sp<Layer> mLayer;
5285 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005286
Peiyong Linefefaac2018-08-17 12:27:51 -07005287 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005288 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005289
5290 SurfaceFlinger* mFlinger;
5291 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005292 };
5293
Robert Carrc0df3122019-04-11 13:18:21 -07005294 int reqWidth = 0;
5295 int reqHeight = 0;
5296 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005297 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005298 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005299 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005300 {
5301 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005302
Robert Carrc0df3122019-04-11 13:18:21 -07005303 parent = fromHandle(layerHandleBinder);
5304 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5305 ALOGE("captureLayers called with an invalid or removed parent");
5306 return NAME_NOT_FOUND;
5307 }
5308
5309 const int uid = IPCThreadState::self()->getCallingUid();
5310 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5311 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5312 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5313 return PERMISSION_DENIED;
5314 }
5315
Vishnu Nairefc42e22019-12-03 17:36:12 -08005316 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005317 if (sourceCrop.width() <= 0) {
5318 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005319 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005320 }
5321
5322 if (sourceCrop.height() <= 0) {
5323 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005324 crop.bottom = parentSourceBounds.getHeight();
5325 }
5326
5327 if (crop.isEmpty() || frameScale <= 0.0f) {
5328 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5329 // crop was not specified, or an invalid frame scale was provided.
5330 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005331 }
5332 reqWidth = crop.width() * frameScale;
5333 reqHeight = crop.height() * frameScale;
5334
5335 for (const auto& handle : excludeHandles) {
5336 sp<Layer> excludeLayer = fromHandle(handle);
5337 if (excludeLayer != nullptr) {
5338 excludeLayers.emplace(excludeLayer);
5339 } else {
5340 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5341 return NAME_NOT_FOUND;
5342 }
5343 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005344
5345 auto display = getDisplayByLayerStack(parent->getLayerStack());
5346 if (!display) {
5347 return BAD_VALUE;
5348 }
5349
5350 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005351 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005352
Chia-I Wu20261cb2018-08-23 12:55:44 -07005353 // really small crop or frameScale
5354 if (reqWidth <= 0) {
5355 reqWidth = 1;
5356 }
5357 if (reqHeight <= 0) {
5358 reqHeight = 1;
5359 }
5360
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005361 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5362 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005363 auto traverseLayers = [parent, childrenOnly,
5364 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005365 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5366 if (!layer->isVisible()) {
5367 return;
Robert Carr578038f2018-03-09 12:25:24 -08005368 } else if (childrenOnly && layer == parent.get()) {
5369 return;
chaviwa76b2712017-09-20 12:02:26 -07005370 }
Robert Carr866455f2019-04-02 16:28:26 -07005371
5372 sp<Layer> p = layer;
5373 while (p != nullptr) {
5374 if (excludeLayers.count(p) != 0) {
5375 return;
5376 }
5377 p = p->getParent();
5378 }
5379
chaviwa76b2712017-09-20 12:02:26 -07005380 visitor(layer);
5381 });
5382 };
Robert Carr108b2c72019-04-02 16:32:58 -07005383
5384 bool outCapturedSecureLayers = false;
5385 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5386 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005387}
5388
5389status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5390 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005391 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005392 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005393 bool useIdentityTransform,
5394 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005395 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005396
Peiyong Lin0e003c92018-09-17 11:09:51 -07005397 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005398 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5399 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005400 *outBuffer =
5401 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5402 static_cast<android_pixel_format>(reqPixelFormat), 1,
5403 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005404
Robert Carr108b2c72019-04-02 16:32:58 -07005405 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5406 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005407}
5408
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005409status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5410 TraverseLayersFunction traverseLayers,
5411 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005412 bool useIdentityTransform,
5413 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005414 // This mutex protects syncFd and captureResult for communication of the return values from the
5415 // main thread back to this Binder thread
5416 std::mutex captureMutex;
5417 std::condition_variable captureCondition;
5418 std::unique_lock<std::mutex> captureLock(captureMutex);
5419 int syncFd = -1;
5420 std::optional<status_t> captureResult;
5421
Robert Carr03480e22018-01-04 16:02:06 -08005422 const int uid = IPCThreadState::self()->getCallingUid();
5423 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5424
Dominik Laskowski8c001672018-05-30 16:52:06 -07005425 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005426 // If there is a refresh pending, bug out early and tell the binder thread to try again
5427 // after the refresh.
5428 if (mRefreshPending) {
5429 ATRACE_NAME("Skipping screenshot for now");
5430 std::unique_lock<std::mutex> captureLock(captureMutex);
5431 captureResult = std::make_optional<status_t>(EAGAIN);
5432 captureCondition.notify_one();
5433 return;
5434 }
5435
5436 status_t result = NO_ERROR;
5437 int fd = -1;
5438 {
5439 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005440 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005441 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005442 useIdentityTransform, forSystem, &fd,
5443 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005444 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005445 }
5446
5447 {
5448 std::unique_lock<std::mutex> captureLock(captureMutex);
5449 syncFd = fd;
5450 captureResult = std::make_optional<status_t>(result);
5451 captureCondition.notify_one();
5452 }
5453 });
5454
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005455 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005456 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005457 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005458 while (*captureResult == EAGAIN) {
5459 captureResult.reset();
5460 result = postMessageAsync(message);
5461 if (result != NO_ERROR) {
5462 return result;
5463 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005464 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005465 }
5466 result = *captureResult;
5467 }
5468
5469 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005470 sync_wait(syncFd, -1);
5471 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005472 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005473
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005474 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005475}
5476
chaviwa76b2712017-09-20 12:02:26 -07005477void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005478 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005479 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5480 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005481 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005482
chaviwa76b2712017-09-20 12:02:26 -07005483 const auto reqWidth = renderArea.getReqWidth();
5484 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005485 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005486 const auto transform = renderArea.getTransform();
5487 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005488 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005489
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005490 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005491 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005492
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005493 // assume that bounds are never offset, and that they are the same as the
5494 // buffer bounds.
5495 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005496 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005497 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005498
5499 // Now take into account the rotation flag. We append a transform that
5500 // rotates the layer stack about the origin, then translate by buffer
5501 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005502 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005503 int displacementX = 0;
5504 int displacementY = 0;
5505 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5506 switch (rotation) {
5507 case ui::Transform::ROT_90:
5508 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005509 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005510 break;
5511 case ui::Transform::ROT_180:
5512 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005513 displacementY = renderArea.getBounds().getWidth();
5514 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005515 break;
5516 case ui::Transform::ROT_270:
5517 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005518 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005519 break;
5520 default:
5521 break;
5522 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005523
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005524 // We need to transform the clipping window into the right spot.
5525 // First, rotate the clipping rectangle by the rotation hint to get the
5526 // right orientation
5527 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5528 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5529 const vec4 rotClipTL = rotMatrix * clipTL;
5530 const vec4 rotClipBR = rotMatrix * clipBR;
5531 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5532 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5533 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5534 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5535
5536 // Now reposition the clipping rectangle with the displacement vector
5537 // computed above.
5538 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005539 clientCompositionDisplay.clip =
5540 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5541 newClipRight + displacementX, newClipBottom + displacementY);
5542
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005543 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005544 clientCompositionDisplay.globalTransform =
5545 clipTransform * clientCompositionDisplay.globalTransform;
5546
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005547 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5548 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005549
chaviw50da5042018-04-09 13:49:37 -07005550 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005551
Vishnu Nair9b079a22020-01-21 14:36:08 -08005552 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005553 fillLayer.source.buffer.buffer = nullptr;
5554 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5555 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5556 fillLayer.alpha = half(alpha);
5557 clientCompositionLayers.push_back(fillLayer);
5558
5559 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005560 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005561 const bool supportProtectedContent = false;
5562 Region clip(renderArea.getBounds());
5563 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5564 clip,
5565 useIdentityTransform,
5566 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5567 renderArea.isSecure(),
5568 supportProtectedContent,
5569 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005570 displayViewport,
5571 clientCompositionDisplay.outputDataspace,
5572 true, /* realContentIsVisible */
5573 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005574 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005575 std::vector<compositionengine::LayerFE::LayerSettings> results =
5576 layer->prepareClientCompositionList(targetSettings);
5577 clientCompositionLayers.insert(clientCompositionLayers.end(),
5578 std::make_move_iterator(results.begin()),
5579 std::make_move_iterator(results.end()));
5580 results.clear();
5581
chaviwa76b2712017-09-20 12:02:26 -07005582 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005583
Vishnu Nair9b079a22020-01-21 14:36:08 -08005584 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5585 clientCompositionLayers.reserve(clientCompositionLayers.size());
5586 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5587 std::back_inserter(clientCompositionLayerPointers),
5588 [](compositionengine::LayerFE::LayerSettings& settings)
5589 -> renderengine::LayerSettings* { return &settings; });
5590
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005591 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005592 // Use an empty fence for the buffer fence, since we just created the buffer so
5593 // there is no need for synchronization with the GPU.
5594 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005595 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005596 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005597 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005598 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005599
5600 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005601}
5602
chaviwa76b2712017-09-20 12:02:26 -07005603status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5604 TraverseLayersFunction traverseLayers,
5605 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005606 bool useIdentityTransform, bool forSystem,
5607 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005608 ATRACE_CALL();
5609
chaviwa76b2712017-09-20 12:02:26 -07005610 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005611 outCapturedSecureLayers =
5612 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005613 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005614
Robert Carr03480e22018-01-04 16:02:06 -08005615 // We allow the system server to take screenshots of secure layers for
5616 // use in situations like the Screen-rotation animation and place
5617 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005618 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005619 ALOGW("FB is protected: PERMISSION_DENIED");
5620 return PERMISSION_DENIED;
5621 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005622 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005623 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005624}
5625
chaviw95ef3c42019-02-14 10:55:09 -08005626void SurfaceFlinger::setInputWindowsFinished() {
5627 Mutex::Autolock _l(mStateLock);
5628
5629 mPendingSyncInputWindows = false;
5630 mTransactionCV.broadcast();
5631}
chaviw5f21a5e2019-02-14 10:00:34 -08005632
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005633// ---------------------------------------------------------------------------
5634
Edgar Arriaga844fa672020-01-16 14:21:42 -08005635void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5636 layersSortedByZ.traverse(visitor);
5637}
5638
Dan Stoza412903f2017-04-27 13:42:17 -07005639void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5640 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005641}
5642
Dan Stoza412903f2017-04-27 13:42:17 -07005643void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5644 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005645}
5646
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005647void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005648 const LayerVector::Visitor& visitor) {
5649 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005650 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005651 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005652 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005653 continue;
5654 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005655 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005656 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005657 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005658 return;
5659 }
chaviwa76b2712017-09-20 12:02:26 -07005660 if (!layer->isVisible()) {
5661 return;
5662 }
5663 visitor(layer);
5664 });
5665 }
5666}
5667
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005668status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5669 HwcConfigIndexType defaultConfig,
5670 float minRefreshRate,
5671 float maxRefreshRate) {
5672 Mutex::Autolock lock(mStateLock);
5673
Dominik Laskowski22488f62019-03-28 09:53:04 -07005674 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005675 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5676 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5677 // it should go thru setDesiredActiveConfig, similar to primary display.
5678 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5679 const auto displayId = display->getId();
5680 LOG_ALWAYS_FATAL_IF(!displayId);
5681
5682 HWC2::VsyncPeriodChangeConstraints constraints;
5683 constraints.desiredTimeNanos = systemTime();
5684 constraints.seamlessRequired = false;
5685
5686 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005687 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5688 constraints, &timeline) < 0) {
5689 return BAD_VALUE;
5690 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005691 if (timeline.refreshRequired) {
5692 repaintEverythingForHWC();
5693 }
5694
Ady Abrahamdfa37362020-01-21 18:02:39 -08005695 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005696 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005697 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5698 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005699 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005700 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005701 }
5702
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005703 if (mDebugDisplayConfigSetByBackdoor) {
5704 // ignore this request as config is overridden by backdoor
5705 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005706 }
5707
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005708 bool policyChanged;
5709 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5710 &policyChanged) < 0) {
5711 return BAD_VALUE;
5712 }
5713 if (!policyChanged) {
5714 return NO_ERROR;
5715 }
5716
5717 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5718 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005719
5720 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5721 // that listeners that care about a change in allowed configs can get the notification.
5722 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005723 const nsecs_t vsyncPeriod =
5724 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005725 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005726 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005727
Ana Krulec3f6a2062020-01-23 15:48:01 -08005728 auto configId = mScheduler->getPreferredConfigId();
5729 auto preferredRefreshRate = configId
5730 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5731 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5732 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5733 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5734 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5735
5736 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5737 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5738 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005739 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005740 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005741 }
5742
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005743 return NO_ERROR;
5744}
5745
Ana Krulec0782b882019-10-15 17:34:54 -07005746status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005747 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005748 float maxRefreshRate) {
5749 ATRACE_CALL();
5750
5751 if (!displayToken) {
5752 return BAD_VALUE;
5753 }
5754
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005755 status_t result = NO_ERROR;
5756
Ana Krulec234bb162019-11-10 22:55:55 +01005757 postMessageSync(new LambdaMessage([&]() {
5758 const auto display = getDisplayDeviceLocked(displayToken);
5759 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005760 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005761 ALOGE("Attempt to set desired display configs for invalid display token %p",
5762 displayToken.get());
5763 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005764 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005765 ALOGW("Attempt to set desired display configs for virtual display");
5766 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005767 result =
5768 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5769 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005770 }
5771 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005772
5773 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005774}
5775
5776status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005777 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005778 float* outMinRefreshRate,
5779 float* outMaxRefreshRate) {
5780 ATRACE_CALL();
5781
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005782 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005783 return BAD_VALUE;
5784 }
5785
5786 Mutex::Autolock lock(mStateLock);
5787 const auto display = getDisplayDeviceLocked(displayToken);
5788 if (!display) {
5789 return NAME_NOT_FOUND;
5790 }
5791
5792 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005793 HwcConfigIndexType defaultConfig;
5794 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5795 *outDefaultConfig = defaultConfig.value();
5796 return NO_ERROR;
5797 } else if (display->isVirtual()) {
5798 return BAD_VALUE;
5799 } else {
5800 const auto displayId = display->getId();
5801 if (!displayId) {
5802 return BAD_VALUE;
5803 }
5804 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5805 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5806 *outMinRefreshRate = 1e9f / vsyncPeriod;
5807 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5808 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005809 }
Ana Krulec0782b882019-10-15 17:34:54 -07005810}
5811
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005812void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005813 mFlinger->setInputWindowsFinished();
5814}
5815
Robert Carrc0df3122019-04-11 13:18:21 -07005816sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005817 BBinder* b = nullptr;
5818 if (handle) {
5819 b = handle->localBinder();
5820 }
Robert Carrc0df3122019-04-11 13:18:21 -07005821 if (b == nullptr) {
5822 return nullptr;
5823 }
5824 auto it = mLayersByLocalBinderToken.find(b);
5825 if (it != mLayersByLocalBinderToken.end()) {
5826 return it->second.promote();
5827 }
5828 return nullptr;
5829}
5830
Dominik Laskowski75848362019-11-11 17:57:20 -08005831void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005832 mNumLayers++;
5833 mScheduler->registerLayer(layer);
5834}
5835
5836void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5837 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005838 removeFromOffscreenLayers(layer);
5839}
5840
5841// WARNING: ONLY CALL THIS FROM LAYER DTOR
5842// Here we add children in the current state to offscreen layers and remove the
5843// layer itself from the offscreen layer list. Since
5844// this is the dtor, it is safe to access the current state. This keeps us
5845// from dangling children layers such that they are not reachable from the
5846// Drawing state nor the offscreen layer list
5847// See b/141111965
5848void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5849 for (auto& child : layer->getCurrentChildren()) {
5850 mOffscreenLayers.emplace(child.get());
5851 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005852 mOffscreenLayers.erase(layer);
5853}
5854
Alec Mouri4545a8a2019-08-08 20:05:32 -07005855void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5856 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5857}
5858
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005859status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5860 float lightPosY, float lightPosZ,
5861 float lightRadius) {
5862 Mutex::Autolock _l(mStateLock);
5863 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5864 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5865 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5866 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5867 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5868
5869 // these values are overridden when calculating the shadow settings for a layer.
5870 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5871 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005872 return NO_ERROR;
5873}
5874
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005875const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5876 const {
5877 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5878 // on the work to remove the table in that bug rather than adding more to
5879 // it.
5880 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5881 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5882 // supported, and exposed via the
5883 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5884 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5885 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5886 };
5887 return genericLayerMetadataKeyMap;
5888}
5889
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005890} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005891
Mathias Agopian3f844832013-08-07 21:24:32 -07005892#if defined(__gl_h_)
5893#error "don't include gl/gl.h in this file"
5894#endif
5895
5896#if defined(__gl2_h_)
5897#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005898#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005899
5900// TODO(b/129481165): remove the #pragma below and fix conversion issues
5901#pragma clang diagnostic pop // ignored "-Wconversion"