blob: 8489adb6aac8e56f54248f4791d58bb4ba3e685f [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
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.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"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800211const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100220uint32_t SurfaceFlinger::maxGraphicsWidth;
221uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800223ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800230bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700231
Kalle Raitaa099a242017-01-11 11:17:29 -0800232std::string getHwcServiceName() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.hwc_service_name", value, "default");
235 ALOGI("Using HWComposer service: '%s'", value);
236 return std::string(value);
237}
238
239bool useTrebleTestingOverride() {
240 char value[PROPERTY_VALUE_MAX] = {};
241 property_get("debug.sf.treble_testing_override", value, "false");
242 ALOGI("Treble testing override: '%s'", value);
243 return std::string(value) == "true";
244}
245
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
247 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Enhanced");
254 default:
255 return std::string("Unknown ") +
256 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258}
259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
263 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700265 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700266 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700268 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800269 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
270 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287
Brian Lindahla13f2d52020-03-05 11:54:17 +0100288 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
289 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 mDefaultCompositionDataspace =
296 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700297 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
298 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 defaultCompositionDataspace = mDefaultCompositionDataspace;
300 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
301 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
302 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
303 wideColorGamutCompositionPixelFormat =
304 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700305
Yichi Chenda901bf2019-06-28 14:58:27 +0800306 mColorSpaceAgnosticDataspace =
307 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800310
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
312 switch (primary_display_orientation(Values::ORIENTATION_0)) {
313 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_90:
316 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_180:
319 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 case Values::ORIENTATION_270:
322 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800326
Sundong Ahn85131bd2019-02-18 15:51:53 +0900327 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 // debugging stuff...
330 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700331
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700333 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334
Alec Mouri5f487d42020-02-06 09:26:19 -0800335 property_get("ro.build.type", value, "user");
336 mIsUserBuild = strcmp(value, "user") == 0;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700367 mSupportsBlur = supportsBlurs;
368 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800369 property_get("ro.sf.blurs_are_expensive", value, "0");
370 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800371
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800372 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800375 mGraphicBufferProducerListSizeLogThreshold =
376 std::max(static_cast<int>(0.95 *
377 static_cast<double>(mMaxGraphicBufferProducerListSize)),
378 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700379
Dan Stozaec460082018-12-17 15:35:09 -0800380 property_get("debug.sf.luma_sampling", value, "1");
381 mLumaSampling = atoi(value);
382
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800383 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800384 mDisableClientCompositionCache = atoi(value);
385
Romain Guy11d63f42017-07-20 12:47:14 -0700386 // We should be reading 'persist.sys.sf.color_saturation' here
387 // but since /data may be encrypted, we need to wait until after vold
388 // comes online to attempt to read the property. The property is
389 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800390
391 if (useTrebleTestingOverride()) {
392 // Without the override SurfaceFlinger cannot connect to HIDL
393 // services that are not listed in the manifests. Considered
394 // deriving the setting from the set service name, but it
395 // would be brittle if the name that's not 'default' is used
396 // for production purposes later on.
397 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
398 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800399
400 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401}
402
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403void SurfaceFlinger::onFirstRef()
404{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800405 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406}
407
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700408SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409
Dan Stozac7014012014-02-14 15:03:43 -0800410void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411{
412 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700413 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414
Andy McFadden13a082e2012-08-24 10:16:42 -0700415 // restore initial conditions (default device unblank, etc)
416 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417
418 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700419 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Robert Carr1db73f62016-12-21 12:58:51 -0800422static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700423 status_t err = client->initCheck();
424 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 }
Robert Carr1db73f62016-12-21 12:58:51 -0800427 return nullptr;
428}
429
430sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
431 return initClient(new Client(this));
432}
433
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700434sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
435 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436{
437 class DisplayToken : public BBinder {
438 sp<SurfaceFlinger> flinger;
439 virtual ~DisplayToken() {
440 // no more references, this display must be terminated
441 Mutex::Autolock _l(flinger->mStateLock);
442 flinger->mCurrentState.displays.removeItem(this);
443 flinger->setTransactionFlags(eDisplayTransactionNeeded);
444 }
445 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700446 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447 : flinger(flinger) {
448 }
449 };
450
451 sp<BBinder> token = new DisplayToken(this);
452
453 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454 // Display ID is assigned when virtual display is allocated by HWC.
455 DisplayDeviceState state;
456 state.isSecure = secure;
457 state.displayName = displayName;
458 mCurrentState.displays.add(token, state);
459 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 return token;
461}
462
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700463void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700464 Mutex::Autolock _l(mStateLock);
465
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
467 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700468 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 return;
470 }
471
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
473 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 ALOGE("destroyDisplay called for non-virtual display");
475 return;
476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 mInterceptor->saveDisplayDeletion(state.sequenceId);
478 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 setTransactionFlags(eDisplayTransactionNeeded);
480}
481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
483 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485 const auto internalDisplayId = getInternalDisplayIdLocked();
486 if (!internalDisplayId) {
487 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 }
489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490 std::vector<PhysicalDisplayId> displayIds;
491 displayIds.reserve(mPhysicalDisplayTokens.size());
492 displayIds.push_back(internalDisplayId->value);
493
494 for (const auto& [id, token] : mPhysicalDisplayTokens) {
495 if (id != *internalDisplayId) {
496 displayIds.push_back(id.value);
497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 return displayIds;
501}
502
503sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
504 Mutex::Autolock lock(mStateLock);
505 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
Ady Abraham37965d42018-11-01 13:43:32 -0700508status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
509 if (!outGetColorManagement) {
510 return BAD_VALUE;
511 }
512 *outGetColorManagement = useColorManagement;
513 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700514}
515
Lloyd Pique441d5042018-10-18 16:49:51 -0700516HWComposer& SurfaceFlinger::getHwComposer() const {
517 return mCompositionEngine->getHwComposer();
518}
519
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700520renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
521 return mCompositionEngine->getRenderEngine();
522}
523
Lloyd Pique70d91362018-10-18 16:02:55 -0700524compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
525 return *mCompositionEngine.get();
526}
527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528void SurfaceFlinger::bootFinished()
529{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700530 if (mBootFinished == true) {
531 ALOGE("Extra call to bootFinished");
532 return;
533 }
534 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700535 if (mStartPropertySetThread->join() != NO_ERROR) {
536 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800537 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 const nsecs_t now = systemTime();
539 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000540 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
Mikael Pessa90092f42019-08-26 17:22:04 -0700542 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000543 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700544
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700545 // wait patiently for the window manager death
546 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700547 mWindowManager = defaultServiceManager()->getService(name);
548 if (mWindowManager != 0) {
549 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550 }
Robert Carr720e5062018-07-30 17:45:14 -0700551 sp<IBinder> input(defaultServiceManager()->getService(
552 String16("inputflinger")));
553 if (input == nullptr) {
554 ALOGE("Failed to link to input service");
555 } else {
556 mInputFlinger = interface_cast<IInputFlinger>(input);
557 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558
Steven Thomas050b2c82017-03-06 11:45:16 -0800559 if (mVrFlinger) {
560 mVrFlinger->OnBootFinished();
561 }
562
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700564 // formerly we would just kill the process, but we now ask it to exit so it
565 // can choose where to stop the animation.
566 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700567
568 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
569 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
570 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700571
Ana Krulecbd6654b2019-02-15 15:18:15 -0800572 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800573 readPersistentProperties();
574 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800575
Ady Abraham8a82ba62020-01-17 12:43:17 -0800576 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
577 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
578 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
579 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581}
582
Dan Stoza436ccf32018-06-21 12:10:12 -0700583uint32_t SurfaceFlinger::getNewTexture() {
584 {
585 std::lock_guard lock(mTexturePoolMutex);
586 if (!mTexturePool.empty()) {
587 uint32_t name = mTexturePool.back();
588 mTexturePool.pop_back();
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
590 return name;
591 }
592
593 // The pool was too small, so increase it for the future
594 ++mTexturePoolSize;
595 }
596
597 // The pool was empty, so we need to get a new texture name directly using a
598 // blocking call to the main thread
599 uint32_t name = 0;
600 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
601 return name;
602}
603
Mathias Agopian3f844832013-08-07 21:24:32 -0700604void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700605 std::lock_guard lock(mTexturePoolMutex);
606 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
607 // to actually delete this or not based on mTexturePoolSize
608 mTexturePool.push_back(texture);
609 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700620 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800621 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700622 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
623 renderengine::RenderEngineCreationArgs::Builder()
624 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
625 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
626 .setUseColorManagerment(useColorManagement)
627 .setEnableProtectedContext(enable_protected_contents(false))
628 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700629 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700630 .setContextPriority(useContextPriority
631 ? renderengine::RenderEngine::ContextPriority::HIGH
632 : renderengine::RenderEngine::ContextPriority::MEDIUM)
633 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800634 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700635
636 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
637 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700638 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800639 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800640 // Process any initial hotplug and resulting display changes.
641 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700642 const auto display = getDefaultDisplayDeviceLocked();
643 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700644 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700645 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800646
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700648 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 // This callback is called from the vr flinger dispatch thread. We
650 // need to call signalTransaction(), which requires holding
651 // mStateLock when we're not on the main thread. Acquiring
652 // mStateLock from the vr flinger dispatch thread might trigger a
653 // deadlock in surface flinger (see b/66916578), so post a message
654 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700656 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
657 mVrFlingerRequestsDisplay = requestDisplay;
658 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700659 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
662 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700663 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 .value_or(0),
665 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 if (!mVrFlinger) {
667 ALOGE("Failed to start vrflinger");
668 }
669 }
670
Mathias Agopian92a979a2012-08-02 18:32:23 -0700671 // initialize our drawing state
672 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700673
Andy McFadden13a082e2012-08-24 10:16:42 -0700674 // set initial conditions (e.g. unblank default device)
675 initializeDisplays();
676
Steven Thomas137d4bc2019-07-25 16:55:14 -0700677 char primeShaderCache[PROPERTY_VALUE_MAX];
678 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
679 if (atoi(primeShaderCache)) {
680 getRenderEngine().primeCache();
681 }
Dan Stoza4e637772016-07-28 13:31:51 -0700682
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700684
685 const bool presentFenceReliable =
686 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
687 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700697 Mutex::Autolock _l(mStateLock);
698
Romain Guy11d63f42017-07-20 12:47:14 -0700699 char value[PROPERTY_VALUE_MAX];
700
701 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800702 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700703 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800704 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100705
706 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700707 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800708
709 property_get("persist.sys.sf.color_mode", value, "0");
710 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700711
712 property_get("persist.sys.sf.disable_blurs", value, "0");
713 bool disableBlurs = atoi(value);
714 mDisableBlurs = disableBlurs;
715 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700716}
717
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800719 // Start boot animation service by setting a property mailbox
720 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700721 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800722 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 if (mStartPropertySetThread->join() != NO_ERROR) {
724 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800725 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700726}
727
Mathias Agopian875d8e12013-06-07 15:35:48 -0700728size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700729 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700730}
731
Mathias Agopian875d8e12013-06-07 15:35:48 -0700732size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700733 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700734}
735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800737
Jamie Gennis582270d2011-08-17 18:19:00 -0700738bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800739 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800740 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800741 return authenticateSurfaceTextureLocked(bufferProducer);
742}
743
744bool SurfaceFlinger::authenticateSurfaceTextureLocked(
745 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800746 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800747 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800748}
749
Brian Anderson6b376712017-04-04 10:51:39 -0700750status_t SurfaceFlinger::getSupportedFrameTimestamps(
751 std::vector<FrameEvent>* outSupported) const {
752 *outSupported = {
753 FrameEvent::REQUESTED_PRESENT,
754 FrameEvent::ACQUIRE,
755 FrameEvent::LATCH,
756 FrameEvent::FIRST_REFRESH_START,
757 FrameEvent::LAST_REFRESH_START,
758 FrameEvent::GPU_COMPOSITION_DONE,
759 FrameEvent::DEQUEUE_READY,
760 FrameEvent::RELEASE,
761 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700762 ConditionalLock _l(mStateLock,
763 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700764 if (!getHwComposer().hasCapability(
765 HWC2::Capability::PresentFenceIsNotReliable)) {
766 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
767 }
768 return NO_ERROR;
769}
770
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800771status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
772 if (!displayToken || !state) {
773 return BAD_VALUE;
774 }
775
776 Mutex::Autolock lock(mStateLock);
777
778 const auto display = getDisplayDeviceLocked(displayToken);
779 if (!display) {
780 return NAME_NOT_FOUND;
781 }
782
783 state->layerStack = display->getLayerStack();
784 state->orientation = display->getOrientation();
785
786 const Rect viewport = display->getViewport();
787 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
788
789 return NO_ERROR;
790}
791
792status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
793 if (!displayToken || !info) {
794 return BAD_VALUE;
795 }
796
797 Mutex::Autolock lock(mStateLock);
798
799 const auto display = getDisplayDeviceLocked(displayToken);
800 if (!display) {
801 return NAME_NOT_FOUND;
802 }
803
Dominik Laskowski55c85402020-01-21 16:25:47 -0800804 if (const auto connectionType = display->getConnectionType())
805 info->connectionType = *connectionType;
806 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800807 return INVALID_OPERATION;
808 }
809
810 if (mEmulatedDisplayDensity) {
811 info->density = mEmulatedDisplayDensity;
812 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800813 info->density = info->connectionType == DisplayConnectionType::Internal
814 ? mInternalDisplayDensity
815 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800816 }
817
818 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200819 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800820
821 return NO_ERROR;
822}
823
Dominik Laskowski22488f62019-03-28 09:53:04 -0700824status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700826 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 return BAD_VALUE;
828 }
829
Dominik Laskowski22488f62019-03-28 09:53:04 -0700830 Mutex::Autolock lock(mStateLock);
831
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800832 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700833 if (!displayId) {
834 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700835 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800837 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dominik Laskowski075d3172018-05-24 15:50:06 -0700841 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800842 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 auto width = hwConfig->getWidth();
845 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 auto xDpi = hwConfig->getDpiX();
848 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800850 if (isInternal &&
851 (internalDisplayOrientation == ui::ROTATION_90 ||
852 internalDisplayOrientation == ui::ROTATION_270)) {
853 std::swap(width, height);
854 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 }
856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800858
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800859 if (mEmulatedDisplayDensity) {
860 config.xDpi = mEmulatedDisplayDensity;
861 config.yDpi = mEmulatedDisplayDensity;
862 } else {
863 config.xDpi = xDpi;
864 config.yDpi = yDpi;
865 }
866
867 const nsecs_t period = hwConfig->getVsyncPeriod();
868 config.refreshRate = 1e9f / period;
869
870 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
871 config.appVsyncOffset = offsets.late.app;
872 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800873 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874
Andy McFadden91b2ca82014-06-13 14:04:23 -0700875 // This is how far in advance a buffer must be queued for
876 // presentation at a given time. If you want a buffer to appear
877 // on the screen at time N, you must submit the buffer before
878 // (N - presentationDeadline).
879 //
880 // Normally it's one full refresh period (to give SF a chance to
881 // latch the buffer), but this can be reduced by configuring a
882 // DispSync offset. Any additional delays introduced by the hardware
883 // composer or panel must be accounted for here.
884 //
885 // We add an additional 1ms to allow for processing time and
886 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800887 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800889 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 return NO_ERROR;
893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700895status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
896 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700897 return BAD_VALUE;
898 }
899
Ana Krulecc2870422019-01-29 19:00:58 -0800900 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return NO_ERROR;
902}
903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
905 const auto display = getDisplayDevice(displayToken);
906 if (!display) {
907 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800908 return BAD_VALUE;
909 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700910
Steven Thomasc9098452019-09-30 17:15:05 -0700911 if (display->isPrimary()) {
912 std::lock_guard<std::mutex> lock(mActiveConfigLock);
913 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800914 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700915 }
Steven Thomasc9098452019-09-30 17:15:05 -0700916 }
Ady Abraham2139f732019-11-13 18:56:40 -0800917
918 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Ady Abraham03b02dd2019-03-21 15:40:11 -0700921void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800923 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800924 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800925
Ady Abrahamb838aed2019-02-12 15:30:16 -0800926 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800927 if (mDesiredActiveConfigChanged) {
928 // If a config change is pending, just cache the latest request in
929 // mDesiredActiveConfig
930 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
931 mDesiredActiveConfig = info;
932 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
933 } else {
934 // Check is we are already at the desired config
935 const auto display = getDefaultDisplayDeviceLocked();
936 if (!display || display->getActiveConfig() == refreshRate.configId) {
937 return;
938 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800939
Ady Abraham59db0a32020-03-02 18:04:20 -0800940 // Initiate a config change.
941 mDesiredActiveConfigChanged = true;
942 mDesiredActiveConfig = info;
943
Ady Abrahamb838aed2019-02-12 15:30:16 -0800944 // This will trigger HWC refresh without resetting the idle timer.
945 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700946 // Start receiving vsync samples now, so that we can detect a period
947 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800948 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700949 // As we called to set period, we will call to onRefreshRateChangeCompleted once
950 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700951 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800952
Ady Abraham9e16a482019-12-03 17:19:41 -0800953 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
954 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700956
957 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800958 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700959 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960}
961
962status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
963 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800964
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100965 if (!displayToken) {
966 return BAD_VALUE;
967 }
Ady Abraham838de062019-02-04 10:24:03 -0800968
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100969 status_t result = NO_ERROR;
970
971 postMessageSync(new LambdaMessage([&]() {
972 const auto display = getDisplayDeviceLocked(displayToken);
973 if (!display) {
974 ALOGE("Attempt to set allowed display configs for invalid display token %p",
975 displayToken.get());
976 result = BAD_VALUE;
977 } else if (display->isVirtual()) {
978 ALOGW("Attempt to set allowed display configs for virtual display");
979 result = BAD_VALUE;
980 } else {
981 HwcConfigIndexType config(mode);
982 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
983 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
984 refreshRate.fps);
985 }
986 }));
987
988 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991void SurfaceFlinger::setActiveConfigInternal() {
992 ATRACE_CALL();
993
Dominik Laskowski22488f62019-03-28 09:53:04 -0700994 const auto display = getDefaultDisplayDeviceLocked();
995 if (!display) {
996 return;
997 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998
Dominik Laskowski22488f62019-03-28 09:53:04 -0700999 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001000 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001001 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002 display->setActiveConfig(mUpcomingActiveConfig.configId);
1003
Ady Abraham2e1dd892020-03-05 13:48:36 -08001004 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001005 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -08001006 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1007 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001008 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001009
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001010 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001011 const nsecs_t vsyncPeriod =
1012 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1013 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001014 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001015 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001016 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017}
1018
Ady Abraham53852a52019-05-28 18:07:44 -07001019void SurfaceFlinger::desiredActiveConfigChangeDone() {
1020 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1021 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1022 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001023
Ady Abraham2e1dd892020-03-05 13:48:36 -08001024 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001025 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001026 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001027 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1028 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001029}
1030
Dominik Laskowski22488f62019-03-28 09:53:04 -07001031bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001032 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001033 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001035 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001037 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 return true;
1039 }
1040
1041 // We received the present fence from the HWC, so we assume it successfully updated
1042 // the config, hence we update SF.
1043 mCheckPendingFence = false;
1044 setActiveConfigInternal();
1045 }
1046
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001047 // Store the local variable to release the lock.
1048 ActiveConfigInfo desiredActiveConfig;
1049 {
1050 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001051 if (!mDesiredActiveConfigChanged) {
1052 return false;
1053 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001054 desiredActiveConfig = mDesiredActiveConfig;
1055 }
1056
Ady Abraham2e1dd892020-03-05 13:48:36 -08001057 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001058 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1059 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1060 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001061 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001062 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1063 // display is not valid or we are already in the requested mode
1064 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001065 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001066 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001067 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001068
Ady Abraham838de062019-02-04 10:24:03 -08001069 // Desired active config was set, it is different than the config currently in use, however
1070 // allowed configs might have change by the time we process the refresh.
1071 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001072 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001073 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001074 return false;
1075 }
Alec Mouri7f015182019-07-11 13:56:22 -07001076
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 mUpcomingActiveConfig = desiredActiveConfig;
1078 const auto displayId = display->getId();
1079 LOG_ALWAYS_FATAL_IF(!displayId);
1080
Ady Abraham2139f732019-11-13 18:56:40 -08001081 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001083 // TODO(b/142753666) use constrains
1084 HWC2::VsyncPeriodChangeConstraints constraints;
1085 constraints.desiredTimeNanos = systemTime();
1086 constraints.seamlessRequired = false;
1087
1088 HWC2::VsyncPeriodChangeTimeline outTimeline;
1089 auto status =
1090 getHwComposer().setActiveConfigWithConstraints(*displayId,
1091 mUpcomingActiveConfig.configId.value(),
1092 constraints, &outTimeline);
1093 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001094 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1095 // to be sent. We just log the error in this case.
1096 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001097 return false;
1098 }
1099
1100 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1101 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001102 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001103 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001104}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1107 Vector<ColorMode>* outColorModes) {
1108 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001109 return BAD_VALUE;
1110 }
1111
Peiyong Lina52f0292018-03-14 17:26:31 -07001112 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001113 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001114 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001115 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1116
1117 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1118 if (!displayId) {
1119 return NAME_NOT_FOUND;
1120 }
1121
Dominik Laskowski075d3172018-05-24 15:50:06 -07001122 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001123 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001124 }
Michael Wright28f24d02016-07-12 13:30:53 -07001125 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001126
1127 // If it's built-in display and the configuration claims it's not wide color capable,
1128 // filter out all wide color modes. The typical reason why this happens is that the
1129 // hardware is not good enough to support GPU composition of wide color, and thus the
1130 // OEMs choose to disable this capability.
1131 if (isInternalDisplay && !hasWideColorDisplay) {
1132 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1133 isWideColorMode);
1134 } else {
1135 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1136 }
Michael Wright28f24d02016-07-12 13:30:53 -07001137
1138 return NO_ERROR;
1139}
1140
Daniel Solomon42d04562019-01-20 21:03:19 -08001141status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1142 ui::DisplayPrimaries &primaries) {
1143 if (!displayToken) {
1144 return BAD_VALUE;
1145 }
1146
1147 // Currently we only support this API for a single internal display.
1148 if (getInternalDisplayToken() != displayToken) {
1149 return BAD_VALUE;
1150 }
1151
1152 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1153 return NO_ERROR;
1154}
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1157 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001158 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001159 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001160 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001161}
1162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001164 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165 Vector<ColorMode> modes;
1166 getDisplayColorModes(displayToken, &modes);
1167 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1168 if (mode < ColorMode::NATIVE || !exists) {
1169 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1170 decodeColorMode(mode).c_str(), mode, displayToken.get());
1171 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001172 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173 const auto display = getDisplayDevice(displayToken);
1174 if (!display) {
1175 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1176 decodeColorMode(mode).c_str(), mode, displayToken.get());
1177 } else if (display->isVirtual()) {
1178 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1179 decodeColorMode(mode).c_str(), mode);
1180 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001181 display->getCompositionDisplay()->setColorProfile(
1182 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1183 RenderIntent::COLORIMETRIC,
1184 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185 }
1186 }));
1187
Michael Wright28f24d02016-07-12 13:30:53 -07001188 return NO_ERROR;
1189}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001190
Galia Peycheva5492cb52019-10-30 14:13:16 +01001191status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1192 bool* outSupport) const {
1193 Mutex::Autolock _l(mStateLock);
1194
1195 if (!displayToken) {
1196 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1197 return BAD_VALUE;
1198 }
1199 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1200 if (!displayId) {
1201 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1202 displayToken.get());
1203 return NAME_NOT_FOUND;
1204 }
1205 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1206 HWC2::DisplayCapability::AutoLowLatencyMode);
1207 return NO_ERROR;
1208}
1209
1210void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1211 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1212}
1213
1214void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1215 if (!displayToken) {
1216 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1217 return;
1218 }
1219 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1220 if (!displayId) {
1221 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1222 displayToken.get());
1223 return;
1224 }
1225
1226 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1227}
1228
1229status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1230 bool* outSupport) const {
1231 Mutex::Autolock _l(mStateLock);
1232
1233 if (!displayToken) {
1234 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1235 return BAD_VALUE;
1236 }
1237 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1238 if (!displayId) {
1239 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1240 displayToken.get());
1241 return NAME_NOT_FOUND;
1242 }
1243
1244 std::vector<HWC2::ContentType> outSupportedContentTypes;
1245 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1246 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1247 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1248 return NO_ERROR;
1249}
1250
1251void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1252 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1253}
1254
1255void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1256 if (!displayToken) {
1257 ALOGE("setGameContentType() failed. Missing display token.");
1258 return;
1259 }
1260 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1261 if (!displayId) {
1262 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1263 displayToken.get());
1264 return;
1265 }
1266
1267 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1268 getHwComposer().setContentType(*displayId, type);
1269}
1270
Svetoslavd85084b2014-03-20 10:28:31 -07001271status_t SurfaceFlinger::clearAnimationFrameStats() {
1272 Mutex::Autolock _l(mStateLock);
1273 mAnimFrameTracker.clearStats();
1274 return NO_ERROR;
1275}
1276
1277status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1278 Mutex::Autolock _l(mStateLock);
1279 mAnimFrameTracker.getStats(outStats);
1280 return NO_ERROR;
1281}
1282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001283status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1284 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001285 Mutex::Autolock _l(mStateLock);
1286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001287 const auto display = getDisplayDeviceLocked(displayToken);
1288 if (!display) {
1289 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001290 return BAD_VALUE;
1291 }
1292
Peiyong Linfb069302018-04-25 14:34:31 -07001293 // At this point the DisplayDeivce should already be set up,
1294 // meaning the luminance information is already queried from
1295 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001296 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001297 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1298 capabilities.getDesiredMaxLuminance(),
1299 capabilities.getDesiredMaxAverageLuminance(),
1300 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001301
1302 return NO_ERROR;
1303}
1304
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001305std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1306 const DisplayDevice& display) const {
1307 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1308 // avoid repetitive HAL IPC and EDID parsing.
1309 const auto displayId = display.getId();
1310 LOG_FATAL_IF(!displayId);
1311
1312 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1313 LOG_FATAL_IF(!hwcDisplayId);
1314
1315 uint8_t port;
1316 DisplayIdentificationData data;
1317 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1318 ALOGV("%s: No identification data.", __FUNCTION__);
1319 return {};
1320 }
1321
1322 const auto info = parseDisplayIdentificationData(port, data);
1323 if (!info) {
1324 return {};
1325 }
1326 return info->deviceProductInfo;
1327}
1328
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001329status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1330 ui::PixelFormat* outFormat,
1331 ui::Dataspace* outDataspace,
1332 uint8_t* outComponentMask) const {
1333 if (!outFormat || !outDataspace || !outComponentMask) {
1334 return BAD_VALUE;
1335 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001336 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001337 if (!display || !display->getId()) {
1338 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1339 return BAD_VALUE;
1340 }
1341 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1342 outDataspace, outComponentMask);
1343}
1344
Kevin DuBois74e53772018-11-19 10:52:38 -08001345status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1346 bool enable, uint8_t componentMask,
1347 uint64_t maxFrames) const {
1348 const auto display = getDisplayDevice(displayToken);
1349 if (!display || !display->getId()) {
1350 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1351 return BAD_VALUE;
1352 }
1353
1354 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1355 componentMask, maxFrames);
1356}
1357
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001358status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1359 uint64_t maxFrames, uint64_t timestamp,
1360 DisplayedFrameStats* outStats) const {
1361 const auto display = getDisplayDevice(displayToken);
1362 if (!display || !display->getId()) {
1363 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1364 return BAD_VALUE;
1365 }
1366
1367 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1368 outStats);
1369}
1370
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001371status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1372 if (!outSupported) {
1373 return BAD_VALUE;
1374 }
1375 *outSupported = getRenderEngine().supportsProtectedContent();
1376 return NO_ERROR;
1377}
1378
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001379status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1380 bool* outIsWideColorDisplay) const {
1381 if (!displayToken || !outIsWideColorDisplay) {
1382 return BAD_VALUE;
1383 }
1384 Mutex::Autolock _l(mStateLock);
1385 const auto display = getDisplayDeviceLocked(displayToken);
1386 if (!display) {
1387 return BAD_VALUE;
1388 }
Peiyong Linff84a152019-05-17 18:36:19 -07001389
1390 // Use hasWideColorDisplay to override built-in display.
1391 const auto displayId = display->getId();
1392 if (displayId && displayId == getInternalDisplayIdLocked()) {
1393 *outIsWideColorDisplay = hasWideColorDisplay;
1394 return NO_ERROR;
1395 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001396 *outIsWideColorDisplay = display->hasWideColorGamut();
1397 return NO_ERROR;
1398}
1399
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001400status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001401 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001402 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403
Dominik Laskowski6505f792019-09-18 11:10:05 -07001404 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1405 mEventQueue->setEventConnection(
1406 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001408 }));
1409
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410 return NO_ERROR;
1411}
1412
1413status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001414 Mutex::Autolock lock(mStateLock);
1415 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001416}
1417
Lloyd Pique755e3192018-01-31 16:46:15 -08001418status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1419 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001420 // Try to acquire a lock for 1s, fail gracefully
1421 const status_t err = mStateLock.timedLock(s2ns(1));
1422 const bool locked = (err == NO_ERROR);
1423 if (!locked) {
1424 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1425 return TIMED_OUT;
1426 }
1427
1428 outLayers->clear();
1429 mCurrentState.traverseInZOrder([&](Layer* layer) {
1430 outLayers->push_back(layer->getLayerDebugInfo());
1431 });
1432
1433 mStateLock.unlock();
1434 return NO_ERROR;
1435}
1436
Peiyong Linc6780972018-10-28 15:24:08 -07001437status_t SurfaceFlinger::getCompositionPreference(
1438 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1439 Dataspace* outWideColorGamutDataspace,
1440 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001441 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001442 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001443 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001444 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001445 return NO_ERROR;
1446}
1447
Dan Stozaec460082018-12-17 15:35:09 -08001448status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1449 const sp<IBinder>& stopLayerHandle,
1450 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001451 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001452 return BAD_VALUE;
1453 }
1454 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001455 return NO_ERROR;
1456}
1457
Dan Stozaec460082018-12-17 15:35:09 -08001458status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001459 if (!listener) {
1460 return BAD_VALUE;
1461 }
Dan Stozaec460082018-12-17 15:35:09 -08001462 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001463 return NO_ERROR;
1464}
Dan Gittik57e63c52019-01-18 16:37:54 +00001465
1466status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1467 bool* outSupport) const {
1468 if (!displayToken || !outSupport) {
1469 return BAD_VALUE;
1470 }
1471 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1472 if (!displayId) {
1473 return NAME_NOT_FOUND;
1474 }
1475 *outSupport =
1476 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1477 return NO_ERROR;
1478}
1479
1480status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1481 float brightness) const {
1482 if (!displayToken) {
1483 return BAD_VALUE;
1484 }
1485 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1486 if (!displayId) {
1487 return NAME_NOT_FOUND;
1488 }
1489 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1490}
1491
Ady Abraham8532d012019-05-08 14:50:56 -07001492status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1493 PowerHint powerHint = static_cast<PowerHint>(hintId);
1494
1495 if (powerHint == PowerHint::INTERACTION) {
1496 mScheduler->notifyTouchEvent();
1497 }
1498
1499 return NO_ERROR;
1500}
1501
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001502// ----------------------------------------------------------------------------
1503
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001504sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001505 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001506 const auto& handle =
1507 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001508
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001509 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001510}
1511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001512// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513
1514void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516}
1517
1518void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001519 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001520 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001521 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522}
1523
1524void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001525 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001526 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001527 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528}
1529
1530void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001531 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001532 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001533}
1534
1535status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001536 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001537 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538}
1539
1540status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001541 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001542 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543 if (res == NO_ERROR) {
1544 msg->wait();
1545 }
1546 return res;
1547}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001549void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001550 do {
1551 waitForEvent();
1552 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001553}
1554
Dominik Laskowski83b88212018-12-11 13:34:06 -08001555nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001556 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001557 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1558 return 0;
1559 }
1560
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001561 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001562}
1563
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001564void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001565 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001566 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001567 ATRACE_NAME("SF onVsync");
1568
Steven Thomas3cfac282017-02-06 12:29:30 -08001569 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001570 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001571 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 return;
1573 }
1574
Dominik Laskowski075d3172018-05-24 15:50:06 -07001575 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001576 return;
1577 }
1578
Dominik Laskowski075d3172018-05-24 15:50:06 -07001579 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001580 // For now, we don't do anything with external display vsyncs.
1581 return;
1582 }
1583
Alec Mourif8e689c2019-05-20 18:32:22 -07001584 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001585 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001586 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001587 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001588 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001589}
1590
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001591void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001592 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1593 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594}
1595
Ady Abraham2139f732019-11-13 18:56:40 -08001596bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001597 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001598}
1599
Ady Abraham2139f732019-11-13 18:56:40 -08001600void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1601 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001602 const auto display = getDefaultDisplayDeviceLocked();
1603 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001604 return;
1605 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001606 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001607
Ana Krulec7d1d6832018-12-27 11:10:09 -08001608 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001609 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1610 ALOGV("Skipping config %d as it is not part of allowed configs",
1611 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001612 return;
1613 }
1614
Ady Abraham2139f732019-11-13 18:56:40 -08001615 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001616}
1617
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001618void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001619 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001620 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001621 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Piqueba04e622017-12-14 17:11:26 -08001623 // Ignore events that do not have the right sequenceId.
1624 if (sequenceId != getBE().mComposerSequenceId) {
1625 return;
1626 }
1627
Steven Thomasb02664d2017-07-26 18:48:28 -07001628 // Only lock if we're not on the main thread. This function is normally
1629 // called on a hwbinder thread, but for the primary display it's called on
1630 // the main thread with the state lock already held, so don't attempt to
1631 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001632 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001633
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001634 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001635
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001636 if (std::this_thread::get_id() == mMainThreadId) {
1637 // Process all pending hot plug events immediately if we are on the main thread.
1638 processDisplayHotplugEventsLocked();
1639 }
1640
Lloyd Piqueba04e622017-12-14 17:11:26 -08001641 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001642}
1643
Ady Abraham7159f572019-10-11 11:10:18 -07001644void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001645 int32_t sequenceId, hwc2_display_t /*display*/,
1646 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1647 Mutex::Autolock lock(mStateLock);
1648 if (sequenceId != getBE().mComposerSequenceId) {
1649 return;
1650 }
1651 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001652}
1653
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001654void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1655 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1656 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1657}
1658
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001659void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001660 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001661 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001662 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001663 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001664 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001665}
1666
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001667void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001668 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001669
1670 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1671 // display power state.
1672 postMessageAsync(new LambdaMessage(
1673 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1674}
1675
1676void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1677 ATRACE_CALL();
1678
Ady Abraham27c70212019-06-11 10:52:26 -07001679 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1680
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001681 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001682 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1683 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001684 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001685 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001686 }
Mathias Agopian86303202012-07-24 22:46:10 -07001687}
1688
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001689// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001690void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001691 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001692 // Clear the drawing state so that the logic inside of
1693 // handleTransactionLocked will fire. It will determine the delta between
1694 // mCurrentState and mDrawingState and re-apply all changes when we make the
1695 // transition.
1696 mDrawingState.displays.clear();
1697 mDisplays.clear();
1698}
1699
Steven Thomas050b2c82017-03-06 11:45:16 -08001700void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001701 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001702 if (!mVrFlinger)
1703 return;
1704 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001705 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001706 return;
1707 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001708
Lloyd Pique441d5042018-10-18 16:49:51 -07001709 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001710 ALOGE("Vr flinger is only supported for remote hardware composer"
1711 " service connections. Ignoring request to transition to vr"
1712 " flinger.");
1713 mVrFlingerRequestsDisplay = false;
1714 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001715 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001716
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001718
Steven Thomas0123ac62018-07-12 11:32:34 -07001719 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001720 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001721
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001722 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001723
1724 // Clear out all the output layers from the composition engine for all
1725 // displays before destroying the hardware composer interface. This ensures
1726 // any HWC layers are destroyed through that interface before it becomes
1727 // invalid.
1728 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001729 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001730 }
1731
Steven Thomas0123ac62018-07-12 11:32:34 -07001732 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1733 // called below. Clear the reference now so we don't accidentally use it
1734 // later.
1735 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001736
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001738 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001739 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001740
Steven Thomasb02664d2017-07-26 18:48:28 -07001741 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001742 // Delete the current instance before creating the new one
1743 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1744 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1745 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001746 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001747
Lloyd Pique441d5042018-10-18 16:49:51 -07001748 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001749 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001750
1751 if (vrFlingerRequestsDisplay) {
1752 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001753 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001754
1755 mVisibleRegionsDirty = true;
1756 invalidateHwcGeometry();
1757
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001758 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001759 display = getDefaultDisplayDeviceLocked();
1760 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001761 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001762
Steven Thomasb02664d2017-07-26 18:48:28 -07001763 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001764 const nsecs_t vsyncPeriod = getVsyncPeriod();
1765 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001766
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001767 // The present fences returned from vr_hwc are not an accurate
1768 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001769 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001770
Steven Thomasb02664d2017-07-26 18:48:28 -07001771 // Use phase of 0 since phase is not known.
1772 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001773 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001774 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001775
Ana Krulecc2870422019-01-29 19:00:58 -08001776 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001777
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001778 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001779 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001780}
1781
Ady Abraham11579302019-09-19 12:35:58 -07001782bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1783 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001784 // We are storing the last 2 present fences. If sf's phase offset is to be
1785 // woken up before the actual vsync but targeting the next vsync, we need to check
1786 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001787 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1788 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001789
Ady Abraham11579302019-09-19 12:35:58 -07001790 if (fence == Fence::NO_FENCE) {
1791 return false;
1792 }
1793
1794 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1795 fence->wait(graceTimeMs);
1796 }
1797
1798 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001799}
1800
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001801void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001802 DisplayStatInfo stats;
1803 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001804 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001805 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001806 mExpectedPresentTime.store(
1807 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001808}
1809
Dominik Laskowski22488f62019-03-28 09:53:04 -07001810void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001811 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001812 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001813 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001814 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001815 // calculate the expected present time once and use the cached
1816 // value throughout this frame to make sure all layers are
1817 // seeing this same value.
1818 populateExpectedPresentTime();
1819
Ady Abraham11579302019-09-19 12:35:58 -07001820 // When Backpressure propagation is enabled we want to give a small grace period
1821 // for the present fence to fire instead of just giving up on this frame to handle cases
1822 // where present fence is just about to get signaled.
1823 const int graceTimeForPresentFenceMs =
1824 (mPropagateBackpressure &&
1825 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1826 ? 1
1827 : 0;
1828 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1829 previousFrameMissed(
1830 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001831 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1832 mHadDeviceComposition && frameMissed};
1833 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1834 mHadClientComposition && frameMissed};
1835
Alec Mouricc0fc602019-02-26 21:45:19 -08001836 if (frameMissed) {
1837 mFrameMissedCount++;
1838 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001839 if (mMissedFrameJankCount == 0) {
1840 mMissedFrameJankStart = systemTime();
1841 }
1842 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001843 }
1844
Alec Mouri40189b02019-03-05 15:07:54 -08001845 if (hwcFrameMissed) {
1846 mHwcFrameMissedCount++;
1847 }
1848
1849 if (gpuFrameMissed) {
1850 mGpuFrameMissedCount++;
1851 }
1852
Ady Abrahamadb9a992019-09-19 21:21:55 +00001853 if (frameMissed && mPropagateBackpressure) {
1854 if ((hwcFrameMissed && !gpuFrameMissed) ||
1855 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001856 signalLayerUpdate();
1857 break;
1858 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001859 }
Dan Stoza50182882016-07-08 12:02:20 -07001860
Alec Mouri5f487d42020-02-06 09:26:19 -08001861 // Our jank window is always at least 100ms since we missed a
1862 // frame...
1863 static constexpr nsecs_t kMinJankyDuration =
1864 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1865 // ...but if it's larger than 1s then we missed the trace cutoff.
1866 static constexpr nsecs_t kMaxJankyDuration =
1867 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1868 // If we're in a user build then don't push any atoms
1869 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1870 const auto displayDevice = getDefaultDisplayDeviceLocked();
1871 // Only report jank when the display is on, as displays in DOZE
1872 // power mode may operate at a different frame rate than is
1873 // reported in their config, which causes noticeable (but less
1874 // severe) jank.
1875 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1876 const nsecs_t currentTime = systemTime();
1877 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1878 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1879 ATRACE_NAME("Jank detected");
1880 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1881 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1882 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1883 jankyDurationMillis, mMissedFrameJankCount);
1884 }
1885
1886 // We either reported a jank event or we missed the trace
1887 // window, so clear counters here.
1888 if (jankDuration > kMinJankyDuration) {
1889 mMissedFrameJankCount = 0;
1890 mMissedFrameJankStart = 0;
1891 }
1892 }
1893 }
1894
Steven Thomas050b2c82017-03-06 11:45:16 -08001895 // Now that we're going to make it to the handleMessageTransaction()
1896 // call below it's safe to call updateVrFlinger(), which will
1897 // potentially trigger a display handoff.
1898 updateVrFlinger();
1899
Dan Stoza6b9454d2014-11-07 16:00:59 -08001900 bool refreshNeeded = handleMessageTransaction();
1901 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001902
Ana Krulecc84d09b2019-11-02 23:10:29 +01001903 // Layers need to get updated (in the previous line) before we can use them for
1904 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001905 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1906 // and may eventually call to ~Layer() if it holds the last reference
1907 {
1908 Mutex::Autolock _l(mStateLock);
1909 mScheduler->chooseRefreshRateForContent();
1910 }
1911
Ana Krulecc84d09b2019-11-02 23:10:29 +01001912 if (performSetActiveConfig()) {
1913 break;
1914 }
1915
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001916 updateCursorAsync();
1917 updateInputFlinger();
1918
Dan Stoza58784442014-12-02 16:58:17 -08001919 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001920 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001921 // Signal a refresh if a transaction modified the window state,
1922 // a new buffer was latched, or if HWC has requested a full
1923 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001924 if (mFrameStartTime <= 0) {
1925 // We should only use the time of the first invalidate
1926 // message that signals a refresh as the beginning of the
1927 // frame. Otherwise the real frame time will be
1928 // underestimated.
1929 mFrameStartTime = frameStart;
1930 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001931 signalRefresh();
1932 }
1933 break;
1934 }
1935 case MessageQueue::REFRESH: {
1936 handleMessageRefresh();
1937 break;
1938 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001939 }
1940}
1941
Dan Stoza6b9454d2014-11-07 16:00:59 -08001942bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001943 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001944 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001945
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001946 bool flushedATransaction = flushTransactionQueues();
1947
1948 bool runHandleTransaction = transactionFlags &&
1949 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1950
1951 if (runHandleTransaction) {
1952 handleTransaction(eTransactionMask);
1953 } else {
1954 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001955 }
1956
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001957 if (transactionFlushNeeded()) {
1958 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001959 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001960
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001961 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001962}
1963
Mathias Agopian4fec8732012-06-29 14:12:52 -07001964void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001966
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001967 mRefreshPending = false;
1968
Lloyd Piqueab039b52019-02-13 14:22:42 -08001969 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001970 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001971 for (const auto& [_, display] : mDisplays) {
1972 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1973 }
1974 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001975 if (auto layerFE = layer->getCompositionEngineLayerFE())
1976 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001977 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001978 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1979 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001980 if (auto layerFE = layer->getCompositionEngineLayerFE())
1981 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001982 }
1983
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001984 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001985 refreshArgs.outputColorSetting = useColorManagement
1986 ? mDisplayColorSetting
1987 : compositionengine::OutputColorSetting::kUnmanaged;
1988 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1989 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001990
1991 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1992 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001993 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001994
1995 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1996 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1997 mDrawingState.colorMatrixChanged = false;
1998 }
1999
2000 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2001
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002002 if (mDebugRegion != 0) {
2003 refreshArgs.devOptFlashDirtyRegionsDelay =
2004 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2005 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002006
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002007 mGeometryInvalid = false;
2008
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002009 // Store the present time just before calling to the composition engine so we could notify
2010 // the scheduler.
2011 const auto presentTime = systemTime();
2012
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002013 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002014 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2015 // Reset the frame start time now that we've recorded this frame.
2016 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002017
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002018 mScheduler->onDisplayRefreshed(presentTime);
2019
David Sodmanfa9b2af2017-12-24 13:28:59 -08002020 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002021 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002022
Lloyd Pique66d68602019-02-13 14:23:31 -08002023 mHadClientComposition =
2024 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2025 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002026 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2027 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002028 });
2029 mHadDeviceComposition =
2030 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2031 auto& displayDevice = tokenDisplayPair.second;
2032 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2033 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002034 mReusedClientComposition =
2035 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2036 auto& displayDevice = tokenDisplayPair.second;
2037 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2038 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002039
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002040 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002041
David Sodman7e4ae112018-02-09 15:02:28 -08002042 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002043 if (mVisibleRegionsDirty) {
2044 mVisibleRegionsDirty = false;
2045 if (mTracingEnabled) {
2046 mTracing.notify("visibleRegionsDirty");
2047 }
2048 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002049
2050 if (mCompositionEngine->needsAnotherUpdate()) {
2051 signalLayerUpdate();
2052 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002054
David Sodmanfa9b2af2017-12-24 13:28:59 -08002055
2056bool SurfaceFlinger::handleMessageInvalidate() {
2057 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002058 bool refreshNeeded = handlePageFlip();
2059
Vishnu Nair4351ad52019-02-11 14:13:02 -08002060 if (mVisibleRegionsDirty) {
2061 computeLayerBounds();
2062 }
2063
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002064 for (auto& layer : mLayersPendingRefresh) {
2065 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002066 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002067 invalidateLayerStack(layer, visibleReg);
2068 }
2069 mLayersPendingRefresh.clear();
2070 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002071}
2072
Ana Krulece588e312018-09-18 12:32:24 -07002073void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2074 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075 // Update queue of past composite+present times and determine the
2076 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002077 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002078 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002079 while (!getBE().mCompositePresentTimes.empty()) {
2080 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081 // Cached values should have been updated before calling this method,
2082 // which helps avoid duplicate syscalls.
2083 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2084 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2085 break;
2086 }
2087 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002088 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089 }
2090
2091 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002092 while (getBE().mCompositePresentTimes.size() > 16) {
2093 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002094 }
2095
Ana Krulece588e312018-09-18 12:32:24 -07002096 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002097}
2098
Ana Krulece588e312018-09-18 12:32:24 -07002099void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2100 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101 // Integer division and modulo round toward 0 not -inf, so we need to
2102 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002103 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2104 ? (stats.vsyncPeriod -
2105 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2106 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002107
Ady Abraham9e16a482019-12-03 17:19:41 -08002108 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002109 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002110 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002111 }
2112
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002113 // Snap the latency to a value that removes scheduling jitter from the
2114 // composition and present times, which often have >1ms of jitter.
2115 // Reducing jitter is important if an app attempts to extrapolate
2116 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002117 // Snapping also allows an app to precisely calculate
2118 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002119 nsecs_t bias = stats.vsyncPeriod / 2;
2120 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2121 nsecs_t snappedCompositeToPresentLatency =
2122 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002123
David Sodman99974d22017-11-28 12:04:33 -08002124 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002125 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2126 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002127 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002128}
2129
David Sodman2b406362017-12-15 13:33:47 -08002130void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002131{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 ATRACE_CALL();
2133 ALOGV("postComposition");
2134
Brian Andersonf6386862016-10-31 16:34:13 -07002135 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002136 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002137 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002138 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002139 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002141
David Sodman73beded2017-11-15 11:56:06 -08002142 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002143 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002144 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002145 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002146 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2147 ->getRenderSurface()
2148 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002149 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002150 } else {
2151 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2152 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002153
David Sodman73beded2017-11-15 11:56:06 -08002154 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002155 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2156 mPreviousPresentFences[0] = displayDevice
2157 ? getHwComposer().getPresentFence(*displayDevice->getId())
2158 : Fence::NO_FENCE;
2159 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002160 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002161
Ana Krulece588e312018-09-18 12:32:24 -07002162 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002163 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002164
Lloyd Piqueab039b52019-02-13 14:22:42 -08002165 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2166 // be sampled a little later than when we started doing work for this frame,
2167 // but that should be okay since updateCompositorTiming has snapping logic.
2168 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2169 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002170 CompositorTiming compositorTiming;
2171 {
David Sodman99974d22017-11-28 12:04:33 -08002172 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2173 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002174 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002175
Edgar Arriaga844fa672020-01-16 14:21:42 -08002176 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002177 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2178 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002179 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002180 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002181 }
Robert Carr2047fae2016-11-28 14:09:09 -08002182 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002183
Ady Abraham92fa2f42020-02-11 15:33:56 -08002184 if (displayDevice && displayDevice->isPrimary() &&
2185 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002186 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002187 }
2188
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002189 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002190 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2191 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002192 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002193 }
2194 }
2195
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002196 if (mAnimCompositionPending) {
2197 mAnimCompositionPending = false;
2198
Brian Anderson4e606e32017-03-16 15:34:57 -07002199 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002200 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002201 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002202 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002203 // The HWC doesn't support present fences, so use the refresh
2204 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002205 const nsecs_t presentTime =
2206 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002207 mAnimFrameTracker.setActualPresentTime(presentTime);
2208 }
2209 mAnimFrameTracker.advanceFrame();
2210 }
Dan Stozab90cf072015-03-05 11:05:59 -08002211
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002212 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002213 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002214 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002215 }
2216
Vishnu Nair9b079a22020-01-21 14:36:08 -08002217 if (mReusedClientComposition) {
2218 mTimeStats->incrementClientCompositionReusedFrames();
2219 }
2220
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002221 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002222
Alec Mouri717bcb62020-02-10 17:07:19 -08002223 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2224 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2225 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2226
Lloyd Pique32cbe282018-10-19 13:09:22 -07002227 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2228 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002229 return;
2230 }
2231
2232 nsecs_t currentTime = systemTime();
2233 if (mHasPoweredOff) {
2234 mHasPoweredOff = false;
2235 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002236 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002237 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002238 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2239 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002240 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002241 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002242 }
David Sodman4a36e932017-11-07 14:29:47 -08002243 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002244 }
David Sodman4a36e932017-11-07 14:29:47 -08002245 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002246
2247 {
2248 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002249 if (mTexturePool.size() < mTexturePoolSize) {
2250 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002251 const size_t offset = mTexturePool.size();
2252 mTexturePool.resize(mTexturePoolSize);
2253 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2254 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002255 } else if (mTexturePool.size() > mTexturePoolSize) {
2256 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2257 const size_t offset = mTexturePoolSize;
2258 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2259 mTexturePool.resize(mTexturePoolSize);
2260 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002261 }
2262 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002263
Ady Abrahambe0f9482019-04-24 15:41:53 -07002264 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002265 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002266
Kevin DuBois413287f2019-02-25 08:46:47 -08002267 if (mLumaSampling && mRegionSamplingThread) {
2268 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002269 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002270
2271 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2272 // side-effect of getTotalSize(), so we check that again here
2273 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002274 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002275 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2276 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002277}
2278
Vishnu Nair4351ad52019-02-11 14:13:02 -08002279void SurfaceFlinger::computeLayerBounds() {
2280 for (const auto& pair : mDisplays) {
2281 const auto& displayDevice = pair.second;
2282 const auto display = displayDevice->getCompositionDisplay();
2283 for (const auto& layer : mDrawingState.layersSortedByZ) {
2284 // only consider the layers on the given layer stack
2285 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002286 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002287 }
2288
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002289 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2290 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002291 }
2292 }
2293}
2294
David Sodmanfa9b2af2017-12-24 13:28:59 -08002295void SurfaceFlinger::postFrame()
2296{
2297 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002298 const auto display = getDefaultDisplayDeviceLocked();
2299 if (display && getHwComposer().isConnected(*display->getId())) {
2300 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002301 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2302 logFrameStats();
2303 }
2304 }
2305}
2306
Mathias Agopian87baae12012-07-31 12:38:26 -07002307void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308{
Mathias Agopian841cde52012-03-01 15:44:37 -08002309 ATRACE_CALL();
2310
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002311 // here we keep a copy of the drawing state (that is the state that's
2312 // going to be overwritten by handleTransactionLocked()) outside of
2313 // mStateLock so that the side-effects of the State assignment
2314 // don't happen with mStateLock held (which can cause deadlocks).
2315 State drawingState(mDrawingState);
2316
Mathias Agopianca4d3602011-05-19 15:38:14 -07002317 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002318 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Mathias Agopianca4d3602011-05-19 15:38:14 -07002320 // Here we're guaranteed that some transaction flags are set
2321 // so we can call handleTransactionLocked() unconditionally.
2322 // We call getTransactionFlags(), which will also clear the flags,
2323 // with mStateLock held to guarantee that mCurrentState won't change
2324 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002325
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002326 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002327 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002328 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002329
Mathias Agopianca4d3602011-05-19 15:38:14 -07002330 mDebugInTransaction = 0;
2331 invalidateHwcGeometry();
2332 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002333}
2334
Lloyd Piqueba04e622017-12-14 17:11:26 -08002335void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2336 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 const std::optional<DisplayIdentificationInfo> info =
2338 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002341 continue;
2342 }
2343
Dominik Laskowski55c85402020-01-21 16:25:47 -08002344 const DisplayId displayId = info->id;
2345 const auto it = mPhysicalDisplayTokens.find(displayId);
2346
Lloyd Piqueba04e622017-12-14 17:11:26 -08002347 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002348 if (it == mPhysicalDisplayTokens.end()) {
2349 ALOGV("Creating display %s", to_string(displayId).c_str());
2350
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002351 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002352 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002353 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002354
Dominik Laskowski075d3172018-05-24 15:50:06 -07002355 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002356 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002357 state.isSecure = true; // All physical displays are currently considered secure.
2358 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002359
2360 sp<IBinder> token = new BBinder();
2361 mCurrentState.displays.add(token, state);
2362 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2363
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002365 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002367 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002368
Dominik Laskowski55c85402020-01-21 16:25:47 -08002369 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 if (index >= 0) {
2371 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2372 mInterceptor->saveDisplayDeletion(state.sequenceId);
2373 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002374 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002375 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002376 }
2377
2378 processDisplayChangesLocked();
2379 }
2380
2381 mPendingHotplugEvents.clear();
2382}
2383
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002384void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002385 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2386 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002387}
2388
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002390 const wp<IBinder>& displayToken,
2391 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002392 const DisplayDeviceState& state,
2393 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002395 auto displayId = compositionDisplay->getDisplayId();
2396 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002397 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002398 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002399 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002400 creationArgs.hasWideColorGamut = false;
2401 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002402
Dominik Laskowski55c85402020-01-21 16:25:47 -08002403 if (const auto& physical = state.physical) {
2404 creationArgs.connectionType = physical->type;
2405 }
2406
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002407 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 creationArgs.isPrimary = isInternalDisplay;
2409
2410 if (useColorManagement && displayId) {
2411 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002412 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002413 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002414 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002416
Dominik Laskowski7e045462018-05-30 13:02:02 -07002417 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002419 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420 }
tangrobin6753a022018-08-10 10:58:54 +08002421 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002422
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 if (displayId) {
2424 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002425 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002426 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002427 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428
Lloyd Pique90c115d2018-09-18 21:39:42 -07002429 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002431 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002432
Lloyd Pique99d3da52018-01-22 17:48:03 -08002433 // Make sure that composition can never be stalled by a virtual display
2434 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002435 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002436 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002437 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2438 }
2439
Dominik Laskowski718f9602019-11-09 20:01:35 -08002440 creationArgs.physicalOrientation =
2441 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002442
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002444 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445
Lloyd Pique9370a482019-10-03 17:58:30 -07002446 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002447
2448 if (maxFrameBufferAcquiredBuffers >= 3) {
2449 nativeWindowSurface->preallocateBuffers();
2450 }
2451
2452 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002453 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002454 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002456 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002457 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002458 display->getCompositionDisplay()->setColorProfile(
2459 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2460 RenderIntent::COLORIMETRIC,
2461 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002462 if (!state.isVirtual()) {
2463 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002464 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2465 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002466 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002467
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 display->setLayerStack(state.layerStack);
2469 display->setProjection(state.orientation, state.viewport, state.frame);
2470 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002472 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473}
2474
Marin Shalamanovae685592020-02-12 17:12:22 +01002475void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2476 const DisplayDeviceState& state) {
2477 int width = 0;
2478 int height = 0;
2479 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2480 if (state.physical) {
2481 const auto& activeConfig =
2482 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2483 width = activeConfig->getWidth();
2484 height = activeConfig->getHeight();
2485 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2486 } else if (state.surface != nullptr) {
2487 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2488 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2489 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2490 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2491 int intPixelFormat;
2492 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2493 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2494 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2495 } else {
2496 // Virtual displays without a surface are dormant:
2497 // they have external state (layer stack, projection,
2498 // etc.) but no internal state (i.e. a DisplayDevice).
2499 return;
2500 }
2501
2502 compositionengine::DisplayCreationArgsBuilder builder;
2503 if (const auto& physical = state.physical) {
2504 builder.setPhysical({physical->id, physical->type});
2505 }
2506 builder.setPixels(ui::Size(width, height));
2507 builder.setPixelFormat(pixelFormat);
2508 builder.setIsSecure(state.isSecure);
2509 builder.setLayerStackId(state.layerStack);
2510 builder.setPowerAdvisor(&mPowerAdvisor);
2511 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2512 builder.setName(state.displayName);
2513 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2514
2515 sp<compositionengine::DisplaySurface> displaySurface;
2516 sp<IGraphicBufferProducer> producer;
2517 sp<IGraphicBufferProducer> bqProducer;
2518 sp<IGraphicBufferConsumer> bqConsumer;
2519 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2520
2521 std::optional<DisplayId> displayId = compositionDisplay->getId();
2522
2523 if (state.isVirtual()) {
2524 sp<VirtualDisplaySurface> vds =
2525 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2526 bqConsumer, state.displayName);
2527
2528 displaySurface = vds;
2529 producer = vds;
2530 } else {
2531 ALOGE_IF(state.surface != nullptr,
2532 "adding a supported display, but rendering "
2533 "surface is provided (%p), ignoring it",
2534 state.surface.get());
2535
2536 LOG_ALWAYS_FATAL_IF(!displayId);
2537 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2538 maxGraphicsWidth, maxGraphicsHeight);
2539 producer = bqProducer;
2540 }
2541
2542 if (displaySurface != nullptr) {
2543 mDisplays.emplace(displayToken,
2544 setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2545 displaySurface, producer));
2546 if (!state.isVirtual()) {
2547 LOG_ALWAYS_FATAL_IF(!displayId);
2548 dispatchDisplayHotplugEvent(displayId->value, true);
2549 }
2550
2551 const auto displayDevice = mDisplays[displayToken];
2552 if (displayDevice->isPrimary()) {
2553 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2554 displayDevice->getHeight());
2555 }
2556 }
2557}
2558
2559void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2560 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2561 // Save display ID before disconnecting.
2562 const auto displayId = display->getId();
2563 display->disconnect();
2564
2565 if (!display->isVirtual()) {
2566 LOG_ALWAYS_FATAL_IF(!displayId);
2567 dispatchDisplayHotplugEvent(displayId->value, false);
2568 }
2569 }
2570
2571 mDisplays.erase(displayToken);
2572}
2573
2574void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2575 const DisplayDeviceState& currentState,
2576 const DisplayDeviceState& drawingState) {
2577 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2578 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
2579 if (currentBinder != drawingBinder) {
2580 // changing the surface is like destroying and recreating the DisplayDevice
2581 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2582 display->disconnect();
2583 }
2584 mDisplays.erase(displayToken);
2585 processDisplayAdded(displayToken, currentState);
2586 return;
2587 }
2588
2589 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2590 if (currentState.layerStack != drawingState.layerStack) {
2591 display->setLayerStack(currentState.layerStack);
2592 }
2593 if ((currentState.orientation != drawingState.orientation) ||
2594 (currentState.viewport != drawingState.viewport) ||
2595 (currentState.frame != drawingState.frame)) {
2596 display->setProjection(currentState.orientation, currentState.viewport,
2597 currentState.frame);
2598 }
2599 if (currentState.width != drawingState.width ||
2600 currentState.height != drawingState.height) {
2601 display->setDisplaySize(currentState.width, currentState.height);
2602 if (display->isPrimary()) {
2603 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2604 }
2605 }
2606 }
2607}
2608
Lloyd Pique347200f2017-12-14 17:00:15 -08002609void SurfaceFlinger::processDisplayChangesLocked() {
2610 // here we take advantage of Vector's copy-on-write semantics to
2611 // improve performance by skipping the transaction entirely when
2612 // know that the lists are identical
2613 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2614 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2615 if (!curr.isIdenticalTo(draw)) {
2616 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002617
2618 // find the displays that were removed
2619 // (ie: in drawing state but not in current state)
2620 // also handle displays that changed
2621 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002622 for (size_t i = 0; i < draw.size(); i++) {
2623 const wp<IBinder>& displayToken = draw.keyAt(i);
2624 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002625 if (j < 0) {
2626 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002627 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002628 } else {
2629 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002630 const DisplayDeviceState& currentState = curr[j];
2631 const DisplayDeviceState& drawingState = draw[i];
2632 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002633 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 }
2635
2636 // find displays that were added
2637 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002638 for (size_t i = 0; i < curr.size(); i++) {
2639 const wp<IBinder>& displayToken = curr.keyAt(i);
2640 if (draw.indexOfKey(displayToken) < 0) {
2641 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002642 }
2643 }
2644 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002645
2646 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002647}
2648
Mathias Agopian87baae12012-07-31 12:38:26 -07002649void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002650{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002651 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2652
Dan Stoza7dde5992015-05-22 09:51:44 -07002653 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002654 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002655 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002656 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002657
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 /*
2659 * Traversal of the children
2660 * (perform the transaction for each of them if needed)
2661 */
2662
Marissa Wall06255332019-03-27 13:48:27 -07002663 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002664 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002666 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667
2668 const uint32_t flags = layer->doTransaction(0);
2669 if (flags & Layer::eVisibleRegion)
2670 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002671
2672 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002673 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002674 }
Robert Carr2047fae2016-11-28 14:09:09 -08002675 });
Marissa Wall06255332019-03-27 13:48:27 -07002676 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 }
2678
2679 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002680 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681 */
2682
Mathias Agopiane57f2922012-08-09 16:29:12 -07002683 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002685 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002686 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002688 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002689 // The transform hint might have changed for some layers
2690 // (either because a display has changed, or because a layer
2691 // as changed).
2692 //
2693 // Walk through all the layers in currentLayers,
2694 // and update their transform hint.
2695 //
2696 // If a layer is visible only on a single display, then that
2697 // display is used to calculate the hint, otherwise we use the
2698 // default display.
2699 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002700 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002701 // the hint is set before we acquire a buffer from the surface texture.
2702 //
2703 // NOTE: layer transactions have taken place already, so we use their
2704 // drawing state. However, SurfaceFlinger's own transaction has not
2705 // happened yet, so we must use the current state layer list
2706 // (soon to become the drawing state list).
2707 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002708 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002709 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002710 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002711 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002712 // NOTE: we rely on the fact that layers are sorted by
2713 // layerStack first (so we don't have to traverse the list
2714 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002715 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002716 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002717 currentlayerStack = layerStack;
2718 // figure out if this layerstack is mirrored
2719 // (more than one display) if so, pick the default display,
2720 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002721 hintDisplay = nullptr;
2722 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002723 if (display->getCompositionDisplay()
2724 ->belongsInOutput(layer->getLayerStack(),
2725 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002726 if (hintDisplay) {
2727 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002728 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002731 }
2732 }
2733 }
2734 }
Chet Haase91d25932013-04-11 15:24:55 -07002735
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002736 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002737 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2738 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002739
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002740 // could be null when this layer is using a layerStack
2741 // that is not visible on any display. Also can occur at
2742 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002744 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002745
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002747 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002748 if (hintDisplay) {
2749 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002750 }
Robert Carr2047fae2016-11-28 14:09:09 -08002751
2752 first = false;
2753 });
Mathias Agopian84300952012-11-21 16:02:13 -08002754 }
2755
2756
Mathias Agopian3559b072012-08-15 13:46:03 -07002757 /*
2758 * Perform our own transaction if needed
2759 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760
2761 if (mLayersAdded) {
2762 mLayersAdded = false;
2763 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002764 mVisibleRegionsDirty = true;
2765 }
2766
2767 // some layers might have been removed, so
2768 // we need to update the regions they're exposing.
2769 if (mLayersRemoved) {
2770 mLayersRemoved = false;
2771 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002772 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002773 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002774 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002776 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002777 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002778 }
Robert Carr2047fae2016-11-28 14:09:09 -08002779 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780 }
2781
Vishnu Nairec0ab382019-02-13 15:32:56 -08002782 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002784}
2785
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002786void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002787 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002788 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002789 return;
2790 }
2791
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002792 if (mVisibleRegionsDirty || mInputInfoChanged) {
2793 mInputInfoChanged = false;
2794 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002795 } else if (mInputWindowCommands.syncInputWindows) {
2796 // If the caller requested to sync input windows, but there are no
2797 // changes to input windows, notify immediately.
2798 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002799 }
2800
Arthur Hung6cbb9752019-09-05 16:38:18 +08002801 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002802}
2803
2804void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002805 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002806
Robert Carra1257842020-01-31 13:48:28 -08002807 // We use a simple caching algorithm here. mInputDirty begins as true,
2808 // after we call setInputWindows we set it to false, so
2809 // in the future we wont call it again.. We set input dirty to true again
2810 // when any layer that hasInput() has a transaction performed on it
2811 // or when any parent or relative parent of such a layer has a transaction
2812 // performed on it. Not all of these transactions will really result in
2813 // input changes but all input changes will spring from these transactions
2814 // so the cache is safe but not optimal. It seems like it might be annoyingly
2815 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002816 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002817 return;
2818 }
2819
Robert Carr720e5062018-07-30 17:45:14 -07002820 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2821 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002822 // When calculating the screen bounds we ignore the transparent region since it may
2823 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002824 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002825 }
2826 });
chaviw291d88a2019-02-14 10:33:58 -08002827
2828 mInputFlinger->setInputWindows(inputHandles,
2829 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2830 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002831
2832 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002833}
2834
Vishnu Nairec0ab382019-02-13 15:32:56 -08002835void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002836 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002837 mPendingInputWindowCommands.clear();
2838}
2839
Riley Andrews03414a12014-07-01 14:22:59 -07002840void SurfaceFlinger::updateCursorAsync()
2841{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002842 compositionengine::CompositionRefreshArgs refreshArgs;
2843 for (const auto& [_, display] : mDisplays) {
2844 if (display->getId()) {
2845 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002846 }
2847 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002848
2849 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002850}
2851
Ady Abraham2139f732019-11-13 18:56:40 -08002852void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002853 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2854 // If this is called from the main thread mStateLock must be locked before
2855 // Currently the only way to call this function from the main thread is from
2856 // Sheduler::chooseRefreshRateForContent
2857
2858 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002859 changeRefreshRateLocked(refreshRate, event);
2860}
2861
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002862void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2863 if (mScheduler) {
2864 // In practice it's not allowed to hotplug in/out the primary display once it's been
2865 // connected during startup, but some tests do it, so just warn and return.
2866 ALOGW("Can't re-init scheduler");
2867 return;
2868 }
2869
Ady Abraham2139f732019-11-13 18:56:40 -08002870 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002871 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002872 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002873 primaryDisplayId),
2874 currentConfig);
2875 mRefreshRateStats =
2876 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2877 currentConfig, HWC_POWER_MODE_OFF);
2878 mRefreshRateStats->setConfigMode(currentConfig);
2879
Ady Abraham9e16a482019-12-03 17:19:41 -08002880 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2881
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002882 // start the EventThread
2883 mScheduler =
2884 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002885 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002886 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002887 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002888 impl::EventThread::InterceptVSyncsCallback());
2889 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002890 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002891 [this](nsecs_t timestamp) {
2892 mInterceptor->saveVSyncEvent(timestamp);
2893 });
2894
2895 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2896 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002897 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002898
2899 mRegionSamplingThread =
2900 new RegionSamplingThread(*this, *mScheduler,
2901 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002902 // Dispatch a config change request for the primary display on scheduler
2903 // initialization, so that the EventThreads always contain a reference to a
2904 // prior configuration.
2905 //
2906 // This is a bit hacky, but this avoids a back-pointer into the main SF
2907 // classes from EventThread, and there should be no run-time binder cost
2908 // anyway since there are no connected apps at this point.
2909 const nsecs_t vsyncPeriod =
2910 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2911 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2912 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002913}
2914
Mathias Agopian4fec8732012-06-29 14:12:52 -07002915void SurfaceFlinger::commitTransaction()
2916{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002917 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002918
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002919 mTransactionPending = false;
2920 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002921 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922}
2923
Lloyd Pique58e24a32019-08-01 15:50:14 -07002924void SurfaceFlinger::commitTransactionLocked() {
2925 if (!mLayersPendingRemoval.isEmpty()) {
2926 // Notify removed layers now that they can't be drawn from
2927 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002928 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002929
2930 // Ensure any buffers set to display on any children are released.
2931 if (l->isRemovedFromCurrentState()) {
2932 l->latchAndReleaseBuffer();
2933 }
2934
2935 // If the layer has been removed and has no parent, then it will not be reachable
2936 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2937 // ensure we can copy its current to drawing state.
2938 if (!l->getParent()) {
2939 mOffscreenLayers.emplace(l.get());
2940 }
2941 }
2942 mLayersPendingRemoval.clear();
2943 }
2944
2945 // If this transaction is part of a window animation then the next frame
2946 // we composite should be considered an animation as well.
2947 mAnimCompositionPending = mAnimTransactionPending;
2948
2949 mDrawingState = mCurrentState;
2950 // clear the "changed" flags in current state
2951 mCurrentState.colorMatrixChanged = false;
2952
Edgar Arriaga844fa672020-01-16 14:21:42 -08002953 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002954 layer->commitChildList();
2955
2956 // If the layer can be reached when traversing mDrawingState, then the layer is no
2957 // longer offscreen. Remove the layer from the offscreenLayer set.
2958 if (mOffscreenLayers.count(layer)) {
2959 mOffscreenLayers.erase(layer);
2960 }
2961 });
2962
2963 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002964 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002965}
2966
Nataniel Borges2b796da2019-02-15 13:32:18 -08002967void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2968 if (mTracingEnabledChanged) {
2969 mTracingEnabled = mTracing.isEnabled();
2970 mTracingEnabledChanged = false;
2971 }
2972
2973 // Synchronize with Tracing thread
2974 std::unique_lock<std::mutex> lock;
2975 if (mTracingEnabled) {
2976 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2977 }
2978
2979 lockedOperation();
2980
2981 // Synchronize with Tracing thread
2982 if (mTracingEnabled) {
2983 lock.unlock();
2984 }
2985}
2986
chaviw74d90ad2019-04-26 14:45:26 -07002987void SurfaceFlinger::commitOffscreenLayers() {
2988 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002989 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002990 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2991 if (!trFlags) return;
2992
2993 layer->doTransaction(0);
2994 layer->commitChildList();
2995 });
2996 }
2997}
2998
Chia-I Wuab0c3192017-08-01 11:29:00 -07002999void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003000 for (const auto& [token, displayDevice] : mDisplays) {
3001 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003002 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003003 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003004 }
3005 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003006}
3007
Dan Stoza6b9454d2014-11-07 16:00:59 -08003008bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009{
Ady Abraham09bd3922019-04-08 10:44:56 -07003010 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003011 ALOGV("handlePageFlip");
3012
Brian Andersond6927fb2016-07-23 23:37:30 -07003013 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003016 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003017 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003018
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003019 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3020
Eric Penner51c59cd2014-07-28 19:51:58 -07003021 // Store the set of layers that need updates. This set must not change as
3022 // buffers are being latched, as this could result in a deadlock.
3023 // Example: Two producers share the same command stream and:
3024 // 1.) Layer 0 is latched
3025 // 2.) Layer 0 gets a new frame
3026 // 2.) Layer 1 gets a new frame
3027 // 3.) Layer 1 is latched.
3028 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3029 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003030 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003031 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003032 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003033 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003034 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003035 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003036 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003037 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003038 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003039 } else {
3040 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 }
Robert Carr2047fae2016-11-28 14:09:09 -08003042 });
3043
chaviw49a108c2019-08-12 11:23:06 -07003044 // The client can continue submitting buffers for offscreen layers, but they will not
3045 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3046 // layers to ensure dequeueBuffer doesn't block indefinitely.
3047 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003048 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003049 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3050 }
3051
Lloyd Piquef2c79392018-12-20 16:23:33 -08003052 if (!mLayersWithQueuedFrames.empty()) {
3053 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3054 // writes to Layer current state. See also b/119481871
3055 Mutex::Autolock lock(mStateLock);
3056
3057 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003058 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003059 mLayersPendingRefresh.push_back(layer);
3060 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003061 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003062 if (layer->isBufferLatched()) {
3063 newDataLatched = true;
3064 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003065 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003066 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003067
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003068 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003069
3070 // If we will need to wake up at some time in the future to deal with a
3071 // queued frame that shouldn't be displayed during this vsync period, wake
3072 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003073 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003074 signalLayerUpdate();
3075 }
3076
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003077 // enter boot animation on first buffer latch
3078 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3079 ALOGI("Enter boot animation");
3080 mBootStage = BootStage::BOOTANIMATION;
3081 }
3082
Edgar Arriaga844fa672020-01-16 14:21:42 -08003083 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003084
Dan Stoza6b9454d2014-11-07 16:00:59 -08003085 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003086 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087}
3088
Mathias Agopianad456f92011-01-13 17:53:01 -08003089void SurfaceFlinger::invalidateHwcGeometry()
3090{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003092}
3093
Robert Carrc0df3122019-04-11 13:18:21 -07003094status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3095 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3096 const sp<IBinder>& parentHandle,
3097 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003098 // add this layer to the current state list
3099 {
3100 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003101 sp<Layer> parent;
3102 if (parentHandle != nullptr) {
3103 parent = fromHandle(parentHandle);
3104 if (parent == nullptr) {
3105 return NAME_NOT_FOUND;
3106 }
3107 } else {
3108 parent = parentLayer;
3109 }
3110
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003111 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003112 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003113 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003114 return NO_MEMORY;
3115 }
Robert Carrc0df3122019-04-11 13:18:21 -07003116
3117 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3118
Robert Carrb89ea9d2018-12-10 13:01:14 -08003119 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003120 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003121 } else if (parent == nullptr) {
3122 lbc->onRemovedFromCurrentState();
3123 } else if (parent->isRemovedFromCurrentState()) {
3124 parent->addChild(lbc);
3125 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003126 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003127 parent->addChild(lbc);
3128 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003129
Yiwei Zhang243b3782018-05-15 17:40:04 -07003130 if (gbc != nullptr) {
3131 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3132 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3133 mMaxGraphicBufferProducerListSize,
3134 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3135 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003136 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003137 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3138 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3139 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3140 mNumLayers.load());
3141 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003142 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003143 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003144 }
3145
Mathias Agopian96f08192010-06-02 23:28:45 -07003146 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003147 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003148
Dan Stoza7d89d062015-04-30 13:29:25 -07003149 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003150}
3151
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003152uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003153 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003154}
3155
Mathias Agopian3f844832013-08-07 21:24:32 -07003156uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003157 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158}
3159
Mathias Agopian3f844832013-08-07 21:24:32 -07003160uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003161 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003162}
3163
3164uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003165 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003166 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003167 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003169 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
3171 return old;
3172}
3173
Marissa Wall713b63f2018-10-17 15:42:43 -07003174bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003175 // to prevent onHandleDestroyed from being called while the lock is held,
3176 // we must keep a copy of the transactions (specifically the composer
3177 // states) around outside the scope of the lock
3178 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003179 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003180 {
3181 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003182
Valerie Haufce31b82019-04-30 16:41:14 -07003183 auto it = mTransactionQueues.begin();
3184 while (it != mTransactionQueues.end()) {
3185 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003186
Valerie Haufce31b82019-04-30 16:41:14 -07003187 while (!transactionQueue.empty()) {
3188 const auto& transaction = transactionQueue.front();
3189 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003190 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003191 transaction.states)) {
3192 setTransactionFlags(eTransactionFlushNeeded);
3193 break;
3194 }
3195 transactions.push_back(transaction);
3196 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3197 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003198 transaction.buffer, transaction.postTime,
3199 transaction.privileged, transaction.hasListenerCallbacks,
3200 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003201 transactionQueue.pop();
3202 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003203 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003204
Valerie Haufce31b82019-04-30 16:41:14 -07003205 if (transactionQueue.empty()) {
3206 it = mTransactionQueues.erase(it);
3207 mTransactionCV.broadcast();
3208 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003209 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003210 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003211 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003212 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003213 return flushedATransaction;
3214}
3215
3216bool SurfaceFlinger::transactionFlushNeeded() {
3217 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003218}
3219
chaviwca27f252018-02-06 16:46:39 -08003220
Marissa Wall17b4e452018-12-26 16:32:34 -08003221bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003222 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003223 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003224 if (!useCachedExpectedPresentTime)
3225 populateExpectedPresentTime();
3226
3227 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003228 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3229 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3230 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3231 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3232 return false;
3233 }
3234
Marissa Wall713b63f2018-10-17 15:42:43 -07003235 for (const ComposerState& state : states) {
3236 const layer_state_t& s = state.state;
3237 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3238 continue;
3239 }
3240 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003241 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003242 }
3243 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003244 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003245}
3246
Valerie Hau9dab9732019-08-20 09:29:25 -07003247void SurfaceFlinger::setTransactionState(
3248 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3249 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3250 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3251 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003252 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003253
Valerie Haubc6ddb12019-03-08 11:10:15 -08003254 const int64_t postTime = systemTime();
3255
Robert Carr14167e02019-02-13 13:50:55 -08003256 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3257
Mathias Agopian698c0872011-06-28 19:09:31 -07003258 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003259
Marissa Wall713b63f2018-10-17 15:42:43 -07003260 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003261 auto itr = mTransactionQueues.find(applyToken);
3262 // if this is an animation frame, wait until prior animation frame has
3263 // been applied by SF
3264 if (flags & eAnimation) {
3265 while (itr != mTransactionQueues.end()) {
3266 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3267 if (CC_UNLIKELY(err != NO_ERROR)) {
3268 ALOGW_IF(err == TIMED_OUT,
3269 "setTransactionState timed out "
3270 "waiting for animation frame to apply");
3271 break;
3272 }
3273 itr = mTransactionQueues.find(applyToken);
3274 }
3275 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003276
3277 // Expected present time is computed and cached on invalidate, so it may be stale.
3278 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3279 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003280 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003281 uncacheBuffer, postTime, privileged,
3282 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003283 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003284 return;
3285 }
3286
Valerie Haubc6ddb12019-03-08 11:10:15 -08003287 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003288 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3289 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003290}
3291
Valerie Hau9dab9732019-08-20 09:29:25 -07003292void SurfaceFlinger::applyTransactionState(
3293 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3294 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3295 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3296 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3297 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003298 uint32_t transactionFlags = 0;
3299
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003300 if (flags & eAnimation) {
3301 // For window updates that are part of an animation we must wait for
3302 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003303 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003304 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003305 if (CC_UNLIKELY(err != NO_ERROR)) {
3306 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003307 // caller after a few seconds.
3308 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3309 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 mAnimTransactionPending = false;
3311 break;
3312 }
3313 }
3314 }
3315
chaviwca27f252018-02-06 16:46:39 -08003316 for (const DisplayState& display : displays) {
3317 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003318 }
3319
Valerie Hau9dab9732019-08-20 09:29:25 -07003320 // start and end registration for listeners w/ no surface so they can get their callback. Note
3321 // that listeners with SurfaceControls will start registration during setClientStateLocked
3322 // below.
3323 for (const auto& listener : listenerCallbacks) {
3324 mTransactionCompletedThread.startRegistration(listener);
3325 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003326 }
3327
Valerie Hau9dab9732019-08-20 09:29:25 -07003328 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003329 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003330 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003331 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3332 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003333 }
3334
Valerie Hau9dab9732019-08-20 09:29:25 -07003335 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003336 mTransactionCompletedThread.endRegistration(listenerCallback);
3337 }
3338
Marissa Walle2ffb422018-10-12 11:33:52 -07003339 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003340 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003341 mTransactionCompletedThread.sendCallbacks();
3342 }
3343 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003344
chaviw273171b2018-12-26 11:46:30 -08003345 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3346
Marissa Wall947d34e2019-03-29 14:03:53 -07003347 if (uncacheBuffer.isValid()) {
3348 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003349 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003350 }
3351
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003352 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3353 // anyway. This can be used as a flush mechanism for previous async transactions.
3354 // Empty animation transaction can be used to simulate back-pressure, so also force a
3355 // transaction for empty animation transactions.
3356 if (transactionFlags == 0 &&
3357 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003358 transactionFlags = eTransactionNeeded;
3359 }
3360
Marissa Wall06255332019-03-27 13:48:27 -07003361 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3362 // so we don't have to wake up again next frame to preform an uneeded traversal.
3363 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3364 transactionFlags = transactionFlags & (~eTraversalNeeded);
3365 mTraversalNeededMainThread = true;
3366 }
3367
Mathias Agopian386aa982011-11-07 21:58:03 -08003368 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003369 if (mInterceptor->isEnabled()) {
3370 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003371 }
Irvel468051e2016-06-13 16:44:44 -07003372
Mathias Agopian386aa982011-11-07 21:58:03 -08003373 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003374 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3375 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003376 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003377
3378 // if this is a synchronous transaction, wait for it to take effect
3379 // before returning.
3380 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003381 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003382 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003383 if (flags & eAnimation) {
3384 mAnimTransactionPending = true;
3385 }
chaviw4fe36852019-04-15 16:25:49 -07003386 if (mPendingInputWindowCommands.syncInputWindows) {
3387 mPendingSyncInputWindows = true;
3388 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003389
3390 // applyTransactionState can be called by either the main SF thread or by
3391 // another process through setTransactionState. While a given process may wish
3392 // to wait on synchronous transactions, the main SF thread should never
3393 // be blocked. Therefore, we only wait if isMainThread is false.
3394 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003395 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3396 if (CC_UNLIKELY(err != NO_ERROR)) {
3397 // just in case something goes wrong in SF, return to the
3398 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003399 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3400 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003401 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003402 break;
3403 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003405 }
3406}
3407
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003408uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3409 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3410 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003411
Mathias Agopiane57f2922012-08-09 16:29:12 -07003412 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003413 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3414
3415 const uint32_t what = s.what;
3416 if (what & DisplayState::eSurfaceChanged) {
3417 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3418 state.surface = s.surface;
3419 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003420 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003421 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003422 if (what & DisplayState::eLayerStackChanged) {
3423 if (state.layerStack != s.layerStack) {
3424 state.layerStack = s.layerStack;
3425 flags |= eDisplayTransactionNeeded;
3426 }
3427 }
3428 if (what & DisplayState::eDisplayProjectionChanged) {
3429 if (state.orientation != s.orientation) {
3430 state.orientation = s.orientation;
3431 flags |= eDisplayTransactionNeeded;
3432 }
3433 if (state.frame != s.frame) {
3434 state.frame = s.frame;
3435 flags |= eDisplayTransactionNeeded;
3436 }
3437 if (state.viewport != s.viewport) {
3438 state.viewport = s.viewport;
3439 flags |= eDisplayTransactionNeeded;
3440 }
3441 }
3442 if (what & DisplayState::eDisplaySizeChanged) {
3443 if (state.width != s.width) {
3444 state.width = s.width;
3445 flags |= eDisplayTransactionNeeded;
3446 }
3447 if (state.height != s.height) {
3448 state.height = s.height;
3449 flags |= eDisplayTransactionNeeded;
3450 }
3451 }
3452
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 return flags;
3454}
3455
Robert Carr14167e02019-02-13 13:50:55 -08003456bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003457 IPCThreadState* ipc = IPCThreadState::self();
3458 const int pid = ipc->getCallingPid();
3459 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003460 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003461 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003462 return false;
3463 }
3464 return true;
3465}
3466
Marissa Wall3dad52d2019-03-22 14:03:19 -07003467uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003468 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3469 bool privileged,
3470 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003471 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003472
Valerie Hau9dab9732019-08-20 09:29:25 -07003473 for (auto& listener : s.listeners) {
3474 // note that startRegistration will not re-register if the listener has
3475 // already be registered for a prior surface control
3476 mTransactionCompletedThread.startRegistration(listener);
3477 listenerCallbacks.insert(listener);
3478 }
3479
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003480 sp<Layer> layer = nullptr;
3481 if (s.surface) {
3482 layer = fromHandle(s.surface);
3483 } else {
3484 // The client may provide us a null handle. Treat it as if the layer was removed.
3485 ALOGW("Attempt to set client state with a null layer handle");
3486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003488 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003489 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003490 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003491 }
chaviw8b3871a2017-11-01 17:41:01 -07003492 return 0;
3493 }
3494
chaviw8b3871a2017-11-01 17:41:01 -07003495 uint32_t flags = 0;
3496
Garfield Tan8a3083e2018-12-03 13:21:07 -08003497 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003498
3499 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3500 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003501 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003502 layer->pushPendingState();
3503 }
3504
Valerie Hau871d6352020-01-29 08:44:02 -08003505 // Only set by BLAST adapter layers
3506 if (what & layer_state_t::eProducerDisconnect) {
3507 layer->onDisconnect();
3508 }
3509
chaviw8b3871a2017-11-01 17:41:01 -07003510 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003511 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003512 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003513 }
chaviw8b3871a2017-11-01 17:41:01 -07003514 }
3515 if (what & layer_state_t::eLayerChanged) {
3516 // NOTE: index needs to be calculated before we update the state
3517 const auto& p = layer->getParent();
3518 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003519 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003520 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003521 mCurrentState.layersSortedByZ.removeAt(idx);
3522 mCurrentState.layersSortedByZ.add(layer);
3523 // we need traversal (state changed)
3524 // AND transaction (list changed)
3525 flags |= eTransactionNeeded|eTraversalNeeded;
3526 }
chaviw8b3871a2017-11-01 17:41:01 -07003527 } else {
3528 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003529 flags |= eTransactionNeeded|eTraversalNeeded;
3530 }
3531 }
chaviw8b3871a2017-11-01 17:41:01 -07003532 }
3533 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003534 // NOTE: index needs to be calculated before we update the state
3535 const auto& p = layer->getParent();
3536 if (p == nullptr) {
3537 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3538 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3539 mCurrentState.layersSortedByZ.removeAt(idx);
3540 mCurrentState.layersSortedByZ.add(layer);
3541 // we need traversal (state changed)
3542 // AND transaction (list changed)
3543 flags |= eTransactionNeeded|eTraversalNeeded;
3544 }
3545 } else {
3546 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3547 flags |= eTransactionNeeded|eTraversalNeeded;
3548 }
chaviw8b3871a2017-11-01 17:41:01 -07003549 }
3550 }
3551 if (what & layer_state_t::eSizeChanged) {
3552 if (layer->setSize(s.w, s.h)) {
3553 flags |= eTraversalNeeded;
3554 }
3555 }
3556 if (what & layer_state_t::eAlphaChanged) {
3557 if (layer->setAlpha(s.alpha))
3558 flags |= eTraversalNeeded;
3559 }
3560 if (what & layer_state_t::eColorChanged) {
3561 if (layer->setColor(s.color))
3562 flags |= eTraversalNeeded;
3563 }
Peiyong Lind3788632018-09-18 16:01:31 -07003564 if (what & layer_state_t::eColorTransformChanged) {
3565 if (layer->setColorTransform(s.colorTransform)) {
3566 flags |= eTraversalNeeded;
3567 }
3568 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003569 if (what & layer_state_t::eBackgroundColorChanged) {
3570 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3571 flags |= eTraversalNeeded;
3572 }
3573 }
chaviw8b3871a2017-11-01 17:41:01 -07003574 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003575 // TODO: b/109894387
3576 //
3577 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3578 // rotation. To see the problem observe that if we have a square parent, and a child
3579 // of the same size, then we rotate the child 45 degrees around it's center, the child
3580 // must now be cropped to a non rectangular 8 sided region.
3581 //
3582 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3583 // private API, and the WindowManager only uses rotation in one case, which is on a top
3584 // level layer in which cropping is not an issue.
3585 //
3586 // However given that abuse of rotation matrices could lead to surfaces extending outside
3587 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3588 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3589 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003590 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003591 flags |= eTraversalNeeded;
3592 }
3593 if (what & layer_state_t::eTransparentRegionChanged) {
3594 if (layer->setTransparentRegionHint(s.transparentRegion))
3595 flags |= eTraversalNeeded;
3596 }
3597 if (what & layer_state_t::eFlagsChanged) {
3598 if (layer->setFlags(s.flags, s.mask))
3599 flags |= eTraversalNeeded;
3600 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003601 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003602 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003603 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003604 if (what & layer_state_t::eCornerRadiusChanged) {
3605 if (layer->setCornerRadius(s.cornerRadius))
3606 flags |= eTraversalNeeded;
3607 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003608 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003609 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3610 }
chaviw8b3871a2017-11-01 17:41:01 -07003611 if (what & layer_state_t::eLayerStackChanged) {
3612 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3613 // We only allow setting layer stacks for top level layers,
3614 // everything else inherits layer stack from its parent.
3615 if (layer->hasParent()) {
3616 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003617 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003618 } else if (idx < 0) {
3619 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003620 "that also does not appear in the top level layer list. Something"
3621 " has gone wrong.",
3622 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003623 } else if (layer->setLayerStack(s.layerStack)) {
3624 mCurrentState.layersSortedByZ.removeAt(idx);
3625 mCurrentState.layersSortedByZ.add(layer);
3626 // we need traversal (state changed)
3627 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003628 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003629 }
3630 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003631 if (what & layer_state_t::eDeferTransaction_legacy) {
3632 if (s.barrierHandle_legacy != nullptr) {
3633 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3634 } else if (s.barrierGbp_legacy != nullptr) {
3635 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003636 if (authenticateSurfaceTextureLocked(gbp)) {
3637 const auto& otherLayer =
3638 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003639 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003640 } else {
3641 ALOGE("Attempt to defer transaction to to an"
3642 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003643 }
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 // We don't trigger a traversal here because if no other state is
3646 // changed, we don't want this to cause any more work
3647 }
chaviw8b3871a2017-11-01 17:41:01 -07003648 if (what & layer_state_t::eReparentChildren) {
3649 if (layer->reparentChildren(s.reparentHandle)) {
3650 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003651 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003652 }
chaviw8b3871a2017-11-01 17:41:01 -07003653 if (what & layer_state_t::eDetachChildren) {
3654 layer->detachChildren();
3655 }
3656 if (what & layer_state_t::eOverrideScalingModeChanged) {
3657 layer->setOverrideScalingMode(s.overrideScalingMode);
3658 // We don't trigger a traversal here because if no other state is
3659 // changed, we don't want this to cause any more work
3660 }
Marissa Wall61c58622018-07-18 10:12:20 -07003661 if (what & layer_state_t::eTransformChanged) {
3662 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3663 }
3664 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3665 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3666 flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eCropChanged) {
3669 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3670 }
Marissa Wall861616d2018-10-22 12:52:23 -07003671 if (what & layer_state_t::eFrameChanged) {
3672 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3673 }
Marissa Wall61c58622018-07-18 10:12:20 -07003674 if (what & layer_state_t::eAcquireFenceChanged) {
3675 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eDataspaceChanged) {
3678 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3679 }
3680 if (what & layer_state_t::eHdrMetadataChanged) {
3681 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3682 }
3683 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3684 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3685 }
3686 if (what & layer_state_t::eApiChanged) {
3687 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eSidebandStreamChanged) {
3690 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3691 }
Robert Carr720e5062018-07-30 17:45:14 -07003692 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003693 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003694 layer->setInputInfo(s.inputInfo);
3695 flags |= eTraversalNeeded;
3696 } else {
3697 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3698 }
Robert Carr720e5062018-07-30 17:45:14 -07003699 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003700 if (what & layer_state_t::eMetadataChanged) {
3701 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3702 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003703 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3704 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3705 flags |= eTraversalNeeded;
3706 }
3707 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003708 if (what & layer_state_t::eShadowRadiusChanged) {
3709 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3710 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003711 if (what & layer_state_t::eFrameRateSelectionPriority) {
3712 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3713 flags |= eTraversalNeeded;
3714 }
3715 }
Steven Thomas3172e202020-01-06 19:25:30 -08003716 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003717 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3718 "SurfaceFlinger::setClientStateLocked") &&
3719 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3720 Layer::FrameRate::convertCompatibility(
3721 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003722 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003723 }
Steven Thomas3172e202020-01-06 19:25:30 -08003724 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003725 // This has to happen after we reparent children because when we reparent to null we remove
3726 // child layers from current state and remove its relative z. If the children are reparented in
3727 // the same transaction, then we have to make sure we reparent the children first so we do not
3728 // lose its relative z order.
3729 if (what & layer_state_t::eReparent) {
3730 bool hadParent = layer->hasParent();
3731 if (layer->reparent(s.parentHandleForChild)) {
3732 if (!hadParent) {
3733 mCurrentState.layersSortedByZ.remove(layer);
3734 }
3735 flags |= eTransactionNeeded | eTraversalNeeded;
3736 }
3737 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003738 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003739 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3740 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003741 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3742 }
3743 }
Marissa Wall78b72202019-03-15 14:58:34 -07003744 bool bufferChanged = what & layer_state_t::eBufferChanged;
3745 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3746 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003747 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003748 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003749 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3750 if (success) {
3751 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3752 success = ClientCache::getInstance()
3753 .registerErasedRecipient(s.cachedBuffer,
3754 wp<ClientCache::ErasedRecipient>(this));
3755 if (!success) {
3756 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3757 }
3758 }
Marissa Wall78b72202019-03-15 14:58:34 -07003759 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003760 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003761 } else if (bufferChanged) {
3762 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003763 }
Marissa Wall78b72202019-03-15 14:58:34 -07003764 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003765 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3766 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003767 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003768 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003769 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003770 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3771 // Do not put anything that updates layer state or modifies flags after
3772 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773 return flags;
3774}
3775
chaviw273171b2018-12-26 11:46:30 -08003776uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3777 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003778 if (inputWindowCommands.syncInputWindows) {
3779 flags |= eTraversalNeeded;
3780 }
3781
Vishnu Nairec0ab382019-02-13 15:32:56 -08003782 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003783 return flags;
3784}
3785
chaviwfe94a222019-08-21 13:52:59 -07003786status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3787 sp<IBinder>* outHandle) {
3788 if (!mirrorFromHandle) {
3789 return NAME_NOT_FOUND;
3790 }
3791
3792 sp<Layer> mirrorLayer;
3793 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003794 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003795
3796 {
3797 Mutex::Autolock _l(mStateLock);
3798 mirrorFrom = fromHandle(mirrorFromHandle);
3799 if (!mirrorFrom) {
3800 return NAME_NOT_FOUND;
3801 }
3802
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003803 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3804 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003805 if (result != NO_ERROR) {
3806 return result;
3807 }
3808
3809 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3810 }
3811
3812 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3813}
3814
Marissa Wall2d814fb2019-04-09 18:52:57 +00003815status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3816 uint32_t h, PixelFormat format, uint32_t flags,
3817 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003818 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003819 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3820 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003821 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003822 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003823 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003824 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003825 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003826
Robert Carrc0df3122019-04-11 13:18:21 -07003827 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3828 "Expected only one of parentLayer or parentHandle to be non-null. "
3829 "Programmer error?");
3830
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003831 status_t result = NO_ERROR;
3832
3833 sp<Layer> layer;
3834
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003835 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003836
Evan Roskya1f1e152019-01-24 16:17:46 -08003837 bool primaryDisplayOnly = false;
3838
3839 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3840 // TODO b/64227542
3841 if (metadata.has(METADATA_WINDOW_TYPE)) {
3842 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3843 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003844 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003845 primaryDisplayOnly = true;
3846 }
3847 }
3848
Mathias Agopian3165cc22012-08-08 19:42:09 -07003849 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003850 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003851 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3852 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003855 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003856 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003857 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003858 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003859 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003860 // check if buffer size is set for color layer.
3861 if (w > 0 || h > 0) {
3862 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3863 int(w), int(h));
3864 return BAD_VALUE;
3865 }
3866
Vishnu Nairfa247b12020-02-11 08:58:26 -08003867 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3868 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003869 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003870 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003871 // check if buffer size is set for container layer.
3872 if (w > 0 || h > 0) {
3873 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3874 int(w), int(h));
3875 return BAD_VALUE;
3876 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003877 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3878 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003879 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003880 default:
3881 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 break;
3883 }
3884
Dan Stoza7d89d062015-04-30 13:29:25 -07003885 if (result != NO_ERROR) {
3886 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003888
Evan Roskya1f1e152019-01-24 16:17:46 -08003889 if (primaryDisplayOnly) {
3890 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003891 }
3892
Robert Carrb89ea9d2018-12-10 13:01:14 -08003893 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003894 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3895 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003896 if (result != NO_ERROR) {
3897 return result;
3898 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003899 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003900
3901 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003902 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903}
3904
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003905std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3906 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003907
3908 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003909 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003910
Dan Stoza436ccf32018-06-21 12:10:12 -07003911 // Grab the state lock since we're accessing mCurrentState
3912 Mutex::Autolock lock(mStateLock);
3913
Cody Northropbc755282017-03-31 12:00:08 -06003914 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003916 while (matchFound) {
3917 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003918 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003919 if (layer->getName() == uniqueName) {
3920 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003921 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003922 }
3923 });
3924 }
3925
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003926 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003927 return uniqueName;
3928}
3929
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003930status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003931 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003932 LayerMetadata metadata, PixelFormat& format,
3933 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003934 sp<IGraphicBufferProducer>* gbp,
3935 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003937 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003938 case PIXEL_FORMAT_TRANSPARENT:
3939 case PIXEL_FORMAT_TRANSLUCENT:
3940 format = PIXEL_FORMAT_RGBA_8888;
3941 break;
3942 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003943 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 break;
3945 }
3946
chaviwb4c6e582019-08-16 14:35:07 -07003947 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003948 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003949 args.textureName = getNewTexture();
3950 {
3951 // Grab the SF state lock during this since it's the only safe way to access
3952 // RenderEngine when creating a BufferLayerConsumer
3953 // TODO: Check if this lock is still needed here
3954 Mutex::Autolock lock(mStateLock);
3955 layer = getFactory().createBufferQueueLayer(args);
3956 }
3957
Marissa Wallfd668622018-05-10 10:21:13 -07003958 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003959 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003960 *handle = layer->getHandle();
3961 *gbp = layer->getProducer();
3962 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003964
Marissa Wallfd668622018-05-10 10:21:13 -07003965 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003966 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967}
3968
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003969status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003970 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003971 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003972 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003973 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003974 args.displayDevice = getDefaultDisplayDevice();
3975 args.textureName = getNewTexture();
3976 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003977 if (outTransformHint) {
3978 *outTransformHint = layer->getTransformHint();
3979 }
Marissa Wall61c58622018-07-18 10:12:20 -07003980 *handle = layer->getHandle();
3981 *outLayer = layer;
3982
3983 return NO_ERROR;
3984}
3985
Vishnu Nairfa247b12020-02-11 08:58:26 -08003986status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3987 uint32_t h, uint32_t flags, LayerMetadata metadata,
3988 sp<IBinder>* handle, sp<Layer>* outLayer) {
3989 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003990 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003991 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003992 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003993}
3994
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003995status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003996 uint32_t w, uint32_t h, uint32_t flags,
3997 LayerMetadata metadata, sp<IBinder>* handle,
3998 sp<Layer>* outLayer) {
3999 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004000 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004001 *handle = (*outLayer)->getHandle();
4002 return NO_ERROR;
4003}
4004
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004005void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004006 mLayersPendingRemoval.add(layer);
4007 mLayersRemoved = true;
4008 setTransactionFlags(eTransactionNeeded);
4009}
4010
Robert Carr695d5282018-12-18 15:27:58 -08004011void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004012{
Robert Carr2e102c92018-10-23 12:11:15 -07004013 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004014 // If a layer has a parent, we allow it to out-live it's handle
4015 // with the idea that the parent holds a reference and will eventually
4016 // be cleaned up. However no one cleans up the top-level so we do so
4017 // here.
4018 if (layer->getParent() == nullptr) {
4019 mCurrentState.layersSortedByZ.remove(layer);
4020 }
4021 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004022
4023 auto it = mLayersByLocalBinderToken.begin();
4024 while (it != mLayersByLocalBinderToken.end()) {
4025 if (it->second == layer) {
4026 it = mLayersByLocalBinderToken.erase(it);
4027 } else {
4028 it++;
4029 }
4030 }
4031
Robert Carr695d5282018-12-18 15:27:58 -08004032 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004033}
4034
Mathias Agopianb60314a2012-04-10 22:09:54 -07004035// ---------------------------------------------------------------------------
4036
Andy McFadden13a082e2012-08-24 10:16:42 -07004037void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004038 const auto display = getDefaultDisplayDeviceLocked();
4039 if (!display) return;
4040
4041 const sp<IBinder> token = display->getDisplayToken().promote();
4042 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004043
Jesse Hall01e29052013-02-19 16:13:35 -08004044 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004045 Vector<ComposerState> state;
4046 Vector<DisplayState> displays;
4047 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004048 d.what = DisplayState::eDisplayProjectionChanged |
4049 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004050 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004051 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004052 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004053 d.frame.makeInvalid();
4054 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004055 d.width = 0;
4056 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004057 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004058 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4059 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004060
Dominik Laskowskie9774092018-12-11 10:04:24 -08004061 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004062
Dominik Laskowski83b88212018-12-11 13:34:06 -08004063 const nsecs_t vsyncPeriod = getVsyncPeriod();
4064 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004065
Brian Andersond0010582017-03-07 13:20:31 -08004066 // Use phase of 0 since phase is not known.
4067 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004068 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004069 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004070}
4071
4072void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004073 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004074 postMessageAsync(
4075 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004076}
4077
Ady Abraham27c70212019-06-11 10:52:26 -07004078void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4079 if (mHWCVsyncState != enabled) {
4080 getHwComposer().setVsyncEnabled(displayId, enabled);
4081 mHWCVsyncState = enabled;
4082 }
4083}
4084
Dominik Laskowskie9774092018-12-11 10:04:24 -08004085void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004086 if (display->isVirtual()) {
4087 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004088 return;
4089 }
4090
Dominik Laskowski075d3172018-05-24 15:50:06 -07004091 const auto displayId = display->getId();
4092 LOG_ALWAYS_FATAL_IF(!displayId);
4093
Dominik Laskowski34157762018-10-31 13:07:19 -07004094 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004095
4096 int currentMode = display->getPowerMode();
4097 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 return;
4099 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004101 display->setPowerMode(mode);
4102
Lloyd Pique4dccc412018-01-22 17:21:36 -08004103 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004104 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004105 }
4106
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004107 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004108 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004109 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004110 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004111 mScheduler->onScreenAcquired(mAppConnectionHandle);
4112 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004113 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004115 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004116 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004117 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004118
4119 struct sched_param param = {0};
4120 param.sched_priority = 1;
4121 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4122 ALOGW("Couldn't set SCHED_FIFO on display on");
4123 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004124 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004125 // Turn off the display
4126 struct sched_param param = {0};
4127 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4128 ALOGW("Couldn't set SCHED_OTHER on display off");
4129 }
4130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004131 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004132 mScheduler->disableHardwareVsync(true);
4133 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004134 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004135
Ady Abraham27c70212019-06-11 10:52:26 -07004136 // Make sure HWVsync is disabled before turning off the display
4137 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4138
Dominik Laskowski075d3172018-05-24 15:50:06 -07004139 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004140 mVisibleRegionsDirty = true;
4141 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004142 } else if (mode == HWC_POWER_MODE_DOZE ||
4143 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004144 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004145 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004146 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004147 mScheduler->onScreenAcquired(mAppConnectionHandle);
4148 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004149 }
4150 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4151 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004152 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004153 mScheduler->disableHardwareVsync(true);
4154 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004155 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004156 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004157 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004158 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004159 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004160 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004161
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004162 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004163 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004164 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004165 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004166 }
4167
Dominik Laskowski34157762018-10-31 13:07:19 -07004168 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004169}
4170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004172 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004173 const auto display = getDisplayDevice(displayToken);
4174 if (!display) {
4175 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4176 displayToken.get());
4177 } else if (display->isVirtual()) {
4178 ALOGW("Attempt to set power mode %d for virtual display", mode);
4179 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004180 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004181 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004182 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004183}
4184
4185// ---------------------------------------------------------------------------
4186
Dominik Laskowskic2867142019-01-21 11:33:38 -08004187status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4188 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004189 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004190
Mathias Agopianbd115332013-04-18 16:41:04 -07004191 IPCThreadState* ipc = IPCThreadState::self();
4192 const int pid = ipc->getCallingPid();
4193 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004194
Mathias Agopianbd115332013-04-18 16:41:04 -07004195 if ((uid != AID_SHELL) &&
4196 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004197 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4198 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004199 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004200 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004201 // (this would indicate SF is stuck, but we want to be able to
4202 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004203 status_t err = mStateLock.timedLock(s2ns(1));
4204 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004205 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004206 StringAppendF(&result,
4207 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4208 "(no locks held)\n",
4209 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004210 }
4211
Dominik Laskowskic2867142019-01-21 11:33:38 -08004212 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004213 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004214 {"--dispsync"s,
4215 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004216 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004217 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4218 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4219 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4220 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4221 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4222 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004223 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004224 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4225 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004226
Dominik Laskowskic2867142019-01-21 11:33:38 -08004227 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004228
Dominik Laskowski46470112019-08-02 13:13:11 -07004229 const auto it = dumpers.find(flag);
4230 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004231 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004232 } else if (!asProto) {
4233 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004234 }
4235
Mathias Agopian9795c422009-08-26 16:36:26 -07004236 if (locked) {
4237 mStateLock.unlock();
4238 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004239
Dominik Laskowski46470112019-08-02 13:13:11 -07004240 if (it == dumpers.end()) {
4241 const LayersProto layersProto = dumpProtoFromMainThread();
4242 if (asProto) {
4243 result.append(layersProto.SerializeAsString());
4244 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004245 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004246 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4247 result.append(LayerProtoParser::layerTreeToString(layerTree));
4248 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004249 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004250 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004251 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004252 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004254 return NO_ERROR;
4255}
4256
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004257status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4258 if (asProto && mTracing.isEnabled()) {
4259 mTracing.writeToFileAsync();
4260 }
4261
4262 return doDump(fd, DumpArgs(), asProto);
4263}
4264
Dominik Laskowskic2867142019-01-21 11:33:38 -08004265void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004267 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004268}
4269
Dominik Laskowskic2867142019-01-21 11:33:38 -08004270void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004271 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004272
Dominik Laskowskic2867142019-01-21 11:33:38 -08004273 if (args.size() > 1) {
4274 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004275 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004276 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004277 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004278 }
Robert Carr2047fae2016-11-28 14:09:09 -08004279 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004280 } else {
4281 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 }
4283}
4284
Dominik Laskowskic2867142019-01-21 11:33:38 -08004285void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004286 const bool clearAll = args.size() < 2;
4287 const auto name = clearAll ? String8() : String8(args[1]);
4288
Edgar Arriaga844fa672020-01-16 14:21:42 -08004289 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004290 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004291 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004292 }
Robert Carr2047fae2016-11-28 14:09:09 -08004293 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004294
Svetoslavd85084b2014-03-20 10:28:31 -07004295 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004296}
4297
Dominik Laskowskic2867142019-01-21 11:33:38 -08004298void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4299 mTimeStats->parseArgs(asProto, args, result);
4300}
4301
Jamie Gennis6547ff42013-07-16 20:12:42 -07004302// This should only be called from the main thread. Otherwise it would need
4303// the lock and should use mCurrentState rather than mDrawingState.
4304void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004305 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004306 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004307 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004308
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004309 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004310}
4311
Yiwei Zhang5434a782018-12-05 18:06:32 -08004312void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004313 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004314
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004315 if (isLayerTripleBufferingDisabled())
4316 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004317
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4319 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4320 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4321 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4322 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4323 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004324 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004325}
4326
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004327void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004328 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004329
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004330 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004331 result.append("\n");
4332
Ady Abraham9e16a482019-12-03 17:19:41 -08004333 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004334 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004335 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004336 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004337
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004338 HwcConfigIndexType defaultConfig;
4339 float minFps, maxFps;
4340 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004341 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004342 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004343 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004344 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004345 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4346 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004347
Ana Krulecc2870422019-01-29 19:00:58 -08004348 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004349}
4350
Yiwei Zhang5434a782018-12-05 18:06:32 -08004351void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4352 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004353 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4354 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004355 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004356 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004358 }
David Sodman4a36e932017-11-07 14:29:47 -08004359 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004360 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004361 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4363 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004364}
4365
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004366void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4367 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004368 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4369 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004370 for (const auto& segment : history) {
4371 if (!segment.usedThirdBuffer) {
4372 stats.twoBufferTime += segment.totalTime;
4373 }
4374 if (segment.occupancyAverage < 1.0f) {
4375 stats.doubleBufferedTime += segment.totalTime;
4376 } else if (segment.occupancyAverage < 2.0f) {
4377 stats.tripleBufferedTime += segment.totalTime;
4378 }
4379 ++stats.numSegments;
4380 stats.totalTime += segment.totalTime;
4381 }
4382}
4383
Yiwei Zhang5434a782018-12-05 18:06:32 -08004384void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4385 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004386
4387 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4388 const size_t count = currentLayers.size();
4389 for (size_t i=0 ; i<count ; i++) {
4390 currentLayers[i]->dumpFrameEvents(result);
4391 }
4392}
4393
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004395 result.append("Buffering stats:\n");
4396 result.append(" [Layer name] <Active time> <Two buffer> "
4397 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004398 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004399 typedef std::tuple<std::string, float, float, float> BufferTuple;
4400 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004401 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004402 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004403 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004404 if (stats.numSegments == 0) {
4405 continue;
4406 }
4407 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4408 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4409 stats.totalTime;
4410 float doubleBufferRatio = static_cast<float>(
4411 stats.doubleBufferedTime) / stats.totalTime;
4412 float tripleBufferRatio = static_cast<float>(
4413 stats.tripleBufferedTime) / stats.totalTime;
4414 sorted.insert({activeTime, {name, twoBufferRatio,
4415 doubleBufferRatio, tripleBufferRatio}});
4416 }
4417 for (const auto& sortedPair : sorted) {
4418 float activeTime = sortedPair.first;
4419 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4421 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004422 }
4423 result.append("\n");
4424}
4425
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004427 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004428 const auto displayId = display->getId();
4429 if (!displayId) {
4430 continue;
4431 }
4432 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004433 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004434 continue;
4435 }
4436
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437 StringAppendF(&result,
4438 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4439 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004440 uint8_t port;
4441 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004442 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004443 result.append("no identification data\n");
4444 continue;
4445 }
4446
4447 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004448 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004449 continue;
4450 }
4451
4452 const auto edid = parseEdid(data);
4453 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004454 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004455 continue;
4456 }
4457
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004459 result.append(edid->displayName.data(), edid->displayName.length());
4460 result.append("\"\n");
4461 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004462}
4463
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004464void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4465 std::string& result) const {
4466 hwc2_display_t hwcDisplayId;
4467 uint8_t port;
4468 DisplayIdentificationData data;
4469
4470 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4471 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4472 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4473 }
4474}
4475
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004477 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4479 StringAppendF(&result, "DisplayColorSetting: %s\n",
4480 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004481
4482 // TODO: print out if wide-color mode is active or not
4483
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004484 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004485 const auto displayId = display->getId();
4486 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004487 continue;
4488 }
4489
Yiwei Zhang5434a782018-12-05 18:06:32 -08004490 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004491 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004492 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004494 }
4495
Lloyd Pique32cbe282018-10-19 13:09:22 -07004496 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004497 StringAppendF(&result, " Current color mode: %s (%d)\n",
4498 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004499 }
4500 result.append("\n");
4501}
4502
Alec Mouri5793c7d2020-03-10 19:55:50 -07004503LayersProto SurfaceFlinger::dumpDrawingStateProto(
4504 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004505 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004506 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004507 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004508 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004509
chaviw1d044282017-09-27 12:19:28 -07004510 return layersProto;
4511}
4512
Alec Mouri6b9e9912020-01-21 10:50:24 -08004513void SurfaceFlinger::dumpHwc(std::string& result) const {
4514 getHwComposer().dump(result);
4515}
4516
Vishnu Nair0f085c62019-08-30 08:49:12 -07004517void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4518 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4519 // it.
4520 LayerProto* rootProto = layersProto.add_layers();
4521 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4522 rootProto->set_id(offscreenRootLayerId);
4523 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004524 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004525
4526 for (Layer* offscreenLayer : mOffscreenLayers) {
4527 // Add layer as child of the fake root
4528 rootProto->add_children(offscreenLayer->sequence);
4529
4530 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004531 LayerProto* layerProto =
4532 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004533 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004534 }
4535}
4536
Vishnu Nair8406fd72019-07-30 11:29:31 -07004537LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4538 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004539 postMessageSync(new LambdaMessage([&]() {
4540 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4541 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4542 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004543 return layersProto;
4544}
4545
Vishnu Nair0f085c62019-08-30 08:49:12 -07004546void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4547 result.append("Offscreen Layers:\n");
4548 postMessageSync(new LambdaMessage([&]() {
4549 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004550 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004551 layer->dumpCallingUidPid(result);
4552 });
4553 }
4554 }));
4555}
4556
Dominik Laskowskic2867142019-01-21 11:33:38 -08004557void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4558 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 Colorizer colorizer(colorize);
4560
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004561 // figure out if we're stuck somewhere
4562 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004564 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4565
4566 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004567 * Dump library configuration.
4568 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569
4570 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004571 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004572 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004573 appendSfConfigString(result);
4574 appendUiConfigString(result);
4575 appendGuiConfigString(result);
4576 result.append("\n");
4577
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004578 result.append("\nDisplay identification data:\n");
4579 dumpDisplayIdentificationData(result);
4580
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004581 result.append("\nWide-Color information:\n");
4582 dumpWideColorInfo(result);
4583
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004584 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004585 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004586 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004587 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004588 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004589
Andy McFadden41d67d72014-04-25 16:58:34 -07004590 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004591 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004592 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004593 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004594 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004595
Dan Stozab90cf072015-03-05 11:05:59 -08004596 dumpStaticScreenStats(result);
4597 result.append("\n");
4598
Alec Mouri40189b02019-03-05 15:07:54 -08004599 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4600 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4601 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004602
Dan Stozae77c7662016-05-13 11:37:28 -07004603 dumpBufferingStats(result);
4604
Andy McFadden4803b742012-09-24 19:07:20 -07004605 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606 * Dump the visible layer list
4607 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004609 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4611 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004613
Chia-I Wu2f884132018-09-13 15:17:58 -07004614 {
Lloyd Pique207def92019-02-28 16:09:52 -08004615 StringAppendF(&result, "Composition layers\n");
4616 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004617 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004618 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004619
4620 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4621 layer->getDebugName() ? layer->getDebugName()
4622 : "<unknown>");
4623 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004624 });
4625 }
4626
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004628 * Dump Display state
4629 */
4630
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004634 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004635 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004636 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004637 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004638
4639 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004640 * Dump CompositionEngine state
4641 */
4642
4643 mCompositionEngine->dump(result);
4644
4645 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004646 * Dump SurfaceFlinger global state
4647 */
4648
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004649 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004650 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004651 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004652
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004653 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004654
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004655 DebugEGLImageTracker::getInstance()->dump(result);
4656
Dominik Laskowski075d3172018-05-24 15:50:06 -07004657 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004658 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4659 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004660 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4661 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004662 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result,
4664 " transaction-flags : %08x\n"
4665 " gpu_to_cpu_unsupported : %d\n",
4666 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004667
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004668 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004669 displayId && getHwComposer().isConnected(*displayId)) {
4670 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 StringAppendF(&result,
4672 " refresh-rate : %f fps\n"
4673 " x-dpi : %f\n"
4674 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004675 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4676 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004677 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680
Dan Stozae22aec72016-08-01 13:20:59 -07004681 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004682 * Tracing state
4683 */
4684 mTracing.dump(result);
4685 result.append("\n");
4686
4687 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004688 * HWC layer minidump
4689 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004690 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004691 const auto displayId = display->getId();
4692 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004693 continue;
4694 }
4695
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004697 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004698 const sp<DisplayDevice> displayDevice = display;
4699 mCurrentState.traverseInZOrder(
4700 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004701 result.append("\n");
4702 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703
4704 /*
4705 * Dump HWComposer state
4706 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004708 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004709 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004710 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004712 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713
4714 /*
4715 * Dump gralloc state
4716 */
4717 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4718 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004719
4720 /*
4721 * Dump VrFlinger state if in use.
4722 */
4723 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4724 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004726 result.append("\n");
4727 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004728
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004729 result.append(mTimeStats->miniDump());
4730 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731}
4732
Chia-I Wu28f320b2018-05-03 11:02:56 -07004733void SurfaceFlinger::updateColorMatrixLocked() {
4734 mat4 colorMatrix;
4735 if (mGlobalSaturationFactor != 1.0f) {
4736 // Rec.709 luma coefficients
4737 float3 luminance{0.213f, 0.715f, 0.072f};
4738 luminance *= 1.0f - mGlobalSaturationFactor;
4739 mat4 saturationMatrix = mat4(
4740 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4741 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4742 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4743 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4744 );
4745 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4746 } else {
4747 colorMatrix = mClientColorMatrix * mDaltonizer();
4748 }
4749
4750 if (mCurrentState.colorMatrix != colorMatrix) {
4751 mCurrentState.colorMatrix = colorMatrix;
4752 mCurrentState.colorMatrixChanged = true;
4753 setTransactionFlags(eTransactionNeeded);
4754 }
4755}
4756
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004757status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004758#pragma clang diagnostic push
4759#pragma clang diagnostic error "-Wswitch-enum"
4760 switch (static_cast<ISurfaceComposerTag>(code)) {
4761 // These methods should at minimum make sure that the client requested
4762 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004763 case BOOT_FINISHED:
4764 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004765 case CREATE_DISPLAY:
4766 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004767 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004768 case GET_ANIMATION_FRAME_STATS:
4769 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004770 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004771 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004773 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4774 case SET_AUTO_LOW_LATENCY_MODE:
4775 case GET_GAME_CONTENT_TYPE_SUPPORT:
4776 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004777 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004778 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004779 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004780 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004781 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004782 case NOTIFY_POWER_HINT:
4783 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004784 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4785 IPCThreadState* ipc = IPCThreadState::self();
4786 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4787 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004788 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004789 }
Robert Carr1db73f62016-12-21 12:58:51 -08004790 return OK;
4791 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004793 IPCThreadState* ipc = IPCThreadState::self();
4794 const int pid = ipc->getCallingPid();
4795 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4797 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004798 return PERMISSION_DENIED;
4799 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004801 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004802 // Used by apps to hook Choreographer to SurfaceFlinger.
4803 case CREATE_DISPLAY_EVENT_CONNECTION:
4804 // The following calls are currently used by clients that do not
4805 // request necessary permissions. However, they do not expose any secret
4806 // information, so it is OK to pass them.
4807 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004808 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004809 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004810 case GET_PHYSICAL_DISPLAY_IDS:
4811 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004813 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004814 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004816 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 case GET_DISPLAY_STATS:
4818 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4819 // Calling setTransactionState is safe, because you need to have been
4820 // granted a reference to Client* and Handle* to do anything with it.
4821 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004822 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004823 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004824 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004825 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004826 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004827 // setFrameRate() is deliberately available for apps to call without any
4828 // special permissions.
4829 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004830 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4831 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004832 return OK;
4833 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004834 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004835 case CAPTURE_SCREEN:
4836 case ADD_REGION_SAMPLING_LISTENER:
4837 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004838 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004839 IPCThreadState* ipc = IPCThreadState::self();
4840 const int pid = ipc->getCallingPid();
4841 const int uid = ipc->getCallingUid();
4842 if ((uid != AID_GRAPHICS) &&
4843 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4844 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4845 return PERMISSION_DENIED;
4846 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004847 return OK;
4848 }
chaviw93df2ea2019-04-30 16:45:12 -07004849 case CAPTURE_SCREEN_BY_ID: {
4850 IPCThreadState* ipc = IPCThreadState::self();
4851 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004852 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004853 return OK;
4854 }
4855 return PERMISSION_DENIED;
4856 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004857 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858
4859 // These codes are used for the IBinder protocol to either interrogate the recipient
4860 // side of the transaction for its canonical interface descriptor or to dump its state.
4861 // We let them pass by default.
4862 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4863 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4864 code == IBinder::SYSPROPS_TRANSACTION) {
4865 return OK;
4866 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004867 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004869 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4871 return OK;
4872 }
4873 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4874 return PERMISSION_DENIED;
4875#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004876}
4877
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4879 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004880 status_t credentialCheck = CheckTransactCodeCredentials(code);
4881 if (credentialCheck != OK) {
4882 return credentialCheck;
4883 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004884
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4886 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004887 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004888 IPCThreadState* ipc = IPCThreadState::self();
4889 const int uid = ipc->getCallingUid();
4890 if (CC_UNLIKELY(uid != AID_SYSTEM
4891 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004892 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004893 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004894 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 return PERMISSION_DENIED;
4896 }
4897 int n;
4898 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004899 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004900 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004901 return NO_ERROR;
4902 case 1002: // SHOW_UPDATES
4903 n = data.readInt32();
4904 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004905 invalidateHwcGeometry();
4906 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004908 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004909 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004910 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004912 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004913 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004914 setTransactionFlags(
4915 eTransactionNeeded|
4916 eDisplayTransactionNeeded|
4917 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004918 return NO_ERROR;
4919 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004920 case 1006:{ // send empty update
4921 signalRefresh();
4922 return NO_ERROR;
4923 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004924 case 1008: // toggle use of hw composer
4925 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004926 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004927 invalidateHwcGeometry();
4928 repaintEverything();
4929 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004930 case 1009: // toggle use of transform hint
4931 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004932 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004933 invalidateHwcGeometry();
4934 repaintEverything();
4935 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004936 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004937 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938 reply->writeInt32(0);
4939 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004940 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004941 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004942 return NO_ERROR;
4943 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004944 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004945 if (!display) {
4946 return NAME_NOT_FOUND;
4947 }
4948
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004949 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004950 return NO_ERROR;
4951 }
4952 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004953 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004954 // daltonize
4955 n = data.readInt32();
4956 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004957 case 1:
4958 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4959 break;
4960 case 2:
4961 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4962 break;
4963 case 3:
4964 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4965 break;
4966 default:
4967 mDaltonizer.setType(ColorBlindnessType::None);
4968 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004969 }
4970 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004971 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004972 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004973 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004974 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004975
4976 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004977 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004978 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004979 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004980 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004981 // apply a color matrix
4982 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004983 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004984 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004985 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004986 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004987 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004988 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004989 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004990 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004991 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004992 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004993
4994 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4995 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004996 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004997 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4998 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4999 }
5000
Chia-I Wu28f320b2018-05-03 11:02:56 -07005001 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005002 return NO_ERROR;
5003 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005004 case 1016: { // Unused.
5005 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005006 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005007 case 1017: {
5008 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005009 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005010 return NO_ERROR;
5011 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005012 case 1018: { // Modify Choreographer's phase offset
5013 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005014 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005015 return NO_ERROR;
5016 }
5017 case 1019: { // Modify SurfaceFlinger's phase offset
5018 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005019 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005020 return NO_ERROR;
5021 }
Irvel468051e2016-06-13 16:44:44 -07005022 case 1020: { // Layer updates interceptor
5023 n = data.readInt32();
5024 if (n) {
5025 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005026 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005027 }
5028 else{
5029 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005030 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005031 }
5032 return NO_ERROR;
5033 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005034 case 1021: { // Disable HWC virtual displays
5035 n = data.readInt32();
5036 mUseHwcVirtualDisplays = !n;
5037 return NO_ERROR;
5038 }
Romain Guy0147a172017-06-01 13:53:56 -07005039 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005040 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005041 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005042
Chia-I Wu28f320b2018-05-03 11:02:56 -07005043 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005044 return NO_ERROR;
5045 }
Romain Guy54f154a2017-10-24 21:40:32 +01005046 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005047 int32_t colorMode;
5048
Chia-I Wu0d711262018-05-21 15:19:35 -07005049 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005050 if (data.readInt32(&colorMode) == NO_ERROR) {
5051 mForceColorMode = static_cast<ColorMode>(colorMode);
5052 }
Romain Guy54f154a2017-10-24 21:40:32 +01005053 invalidateHwcGeometry();
5054 repaintEverything();
5055 return NO_ERROR;
5056 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005057 // Deprecate, use 1030 to check whether the device is color managed.
5058 case 1024: {
5059 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005060 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005061 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005062 n = data.readInt32();
5063 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005064 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005065 Mutex::Autolock lock(mStateLock);
5066 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005067 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005068 reply->writeInt32(NO_ERROR);
5069 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005070 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005071 bool writeFile = false;
5072 {
5073 Mutex::Autolock lock(mStateLock);
5074 mTracingEnabledChanged = true;
5075 writeFile = mTracing.disable();
5076 }
5077
5078 if (writeFile) {
5079 reply->writeInt32(mTracing.writeToFile());
5080 } else {
5081 reply->writeInt32(NO_ERROR);
5082 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005083 }
5084 return NO_ERROR;
5085 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005086 case 1026: { // Get layer tracing status
5087 reply->writeBool(mTracing.isEnabled());
5088 return NO_ERROR;
5089 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005090 // Is a DisplayColorSetting supported?
5091 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005092 const auto display = getDefaultDisplayDevice();
5093 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005094 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005095 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005096
5097 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5098 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005099 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005100 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005101 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005102 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005103 reply->writeBool(true);
5104 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005105 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005106 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005107 break;
5108 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005109 reply->writeBool(
5110 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005111 break;
5112 }
5113 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005114 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005115 // Is VrFlinger active?
5116 case 1028: {
5117 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005118 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005119 return NO_ERROR;
5120 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005121 // Set buffer size for SF tracing (value in KB)
5122 case 1029: {
5123 n = data.readInt32();
5124 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5125 ALOGW("Invalid buffer size: %d KB", n);
5126 reply->writeInt32(BAD_VALUE);
5127 return BAD_VALUE;
5128 }
5129
5130 ALOGD("Updating trace buffer to %d KB", n);
5131 mTracing.setBufferSize(n * 1024);
5132 reply->writeInt32(NO_ERROR);
5133 return NO_ERROR;
5134 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005135 // Is device color managed?
5136 case 1030: {
5137 reply->writeBool(useColorManagement);
5138 return NO_ERROR;
5139 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005140 // Override default composition data space
5141 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5142 // && adb shell stop zygote && adb shell start zygote
5143 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5144 // adb shell stop zygote && adb shell start zygote
5145 case 1031: {
5146 Mutex::Autolock _l(mStateLock);
5147 n = data.readInt32();
5148 if (n) {
5149 n = data.readInt32();
5150 if (n) {
5151 Dataspace dataspace = static_cast<Dataspace>(n);
5152 if (!validateCompositionDataspace(dataspace)) {
5153 return BAD_VALUE;
5154 }
5155 mDefaultCompositionDataspace = dataspace;
5156 }
5157 n = data.readInt32();
5158 if (n) {
5159 Dataspace dataspace = static_cast<Dataspace>(n);
5160 if (!validateCompositionDataspace(dataspace)) {
5161 return BAD_VALUE;
5162 }
5163 mWideColorGamutCompositionDataspace = dataspace;
5164 }
5165 } else {
5166 // restore composition data space.
5167 mDefaultCompositionDataspace = defaultCompositionDataspace;
5168 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5169 }
5170 return NO_ERROR;
5171 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005172 // Set trace flags
5173 case 1033: {
5174 n = data.readUint32();
5175 ALOGD("Updating trace flags to 0x%x", n);
5176 mTracing.setTraceFlags(n);
5177 reply->writeInt32(NO_ERROR);
5178 return NO_ERROR;
5179 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005180 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005181 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005182 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005183 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005184 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005185 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005186 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005187 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005188 } else {
5189 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005190 }
5191 return NO_ERROR;
5192 }
Ady Abraham34392f72019-04-10 11:29:27 -07005193 case 1035: {
5194 n = data.readInt32();
5195 mDebugDisplayConfigSetByBackdoor = false;
5196 if (n >= 0) {
5197 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005198 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005199 if (result != NO_ERROR) {
5200 return result;
5201 }
5202 mDebugDisplayConfigSetByBackdoor = true;
5203 }
5204 return NO_ERROR;
5205 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005206 }
5207 }
5208 return err;
5209}
5210
Steven Thomas6d8110b2017-08-31 18:24:21 -07005211void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005212 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005213 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005214}
5215
Ana Krulec7d1d6832018-12-27 11:10:09 -08005216void SurfaceFlinger::repaintEverythingForHWC() {
5217 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005218 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005219 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005220}
5221
Ady Abrahama09852a2020-02-20 14:23:42 -08005222void SurfaceFlinger::kernelTimerChanged(bool expired) {
5223 static bool updateOverlay =
5224 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5225 if (!updateOverlay || !mRefreshRateOverlay) return;
5226
5227 // Update the overlay on the main thread to avoid race conditions with
5228 // mRefreshRateConfigs->getCurrentRefreshRate()
5229 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5230 if (mRefreshRateOverlay) {
5231 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5232 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005233 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005234 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5235 if (mDesiredActiveConfigChanged) {
5236 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5237 mDesiredActiveConfig.configId);
5238 }
5239
5240 return mRefreshRateConfigs->getCurrentRefreshRate();
5241 }();
5242 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5243
5244 if (current != min) {
5245 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5246 mEventQueue->invalidate();
5247 }
5248 }
5249 }));
5250}
5251
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005252// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5253class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005254public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005255 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5256 ~WindowDisconnector() {
5257 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005258 }
5259
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005260private:
5261 ANativeWindow* mWindow;
5262 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005263};
5264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005265status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005266 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005267 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5268 const Rect& sourceCrop, uint32_t reqWidth,
5269 uint32_t reqHeight, bool useIdentityTransform,
5270 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005271 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005272
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005273 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005274
Dominik Laskowski718f9602019-11-09 20:01:35 -08005275 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5276 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5277 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5278 renderAreaRotation = ui::Transform::ROT_0;
5279 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005280
Chia-I Wu20261cb2018-08-23 12:55:44 -07005281 sp<DisplayDevice> display;
5282 {
5283 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005284
Chia-I Wu20261cb2018-08-23 12:55:44 -07005285 display = getDisplayDeviceLocked(displayToken);
5286 if (!display) return BAD_VALUE;
5287
Chia-I Wucb023152018-08-28 12:57:23 -07005288 // set the requested width/height to the logical display viewport size
5289 // by default
5290 if (reqWidth == 0 || reqHeight == 0) {
5291 reqWidth = uint32_t(display->getViewport().width());
5292 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005293 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005294 }
5295
Peiyong Lin0e003c92018-09-17 11:09:51 -07005296 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005297 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005298
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005299 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5300 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005301 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005302 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005303}
5304
chaviw93df2ea2019-04-30 16:45:12 -07005305static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5306 switch (colorMode) {
5307 case ColorMode::DISPLAY_P3:
5308 case ColorMode::BT2100_PQ:
5309 case ColorMode::BT2100_HLG:
5310 case ColorMode::DISPLAY_BT2020:
5311 return Dataspace::DISPLAY_P3;
5312 default:
5313 return Dataspace::V0_SRGB;
5314 }
5315}
5316
5317const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5318 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5319 if (displayToken) {
5320 return getDisplayDeviceLocked(displayToken);
5321 }
5322 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5323 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005324 return getDisplayByLayerStack(displayOrLayerStack);
5325}
5326
5327const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005328 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005329 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005330 return display;
5331 }
5332 }
5333 return nullptr;
5334}
5335
5336status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5337 sp<GraphicBuffer>* outBuffer) {
5338 sp<DisplayDevice> display;
5339 uint32_t width;
5340 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005341 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005342 {
5343 Mutex::Autolock _l(mStateLock);
5344 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5345 if (!display) {
5346 return BAD_VALUE;
5347 }
5348
5349 width = uint32_t(display->getViewport().width());
5350 height = uint32_t(display->getViewport().height());
5351
Dominik Laskowski718f9602019-11-09 20:01:35 -08005352 const auto orientation = display->getOrientation();
5353 captureOrientation = ui::Transform::toRotationFlags(orientation);
5354
5355 switch (captureOrientation) {
5356 case ui::Transform::ROT_90:
5357 captureOrientation = ui::Transform::ROT_270;
5358 break;
5359
5360 case ui::Transform::ROT_270:
5361 captureOrientation = ui::Transform::ROT_90;
5362 break;
5363
5364 case ui::Transform::ROT_INVALID:
5365 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5366 captureOrientation = ui::Transform::ROT_0;
5367 break;
5368
5369 default:
5370 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005371 }
chaviw93df2ea2019-04-30 16:45:12 -07005372 *outDataspace =
5373 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5374 }
5375
5376 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5377 false /* captureSecureLayers */);
5378
5379 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5380 std::placeholders::_1);
5381 bool ignored = false;
5382 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5383 false /* useIdentityTransform */,
5384 ignored /* outCapturedSecureLayers */);
5385}
5386
Robert Carr866455f2019-04-02 16:28:26 -07005387status_t SurfaceFlinger::captureLayers(
5388 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5389 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5390 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5391 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005392 ATRACE_CALL();
5393
5394 class LayerRenderArea : public RenderArea {
5395 public:
Robert Carr578038f2018-03-09 12:25:24 -08005396 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005397 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005398 bool childrenOnly, const Rect& displayViewport)
5399 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005400 mLayer(layer),
5401 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005402 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005403 mFlinger(flinger),
5404 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005405 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005406 Rect getBounds() const override {
5407 const Layer::State& layerState(mLayer->getDrawingState());
5408 return mLayer->getBufferSize(layerState);
5409 }
Marissa Wall61c58622018-07-18 10:12:20 -07005410 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005411 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005412 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005413 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005414 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005415 }
chaviwa76b2712017-09-20 12:02:26 -07005416 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005417 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005418 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005419 Rect getSourceCrop() const override {
5420 if (mCrop.isEmpty()) {
5421 return getBounds();
5422 } else {
5423 return mCrop;
5424 }
5425 }
Robert Carr578038f2018-03-09 12:25:24 -08005426 class ReparentForDrawing {
5427 public:
5428 const sp<Layer>& oldParent;
5429 const sp<Layer>& newParent;
5430
Vishnu Nair4351ad52019-02-11 14:13:02 -08005431 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5432 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005433 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005434 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005435 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5436 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005437 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005438 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005439 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005440 };
5441
5442 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005443 const Rect sourceCrop = getSourceCrop();
5444 // no need to check rotation because there is none
5445 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5446 sourceCrop.height() != getReqHeight();
5447
Robert Carr578038f2018-03-09 12:25:24 -08005448 if (!mChildrenOnly) {
5449 mTransform = mLayer->getTransform().inverse();
5450 drawLayers();
5451 } else {
5452 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005453 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5454 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005455 // In the "childrenOnly" case we reparent the children to a screenshot
5456 // layer which has no properties set and which does not draw.
5457 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005458 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5459 "Screenshot Parent"s, w, h, 0,
5460 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005461
Vishnu Nair4351ad52019-02-11 14:13:02 -08005462 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005463 drawLayers();
5464 }
5465 }
chaviwa76b2712017-09-20 12:02:26 -07005466
chaviwa76b2712017-09-20 12:02:26 -07005467 private:
chaviw7206d492017-11-10 16:16:12 -08005468 const sp<Layer> mLayer;
5469 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005470
Peiyong Linefefaac2018-08-17 12:27:51 -07005471 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005472 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005473
5474 SurfaceFlinger* mFlinger;
5475 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005476 };
5477
Robert Carrc0df3122019-04-11 13:18:21 -07005478 int reqWidth = 0;
5479 int reqHeight = 0;
5480 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005481 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005482 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005483 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005484 {
5485 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005486
Robert Carrc0df3122019-04-11 13:18:21 -07005487 parent = fromHandle(layerHandleBinder);
5488 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5489 ALOGE("captureLayers called with an invalid or removed parent");
5490 return NAME_NOT_FOUND;
5491 }
5492
5493 const int uid = IPCThreadState::self()->getCallingUid();
5494 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5495 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5496 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5497 return PERMISSION_DENIED;
5498 }
5499
Vishnu Nairefc42e22019-12-03 17:36:12 -08005500 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005501 if (sourceCrop.width() <= 0) {
5502 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005503 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005504 }
5505
5506 if (sourceCrop.height() <= 0) {
5507 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005508 crop.bottom = parentSourceBounds.getHeight();
5509 }
5510
5511 if (crop.isEmpty() || frameScale <= 0.0f) {
5512 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5513 // crop was not specified, or an invalid frame scale was provided.
5514 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005515 }
5516 reqWidth = crop.width() * frameScale;
5517 reqHeight = crop.height() * frameScale;
5518
5519 for (const auto& handle : excludeHandles) {
5520 sp<Layer> excludeLayer = fromHandle(handle);
5521 if (excludeLayer != nullptr) {
5522 excludeLayers.emplace(excludeLayer);
5523 } else {
5524 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5525 return NAME_NOT_FOUND;
5526 }
5527 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005528
5529 auto display = getDisplayByLayerStack(parent->getLayerStack());
5530 if (!display) {
5531 return BAD_VALUE;
5532 }
5533
5534 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005535 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005536
Chia-I Wu20261cb2018-08-23 12:55:44 -07005537 // really small crop or frameScale
5538 if (reqWidth <= 0) {
5539 reqWidth = 1;
5540 }
5541 if (reqHeight <= 0) {
5542 reqHeight = 1;
5543 }
5544
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005545 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5546 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005547 auto traverseLayers = [parent, childrenOnly,
5548 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005549 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5550 if (!layer->isVisible()) {
5551 return;
Robert Carr578038f2018-03-09 12:25:24 -08005552 } else if (childrenOnly && layer == parent.get()) {
5553 return;
chaviwa76b2712017-09-20 12:02:26 -07005554 }
Robert Carr866455f2019-04-02 16:28:26 -07005555
5556 sp<Layer> p = layer;
5557 while (p != nullptr) {
5558 if (excludeLayers.count(p) != 0) {
5559 return;
5560 }
5561 p = p->getParent();
5562 }
5563
chaviwa76b2712017-09-20 12:02:26 -07005564 visitor(layer);
5565 });
5566 };
Robert Carr108b2c72019-04-02 16:32:58 -07005567
5568 bool outCapturedSecureLayers = false;
5569 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5570 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005571}
5572
5573status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5574 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005575 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005576 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005577 bool useIdentityTransform,
5578 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005579 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005580
Peiyong Lin0e003c92018-09-17 11:09:51 -07005581 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005582 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5583 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005584 *outBuffer =
5585 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5586 static_cast<android_pixel_format>(reqPixelFormat), 1,
5587 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005588
Robert Carr108b2c72019-04-02 16:32:58 -07005589 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5590 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005591}
5592
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005593status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5594 TraverseLayersFunction traverseLayers,
5595 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005596 bool useIdentityTransform,
5597 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005598 // This mutex protects syncFd and captureResult for communication of the return values from the
5599 // main thread back to this Binder thread
5600 std::mutex captureMutex;
5601 std::condition_variable captureCondition;
5602 std::unique_lock<std::mutex> captureLock(captureMutex);
5603 int syncFd = -1;
5604 std::optional<status_t> captureResult;
5605
Robert Carr03480e22018-01-04 16:02:06 -08005606 const int uid = IPCThreadState::self()->getCallingUid();
5607 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5608
Dominik Laskowski8c001672018-05-30 16:52:06 -07005609 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005610 // If there is a refresh pending, bug out early and tell the binder thread to try again
5611 // after the refresh.
5612 if (mRefreshPending) {
5613 ATRACE_NAME("Skipping screenshot for now");
5614 std::unique_lock<std::mutex> captureLock(captureMutex);
5615 captureResult = std::make_optional<status_t>(EAGAIN);
5616 captureCondition.notify_one();
5617 return;
5618 }
5619
5620 status_t result = NO_ERROR;
5621 int fd = -1;
5622 {
5623 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005624 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005625 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005626 useIdentityTransform, forSystem, &fd,
5627 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005628 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005629 }
5630
5631 {
5632 std::unique_lock<std::mutex> captureLock(captureMutex);
5633 syncFd = fd;
5634 captureResult = std::make_optional<status_t>(result);
5635 captureCondition.notify_one();
5636 }
5637 });
5638
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005639 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005640 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005641 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005642 while (*captureResult == EAGAIN) {
5643 captureResult.reset();
5644 result = postMessageAsync(message);
5645 if (result != NO_ERROR) {
5646 return result;
5647 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005648 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005649 }
5650 result = *captureResult;
5651 }
5652
5653 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005654 sync_wait(syncFd, -1);
5655 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005657
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005658 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005659}
5660
chaviwa76b2712017-09-20 12:02:26 -07005661void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005662 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005663 const sp<GraphicBuffer>& buffer,
5664 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005665 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005666
chaviwa76b2712017-09-20 12:02:26 -07005667 const auto reqWidth = renderArea.getReqWidth();
5668 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005669 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005670 const auto transform = renderArea.getTransform();
5671 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005672 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005673
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005674 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005675 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005676
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005677 // assume that bounds are never offset, and that they are the same as the
5678 // buffer bounds.
5679 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005680 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005681 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005682
5683 // Now take into account the rotation flag. We append a transform that
5684 // rotates the layer stack about the origin, then translate by buffer
5685 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005686 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005687 int displacementX = 0;
5688 int displacementY = 0;
5689 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5690 switch (rotation) {
5691 case ui::Transform::ROT_90:
5692 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005693 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694 break;
5695 case ui::Transform::ROT_180:
5696 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005697 displacementY = renderArea.getBounds().getWidth();
5698 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699 break;
5700 case ui::Transform::ROT_270:
5701 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005702 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005703 break;
5704 default:
5705 break;
5706 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005707
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005708 // We need to transform the clipping window into the right spot.
5709 // First, rotate the clipping rectangle by the rotation hint to get the
5710 // right orientation
5711 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5712 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5713 const vec4 rotClipTL = rotMatrix * clipTL;
5714 const vec4 rotClipBR = rotMatrix * clipBR;
5715 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5716 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5717 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5718 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5719
5720 // Now reposition the clipping rectangle with the displacement vector
5721 // computed above.
5722 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005723 clientCompositionDisplay.clip =
5724 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5725 newClipRight + displacementX, newClipBottom + displacementY);
5726
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005727 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005728 clientCompositionDisplay.globalTransform =
5729 clipTransform * clientCompositionDisplay.globalTransform;
5730
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005731 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5732 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005733
chaviw50da5042018-04-09 13:49:37 -07005734 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005735
Vishnu Nair9b079a22020-01-21 14:36:08 -08005736 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005737 fillLayer.source.buffer.buffer = nullptr;
5738 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5739 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5740 fillLayer.alpha = half(alpha);
5741 clientCompositionLayers.push_back(fillLayer);
5742
5743 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005744 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005745 const bool supportProtectedContent = false;
5746 Region clip(renderArea.getBounds());
5747 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5748 clip,
5749 useIdentityTransform,
5750 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5751 renderArea.isSecure(),
5752 supportProtectedContent,
5753 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005754 displayViewport,
5755 clientCompositionDisplay.outputDataspace,
5756 true, /* realContentIsVisible */
5757 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005758 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005759 std::vector<compositionengine::LayerFE::LayerSettings> results =
5760 layer->prepareClientCompositionList(targetSettings);
5761 clientCompositionLayers.insert(clientCompositionLayers.end(),
5762 std::make_move_iterator(results.begin()),
5763 std::make_move_iterator(results.end()));
5764 results.clear();
5765
chaviwa76b2712017-09-20 12:02:26 -07005766 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767
Vishnu Nair9b079a22020-01-21 14:36:08 -08005768 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5769 clientCompositionLayers.reserve(clientCompositionLayers.size());
5770 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5771 std::back_inserter(clientCompositionLayerPointers),
5772 [](compositionengine::LayerFE::LayerSettings& settings)
5773 -> renderengine::LayerSettings* { return &settings; });
5774
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005775 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005776 // Use an empty fence for the buffer fence, since we just created the buffer so
5777 // there is no need for synchronization with the GPU.
5778 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005779 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005780 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005781 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005782 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005783
5784 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005785}
5786
chaviwa76b2712017-09-20 12:02:26 -07005787status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5788 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005789 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005790 bool useIdentityTransform, bool forSystem,
5791 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005792 ATRACE_CALL();
5793
chaviwa76b2712017-09-20 12:02:26 -07005794 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005795 outCapturedSecureLayers =
5796 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005797 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005798
Robert Carr03480e22018-01-04 16:02:06 -08005799 // We allow the system server to take screenshots of secure layers for
5800 // use in situations like the Screen-rotation animation and place
5801 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005802 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005803 ALOGW("FB is protected: PERMISSION_DENIED");
5804 return PERMISSION_DENIED;
5805 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005806 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005807 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005808}
5809
chaviw95ef3c42019-02-14 10:55:09 -08005810void SurfaceFlinger::setInputWindowsFinished() {
5811 Mutex::Autolock _l(mStateLock);
5812
5813 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005814
chaviw95ef3c42019-02-14 10:55:09 -08005815 mTransactionCV.broadcast();
5816}
chaviw5f21a5e2019-02-14 10:00:34 -08005817
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005818// ---------------------------------------------------------------------------
5819
Edgar Arriaga844fa672020-01-16 14:21:42 -08005820void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5821 layersSortedByZ.traverse(visitor);
5822}
5823
Dan Stoza412903f2017-04-27 13:42:17 -07005824void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5825 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005826}
5827
Dan Stoza412903f2017-04-27 13:42:17 -07005828void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5829 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005830}
5831
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005832void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005833 const LayerVector::Visitor& visitor) {
5834 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005835 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005836 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005837 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005838 continue;
5839 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005840 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005841 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005842 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005843 return;
5844 }
chaviwa76b2712017-09-20 12:02:26 -07005845 if (!layer->isVisible()) {
5846 return;
5847 }
5848 visitor(layer);
5849 });
5850 }
5851}
5852
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005853status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5854 HwcConfigIndexType defaultConfig,
5855 float minRefreshRate,
5856 float maxRefreshRate) {
5857 Mutex::Autolock lock(mStateLock);
5858
Dominik Laskowski22488f62019-03-28 09:53:04 -07005859 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005860 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5861 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5862 // it should go thru setDesiredActiveConfig, similar to primary display.
5863 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5864 const auto displayId = display->getId();
5865 LOG_ALWAYS_FATAL_IF(!displayId);
5866
5867 HWC2::VsyncPeriodChangeConstraints constraints;
5868 constraints.desiredTimeNanos = systemTime();
5869 constraints.seamlessRequired = false;
5870
5871 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005872 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5873 constraints, &timeline) < 0) {
5874 return BAD_VALUE;
5875 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005876 if (timeline.refreshRequired) {
5877 repaintEverythingForHWC();
5878 }
5879
Ady Abrahamdfa37362020-01-21 18:02:39 -08005880 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005881 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005882 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5883 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005884 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005885 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005886 }
5887
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005888 if (mDebugDisplayConfigSetByBackdoor) {
5889 // ignore this request as config is overridden by backdoor
5890 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005891 }
5892
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005893 bool policyChanged;
5894 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5895 &policyChanged) < 0) {
5896 return BAD_VALUE;
5897 }
5898 if (!policyChanged) {
5899 return NO_ERROR;
5900 }
5901
5902 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5903 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005904
5905 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5906 // that listeners that care about a change in allowed configs can get the notification.
5907 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005908 const nsecs_t vsyncPeriod =
5909 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005910 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005911 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005912
Ana Krulec3f6a2062020-01-23 15:48:01 -08005913 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005914 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005915 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5916 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5917 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5918 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5919 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5920
5921 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5922 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5923 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005924 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005925 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005926 }
5927
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005928 return NO_ERROR;
5929}
5930
Ana Krulec0782b882019-10-15 17:34:54 -07005931status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005932 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005933 float maxRefreshRate) {
5934 ATRACE_CALL();
5935
5936 if (!displayToken) {
5937 return BAD_VALUE;
5938 }
5939
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005940 status_t result = NO_ERROR;
5941
Ana Krulec234bb162019-11-10 22:55:55 +01005942 postMessageSync(new LambdaMessage([&]() {
5943 const auto display = getDisplayDeviceLocked(displayToken);
5944 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005945 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005946 ALOGE("Attempt to set desired display configs for invalid display token %p",
5947 displayToken.get());
5948 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005949 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005950 ALOGW("Attempt to set desired display configs for virtual display");
5951 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005952 result =
5953 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5954 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005955 }
5956 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005957
5958 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005959}
5960
5961status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005962 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005963 float* outMinRefreshRate,
5964 float* outMaxRefreshRate) {
5965 ATRACE_CALL();
5966
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005967 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005968 return BAD_VALUE;
5969 }
5970
5971 Mutex::Autolock lock(mStateLock);
5972 const auto display = getDisplayDeviceLocked(displayToken);
5973 if (!display) {
5974 return NAME_NOT_FOUND;
5975 }
5976
5977 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005978 HwcConfigIndexType defaultConfig;
5979 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5980 *outDefaultConfig = defaultConfig.value();
5981 return NO_ERROR;
5982 } else if (display->isVirtual()) {
5983 return BAD_VALUE;
5984 } else {
5985 const auto displayId = display->getId();
5986 if (!displayId) {
5987 return BAD_VALUE;
5988 }
5989 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5990 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5991 *outMinRefreshRate = 1e9f / vsyncPeriod;
5992 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5993 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005994 }
Ana Krulec0782b882019-10-15 17:34:54 -07005995}
5996
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005997void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005998 mFlinger->setInputWindowsFinished();
5999}
6000
Robert Carrc0df3122019-04-11 13:18:21 -07006001sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006002 BBinder* b = nullptr;
6003 if (handle) {
6004 b = handle->localBinder();
6005 }
Robert Carrc0df3122019-04-11 13:18:21 -07006006 if (b == nullptr) {
6007 return nullptr;
6008 }
6009 auto it = mLayersByLocalBinderToken.find(b);
6010 if (it != mLayersByLocalBinderToken.end()) {
6011 return it->second.promote();
6012 }
6013 return nullptr;
6014}
6015
Dominik Laskowski75848362019-11-11 17:57:20 -08006016void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006017 mNumLayers++;
6018 mScheduler->registerLayer(layer);
6019}
6020
6021void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6022 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006023 removeFromOffscreenLayers(layer);
6024}
6025
6026// WARNING: ONLY CALL THIS FROM LAYER DTOR
6027// Here we add children in the current state to offscreen layers and remove the
6028// layer itself from the offscreen layer list. Since
6029// this is the dtor, it is safe to access the current state. This keeps us
6030// from dangling children layers such that they are not reachable from the
6031// Drawing state nor the offscreen layer list
6032// See b/141111965
6033void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6034 for (auto& child : layer->getCurrentChildren()) {
6035 mOffscreenLayers.emplace(child.get());
6036 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006037 mOffscreenLayers.erase(layer);
6038}
6039
Alec Mouri4545a8a2019-08-08 20:05:32 -07006040void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6041 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6042}
6043
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006044status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6045 float lightPosY, float lightPosZ,
6046 float lightRadius) {
6047 Mutex::Autolock _l(mStateLock);
6048 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6049 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6050 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6051 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6052 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6053
6054 // these values are overridden when calculating the shadow settings for a layer.
6055 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6056 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006057 return NO_ERROR;
6058}
6059
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006060const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6061 const {
6062 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6063 // on the work to remove the table in that bug rather than adding more to
6064 // it.
6065 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6066 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6067 // supported, and exposed via the
6068 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6069 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6070 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6071 };
6072 return genericLayerMetadataKeyMap;
6073}
6074
Steven Thomas62a4cf82020-01-31 12:04:03 -08006075status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6076 int8_t compatibility) {
6077 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6078 return BAD_VALUE;
6079 }
6080
6081 Mutex::Autolock lock(mStateLock);
6082 if (authenticateSurfaceTextureLocked(surface)) {
6083 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6084 if (layer->setFrameRate(
6085 Layer::FrameRate(frameRate,
6086 Layer::FrameRate::convertCompatibility(compatibility)))) {
6087 setTransactionFlags(eTraversalNeeded);
6088 }
6089 } else {
6090 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6091 return BAD_VALUE;
6092 }
6093 return NO_ERROR;
6094}
6095
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006096} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006097
Mathias Agopian3f844832013-08-07 21:24:32 -07006098#if defined(__gl_h_)
6099#error "don't include gl/gl.h in this file"
6100#endif
6101
6102#if defined(__gl2_h_)
6103#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006104#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006105
6106// TODO(b/129481165): remove the #pragma below and fix conversion issues
6107#pragma clang diagnostic pop // ignored "-Wconversion"