blob: 2294a9935950467119fd65ac08e9038f028a70a3 [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 Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800368 bool disableBlurs = atoi(value);
369 mEnableBlurs = supportsBlurs && !disableBlurs;
370 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
371 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800372 property_get("ro.sf.blurs_are_expensive", value, "0");
373 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800375 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800378 mGraphicBufferProducerListSizeLogThreshold =
379 std::max(static_cast<int>(0.95 *
380 static_cast<double>(mMaxGraphicBufferProducerListSize)),
381 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700382
Dan Stozaec460082018-12-17 15:35:09 -0800383 property_get("debug.sf.luma_sampling", value, "1");
384 mLumaSampling = atoi(value);
385
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800386 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800387 mDisableClientCompositionCache = atoi(value);
388
Romain Guy11d63f42017-07-20 12:47:14 -0700389 // We should be reading 'persist.sys.sf.color_saturation' here
390 // but since /data may be encrypted, we need to wait until after vold
391 // comes online to attempt to read the property. The property is
392 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800393
394 if (useTrebleTestingOverride()) {
395 // Without the override SurfaceFlinger cannot connect to HIDL
396 // services that are not listed in the manifests. Considered
397 // deriving the setting from the set service name, but it
398 // would be brittle if the name that's not 'default' is used
399 // for production purposes later on.
400 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
401 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800402
403 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404}
405
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406void SurfaceFlinger::onFirstRef()
407{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800408 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409}
410
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700411SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412
Dan Stozac7014012014-02-14 15:03:43 -0800413void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414{
415 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700416 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417
Andy McFadden13a082e2012-08-24 10:16:42 -0700418 // restore initial conditions (default device unblank, etc)
419 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420
421 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700422 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423}
424
Robert Carr1db73f62016-12-21 12:58:51 -0800425static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700426 status_t err = client->initCheck();
427 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800428 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429 }
Robert Carr1db73f62016-12-21 12:58:51 -0800430 return nullptr;
431}
432
433sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
434 return initClient(new Client(this));
435}
436
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700437sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
438 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439{
440 class DisplayToken : public BBinder {
441 sp<SurfaceFlinger> flinger;
442 virtual ~DisplayToken() {
443 // no more references, this display must be terminated
444 Mutex::Autolock _l(flinger->mStateLock);
445 flinger->mCurrentState.displays.removeItem(this);
446 flinger->setTransactionFlags(eDisplayTransactionNeeded);
447 }
448 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700449 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700450 : flinger(flinger) {
451 }
452 };
453
454 sp<BBinder> token = new DisplayToken(this);
455
456 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457 // Display ID is assigned when virtual display is allocated by HWC.
458 DisplayDeviceState state;
459 state.isSecure = secure;
460 state.displayName = displayName;
461 mCurrentState.displays.add(token, state);
462 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700463 return token;
464}
465
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700466void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 Mutex::Autolock _l(mStateLock);
468
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
470 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700471 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 return;
473 }
474
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
476 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 ALOGE("destroyDisplay called for non-virtual display");
478 return;
479 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480 mInterceptor->saveDisplayDeletion(state.sequenceId);
481 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 setTransactionFlags(eDisplayTransactionNeeded);
483}
484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
486 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800488 const auto internalDisplayId = getInternalDisplayIdLocked();
489 if (!internalDisplayId) {
490 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700491 }
492
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800493 std::vector<PhysicalDisplayId> displayIds;
494 displayIds.reserve(mPhysicalDisplayTokens.size());
495 displayIds.push_back(internalDisplayId->value);
496
497 for (const auto& [id, token] : mPhysicalDisplayTokens) {
498 if (id != *internalDisplayId) {
499 displayIds.push_back(id.value);
500 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503 return displayIds;
504}
505
506sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
507 Mutex::Autolock lock(mStateLock);
508 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700509}
510
Ady Abraham37965d42018-11-01 13:43:32 -0700511status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
512 if (!outGetColorManagement) {
513 return BAD_VALUE;
514 }
515 *outGetColorManagement = useColorManagement;
516 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700517}
518
Lloyd Pique441d5042018-10-18 16:49:51 -0700519HWComposer& SurfaceFlinger::getHwComposer() const {
520 return mCompositionEngine->getHwComposer();
521}
522
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700523renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
524 return mCompositionEngine->getRenderEngine();
525}
526
Lloyd Pique70d91362018-10-18 16:02:55 -0700527compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
528 return *mCompositionEngine.get();
529}
530
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531void SurfaceFlinger::bootFinished()
532{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700533 if (mBootFinished == true) {
534 ALOGE("Extra call to bootFinished");
535 return;
536 }
537 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700538 if (mStartPropertySetThread->join() != NO_ERROR) {
539 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800540 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541 const nsecs_t now = systemTime();
542 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000543 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544
Mikael Pessa90092f42019-08-26 17:22:04 -0700545 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000546 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700547
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548 // wait patiently for the window manager death
549 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700550 mWindowManager = defaultServiceManager()->getService(name);
551 if (mWindowManager != 0) {
552 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553 }
Robert Carr720e5062018-07-30 17:45:14 -0700554 sp<IBinder> input(defaultServiceManager()->getService(
555 String16("inputflinger")));
556 if (input == nullptr) {
557 ALOGE("Failed to link to input service");
558 } else {
559 mInputFlinger = interface_cast<IInputFlinger>(input);
560 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561
Steven Thomas050b2c82017-03-06 11:45:16 -0800562 if (mVrFlinger) {
563 mVrFlinger->OnBootFinished();
564 }
565
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700566 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700567 // formerly we would just kill the process, but we now ask it to exit so it
568 // can choose where to stop the animation.
569 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700570
571 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
572 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
573 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700574
Ana Krulecbd6654b2019-02-15 15:18:15 -0800575 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800576 readPersistentProperties();
577 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800578
Ady Abraham8a82ba62020-01-17 12:43:17 -0800579 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
580 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
581 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
582 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584}
585
Dan Stoza436ccf32018-06-21 12:10:12 -0700586uint32_t SurfaceFlinger::getNewTexture() {
587 {
588 std::lock_guard lock(mTexturePoolMutex);
589 if (!mTexturePool.empty()) {
590 uint32_t name = mTexturePool.back();
591 mTexturePool.pop_back();
592 ATRACE_INT("TexturePoolSize", mTexturePool.size());
593 return name;
594 }
595
596 // The pool was too small, so increase it for the future
597 ++mTexturePoolSize;
598 }
599
600 // The pool was empty, so we need to get a new texture name directly using a
601 // blocking call to the main thread
602 uint32_t name = 0;
603 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
604 return name;
605}
606
Mathias Agopian3f844832013-08-07 21:24:32 -0700607void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700608 std::lock_guard lock(mTexturePoolMutex);
609 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
610 // to actually delete this or not based on mTexturePoolSize
611 mTexturePool.push_back(texture);
612 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700613}
614
Wei Wangf9b05ee2017-07-19 20:59:39 -0700615// Do not call property_set on main thread which will be blocked by init
616// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700618 ALOGI( "SurfaceFlinger's main thread ready to run. "
619 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800621
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700623 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800624 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700625 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
626 renderengine::RenderEngineCreationArgs::Builder()
627 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
628 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
629 .setUseColorManagerment(useColorManagement)
630 .setEnableProtectedContext(enable_protected_contents(false))
631 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800632 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700633 .setContextPriority(useContextPriority
634 ? renderengine::RenderEngine::ContextPriority::HIGH
635 : renderengine::RenderEngine::ContextPriority::MEDIUM)
636 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800637 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700638
639 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
640 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700641 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800642 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800643 // Process any initial hotplug and resulting display changes.
644 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700645 const auto display = getDefaultDisplayDeviceLocked();
646 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700647 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800649
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700652 // This callback is called from the vr flinger dispatch thread. We
653 // need to call signalTransaction(), which requires holding
654 // mStateLock when we're not on the main thread. Acquiring
655 // mStateLock from the vr flinger dispatch thread might trigger a
656 // deadlock in surface flinger (see b/66916578), so post a message
657 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700659 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
660 mVrFlingerRequestsDisplay = requestDisplay;
661 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700662 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800663 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
665 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700666 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 .value_or(0),
668 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 if (!mVrFlinger) {
670 ALOGE("Failed to start vrflinger");
671 }
672 }
673
Mathias Agopian92a979a2012-08-02 18:32:23 -0700674 // initialize our drawing state
675 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700676
Andy McFadden13a082e2012-08-24 10:16:42 -0700677 // set initial conditions (e.g. unblank default device)
678 initializeDisplays();
679
Steven Thomas137d4bc2019-07-25 16:55:14 -0700680 char primeShaderCache[PROPERTY_VALUE_MAX];
681 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
682 if (atoi(primeShaderCache)) {
683 getRenderEngine().primeCache();
684 }
Dan Stoza4e637772016-07-28 13:31:51 -0700685
Wei Wangf9b05ee2017-07-19 20:59:39 -0700686 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700687
688 const bool presentFenceReliable =
689 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
690 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691
692 if (mStartPropertySetThread->Start() != NO_ERROR) {
693 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800694 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800695
Dan Stoza9e56aa02015-11-02 13:00:03 -0800696 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700697}
698
Romain Guy11d63f42017-07-20 12:47:14 -0700699void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700700 Mutex::Autolock _l(mStateLock);
701
Romain Guy11d63f42017-07-20 12:47:14 -0700702 char value[PROPERTY_VALUE_MAX];
703
704 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800705 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700706 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800707 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100708
709 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700710 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800711
712 property_get("persist.sys.sf.color_mode", value, "0");
713 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700714}
715
Mathias Agopiana67e4182012-06-19 17:26:12 -0700716void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800717 // Start boot animation service by setting a property mailbox
718 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800720 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700721 if (mStartPropertySetThread->join() != NO_ERROR) {
722 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800723 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700724}
725
Mathias Agopian875d8e12013-06-07 15:35:48 -0700726size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700727 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700728}
729
Mathias Agopian875d8e12013-06-07 15:35:48 -0700730size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700731 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700732}
733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800734// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800735
Jamie Gennis582270d2011-08-17 18:19:00 -0700736bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800737 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800738 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800739 return authenticateSurfaceTextureLocked(bufferProducer);
740}
741
742bool SurfaceFlinger::authenticateSurfaceTextureLocked(
743 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800744 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800745 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800746}
747
Brian Anderson6b376712017-04-04 10:51:39 -0700748status_t SurfaceFlinger::getSupportedFrameTimestamps(
749 std::vector<FrameEvent>* outSupported) const {
750 *outSupported = {
751 FrameEvent::REQUESTED_PRESENT,
752 FrameEvent::ACQUIRE,
753 FrameEvent::LATCH,
754 FrameEvent::FIRST_REFRESH_START,
755 FrameEvent::LAST_REFRESH_START,
756 FrameEvent::GPU_COMPOSITION_DONE,
757 FrameEvent::DEQUEUE_READY,
758 FrameEvent::RELEASE,
759 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700760 ConditionalLock _l(mStateLock,
761 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700762 if (!getHwComposer().hasCapability(
763 HWC2::Capability::PresentFenceIsNotReliable)) {
764 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
765 }
766 return NO_ERROR;
767}
768
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800769status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
770 if (!displayToken || !state) {
771 return BAD_VALUE;
772 }
773
774 Mutex::Autolock lock(mStateLock);
775
776 const auto display = getDisplayDeviceLocked(displayToken);
777 if (!display) {
778 return NAME_NOT_FOUND;
779 }
780
781 state->layerStack = display->getLayerStack();
782 state->orientation = display->getOrientation();
783
784 const Rect viewport = display->getViewport();
785 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
786
787 return NO_ERROR;
788}
789
790status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
791 if (!displayToken || !info) {
792 return BAD_VALUE;
793 }
794
795 Mutex::Autolock lock(mStateLock);
796
797 const auto display = getDisplayDeviceLocked(displayToken);
798 if (!display) {
799 return NAME_NOT_FOUND;
800 }
801
Dominik Laskowski55c85402020-01-21 16:25:47 -0800802 if (const auto connectionType = display->getConnectionType())
803 info->connectionType = *connectionType;
804 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800805 return INVALID_OPERATION;
806 }
807
808 if (mEmulatedDisplayDensity) {
809 info->density = mEmulatedDisplayDensity;
810 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800811 info->density = info->connectionType == DisplayConnectionType::Internal
812 ? mInternalDisplayDensity
813 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800814 }
815
816 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200817 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800818
819 return NO_ERROR;
820}
821
Dominik Laskowski22488f62019-03-28 09:53:04 -0700822status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 return BAD_VALUE;
826 }
827
Dominik Laskowski22488f62019-03-28 09:53:04 -0700828 Mutex::Autolock lock(mStateLock);
829
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800830 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700831 if (!displayId) {
832 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700841
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800842 auto width = hwConfig->getWidth();
843 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800845 auto xDpi = hwConfig->getDpiX();
846 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700847
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800848 if (isInternal &&
849 (internalDisplayOrientation == ui::ROTATION_90 ||
850 internalDisplayOrientation == ui::ROTATION_270)) {
851 std::swap(width, height);
852 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 }
854
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800855 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 if (mEmulatedDisplayDensity) {
858 config.xDpi = mEmulatedDisplayDensity;
859 config.yDpi = mEmulatedDisplayDensity;
860 } else {
861 config.xDpi = xDpi;
862 config.yDpi = yDpi;
863 }
864
865 const nsecs_t period = hwConfig->getVsyncPeriod();
866 config.refreshRate = 1e9f / period;
867
868 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
869 config.appVsyncOffset = offsets.late.app;
870 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800871 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872
Andy McFadden91b2ca82014-06-13 14:04:23 -0700873 // This is how far in advance a buffer must be queued for
874 // presentation at a given time. If you want a buffer to appear
875 // on the screen at time N, you must submit the buffer before
876 // (N - presentationDeadline).
877 //
878 // Normally it's one full refresh period (to give SF a chance to
879 // latch the buffer), but this can be reduced by configuring a
880 // DispSync offset. Any additional delays introduced by the hardware
881 // composer or panel must be accounted for here.
882 //
883 // We add an additional 1ms to allow for processing time and
884 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800885 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700886
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800887 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700888 }
889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 return NO_ERROR;
891}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700892
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700893status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
894 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700895 return BAD_VALUE;
896 }
897
Ana Krulecc2870422019-01-29 19:00:58 -0800898 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700899 return NO_ERROR;
900}
901
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700902int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
903 const auto display = getDisplayDevice(displayToken);
904 if (!display) {
905 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800906 return BAD_VALUE;
907 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700908
Steven Thomasc9098452019-09-30 17:15:05 -0700909 if (display->isPrimary()) {
910 std::lock_guard<std::mutex> lock(mActiveConfigLock);
911 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800912 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700913 }
Steven Thomasc9098452019-09-30 17:15:05 -0700914 }
Ady Abraham2139f732019-11-13 18:56:40 -0800915
916 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Ady Abraham03b02dd2019-03-21 15:40:11 -0700919void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800920 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800921 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800922 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800923
Ady Abrahamb838aed2019-02-12 15:30:16 -0800924 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800925 if (mDesiredActiveConfigChanged) {
926 // If a config change is pending, just cache the latest request in
927 // mDesiredActiveConfig
928 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
929 mDesiredActiveConfig = info;
930 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
931 } else {
932 // Check is we are already at the desired config
933 const auto display = getDefaultDisplayDeviceLocked();
934 if (!display || display->getActiveConfig() == refreshRate.configId) {
935 return;
936 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800937
Ady Abraham59db0a32020-03-02 18:04:20 -0800938 // Initiate a config change.
939 mDesiredActiveConfigChanged = true;
940 mDesiredActiveConfig = info;
941
Ady Abrahamb838aed2019-02-12 15:30:16 -0800942 // This will trigger HWC refresh without resetting the idle timer.
943 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700944 // Start receiving vsync samples now, so that we can detect a period
945 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800946 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700947 // As we called to set period, we will call to onRefreshRateChangeCompleted once
948 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700949 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800950
Ady Abraham9e16a482019-12-03 17:19:41 -0800951 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
952 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700954
955 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800956 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700957 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958}
959
960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
961 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800962
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100963 if (!displayToken) {
964 return BAD_VALUE;
965 }
Ady Abraham838de062019-02-04 10:24:03 -0800966
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100967 status_t result = NO_ERROR;
968
969 postMessageSync(new LambdaMessage([&]() {
970 const auto display = getDisplayDeviceLocked(displayToken);
971 if (!display) {
972 ALOGE("Attempt to set allowed display configs for invalid display token %p",
973 displayToken.get());
974 result = BAD_VALUE;
975 } else if (display->isVirtual()) {
976 ALOGW("Attempt to set allowed display configs for virtual display");
977 result = BAD_VALUE;
978 } else {
979 HwcConfigIndexType config(mode);
980 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
981 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
982 refreshRate.fps);
983 }
984 }));
985
986 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987}
988
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989void SurfaceFlinger::setActiveConfigInternal() {
990 ATRACE_CALL();
991
Dominik Laskowski22488f62019-03-28 09:53:04 -0700992 const auto display = getDefaultDisplayDeviceLocked();
993 if (!display) {
994 return;
995 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996
Dominik Laskowski22488f62019-03-28 09:53:04 -0700997 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800998 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700999 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001000 display->setActiveConfig(mUpcomingActiveConfig.configId);
1001
Ady Abraham2e1dd892020-03-05 13:48:36 -08001002 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001003 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -08001004 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1005 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001006 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001007
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001008 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001009 const nsecs_t vsyncPeriod =
1010 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1011 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001012 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001013 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001014 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001015}
1016
Ady Abraham53852a52019-05-28 18:07:44 -07001017void SurfaceFlinger::desiredActiveConfigChangeDone() {
1018 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1019 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1020 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001021
Ady Abraham2e1dd892020-03-05 13:48:36 -08001022 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001023 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001024 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001025 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1026 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001027}
1028
Dominik Laskowski22488f62019-03-28 09:53:04 -07001029bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001030 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001031 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001033 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001035 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 return true;
1037 }
1038
1039 // We received the present fence from the HWC, so we assume it successfully updated
1040 // the config, hence we update SF.
1041 mCheckPendingFence = false;
1042 setActiveConfigInternal();
1043 }
1044
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001045 // Store the local variable to release the lock.
1046 ActiveConfigInfo desiredActiveConfig;
1047 {
1048 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049 if (!mDesiredActiveConfigChanged) {
1050 return false;
1051 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001052 desiredActiveConfig = mDesiredActiveConfig;
1053 }
1054
Ady Abraham2e1dd892020-03-05 13:48:36 -08001055 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001056 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1057 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1058 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001059 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1061 // display is not valid or we are already in the requested mode
1062 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001063 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001064 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001065 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001066
Ady Abraham838de062019-02-04 10:24:03 -08001067 // Desired active config was set, it is different than the config currently in use, however
1068 // allowed configs might have change by the time we process the refresh.
1069 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001070 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001071 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001072 return false;
1073 }
Alec Mouri7f015182019-07-11 13:56:22 -07001074
Ady Abrahamb838aed2019-02-12 15:30:16 -08001075 mUpcomingActiveConfig = desiredActiveConfig;
1076 const auto displayId = display->getId();
1077 LOG_ALWAYS_FATAL_IF(!displayId);
1078
Ady Abraham2139f732019-11-13 18:56:40 -08001079 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001080
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001081 // TODO(b/142753666) use constrains
1082 HWC2::VsyncPeriodChangeConstraints constraints;
1083 constraints.desiredTimeNanos = systemTime();
1084 constraints.seamlessRequired = false;
1085
1086 HWC2::VsyncPeriodChangeTimeline outTimeline;
1087 auto status =
1088 getHwComposer().setActiveConfigWithConstraints(*displayId,
1089 mUpcomingActiveConfig.configId.value(),
1090 constraints, &outTimeline);
1091 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001092 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1093 // to be sent. We just log the error in this case.
1094 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001095 return false;
1096 }
1097
1098 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1099 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001100 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001101 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001102}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1105 Vector<ColorMode>* outColorModes) {
1106 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001107 return BAD_VALUE;
1108 }
1109
Peiyong Lina52f0292018-03-14 17:26:31 -07001110 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001111 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001112 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001113 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1114
1115 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1116 if (!displayId) {
1117 return NAME_NOT_FOUND;
1118 }
1119
Dominik Laskowski075d3172018-05-24 15:50:06 -07001120 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001121 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001122 }
Michael Wright28f24d02016-07-12 13:30:53 -07001123 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001124
1125 // If it's built-in display and the configuration claims it's not wide color capable,
1126 // filter out all wide color modes. The typical reason why this happens is that the
1127 // hardware is not good enough to support GPU composition of wide color, and thus the
1128 // OEMs choose to disable this capability.
1129 if (isInternalDisplay && !hasWideColorDisplay) {
1130 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1131 isWideColorMode);
1132 } else {
1133 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1134 }
Michael Wright28f24d02016-07-12 13:30:53 -07001135
1136 return NO_ERROR;
1137}
1138
Daniel Solomon42d04562019-01-20 21:03:19 -08001139status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1140 ui::DisplayPrimaries &primaries) {
1141 if (!displayToken) {
1142 return BAD_VALUE;
1143 }
1144
1145 // Currently we only support this API for a single internal display.
1146 if (getInternalDisplayToken() != displayToken) {
1147 return BAD_VALUE;
1148 }
1149
1150 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1151 return NO_ERROR;
1152}
1153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001154ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1155 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001156 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001157 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001158 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001159}
1160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001162 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163 Vector<ColorMode> modes;
1164 getDisplayColorModes(displayToken, &modes);
1165 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1166 if (mode < ColorMode::NATIVE || !exists) {
1167 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1168 decodeColorMode(mode).c_str(), mode, displayToken.get());
1169 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001170 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001171 const auto display = getDisplayDevice(displayToken);
1172 if (!display) {
1173 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1174 decodeColorMode(mode).c_str(), mode, displayToken.get());
1175 } else if (display->isVirtual()) {
1176 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1177 decodeColorMode(mode).c_str(), mode);
1178 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001179 display->getCompositionDisplay()->setColorProfile(
1180 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1181 RenderIntent::COLORIMETRIC,
1182 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001183 }
1184 }));
1185
Michael Wright28f24d02016-07-12 13:30:53 -07001186 return NO_ERROR;
1187}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001188
Galia Peycheva5492cb52019-10-30 14:13:16 +01001189status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1190 bool* outSupport) const {
1191 Mutex::Autolock _l(mStateLock);
1192
1193 if (!displayToken) {
1194 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1195 return BAD_VALUE;
1196 }
1197 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1198 if (!displayId) {
1199 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1200 displayToken.get());
1201 return NAME_NOT_FOUND;
1202 }
1203 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1204 HWC2::DisplayCapability::AutoLowLatencyMode);
1205 return NO_ERROR;
1206}
1207
1208void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1209 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1210}
1211
1212void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1213 if (!displayToken) {
1214 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1215 return;
1216 }
1217 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1218 if (!displayId) {
1219 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1220 displayToken.get());
1221 return;
1222 }
1223
1224 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1225}
1226
1227status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1228 bool* outSupport) const {
1229 Mutex::Autolock _l(mStateLock);
1230
1231 if (!displayToken) {
1232 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1233 return BAD_VALUE;
1234 }
1235 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1236 if (!displayId) {
1237 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1238 displayToken.get());
1239 return NAME_NOT_FOUND;
1240 }
1241
1242 std::vector<HWC2::ContentType> outSupportedContentTypes;
1243 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1244 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1245 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1246 return NO_ERROR;
1247}
1248
1249void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1250 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1251}
1252
1253void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1254 if (!displayToken) {
1255 ALOGE("setGameContentType() failed. Missing display token.");
1256 return;
1257 }
1258 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1259 if (!displayId) {
1260 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1261 displayToken.get());
1262 return;
1263 }
1264
1265 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1266 getHwComposer().setContentType(*displayId, type);
1267}
1268
Svetoslavd85084b2014-03-20 10:28:31 -07001269status_t SurfaceFlinger::clearAnimationFrameStats() {
1270 Mutex::Autolock _l(mStateLock);
1271 mAnimFrameTracker.clearStats();
1272 return NO_ERROR;
1273}
1274
1275status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1276 Mutex::Autolock _l(mStateLock);
1277 mAnimFrameTracker.getStats(outStats);
1278 return NO_ERROR;
1279}
1280
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001281status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1282 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001283 Mutex::Autolock _l(mStateLock);
1284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001285 const auto display = getDisplayDeviceLocked(displayToken);
1286 if (!display) {
1287 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001288 return BAD_VALUE;
1289 }
1290
Peiyong Linfb069302018-04-25 14:34:31 -07001291 // At this point the DisplayDeivce should already be set up,
1292 // meaning the luminance information is already queried from
1293 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001294 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001295 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1296 capabilities.getDesiredMaxLuminance(),
1297 capabilities.getDesiredMaxAverageLuminance(),
1298 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001299
1300 return NO_ERROR;
1301}
1302
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001303std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1304 const DisplayDevice& display) const {
1305 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1306 // avoid repetitive HAL IPC and EDID parsing.
1307 const auto displayId = display.getId();
1308 LOG_FATAL_IF(!displayId);
1309
1310 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1311 LOG_FATAL_IF(!hwcDisplayId);
1312
1313 uint8_t port;
1314 DisplayIdentificationData data;
1315 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1316 ALOGV("%s: No identification data.", __FUNCTION__);
1317 return {};
1318 }
1319
1320 const auto info = parseDisplayIdentificationData(port, data);
1321 if (!info) {
1322 return {};
1323 }
1324 return info->deviceProductInfo;
1325}
1326
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001327status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1328 ui::PixelFormat* outFormat,
1329 ui::Dataspace* outDataspace,
1330 uint8_t* outComponentMask) const {
1331 if (!outFormat || !outDataspace || !outComponentMask) {
1332 return BAD_VALUE;
1333 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001334 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001335 if (!display || !display->getId()) {
1336 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1337 return BAD_VALUE;
1338 }
1339 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1340 outDataspace, outComponentMask);
1341}
1342
Kevin DuBois74e53772018-11-19 10:52:38 -08001343status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1344 bool enable, uint8_t componentMask,
1345 uint64_t maxFrames) const {
1346 const auto display = getDisplayDevice(displayToken);
1347 if (!display || !display->getId()) {
1348 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1349 return BAD_VALUE;
1350 }
1351
1352 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1353 componentMask, maxFrames);
1354}
1355
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001356status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1357 uint64_t maxFrames, uint64_t timestamp,
1358 DisplayedFrameStats* outStats) const {
1359 const auto display = getDisplayDevice(displayToken);
1360 if (!display || !display->getId()) {
1361 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1362 return BAD_VALUE;
1363 }
1364
1365 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1366 outStats);
1367}
1368
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001369status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1370 if (!outSupported) {
1371 return BAD_VALUE;
1372 }
1373 *outSupported = getRenderEngine().supportsProtectedContent();
1374 return NO_ERROR;
1375}
1376
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001377status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1378 bool* outIsWideColorDisplay) const {
1379 if (!displayToken || !outIsWideColorDisplay) {
1380 return BAD_VALUE;
1381 }
1382 Mutex::Autolock _l(mStateLock);
1383 const auto display = getDisplayDeviceLocked(displayToken);
1384 if (!display) {
1385 return BAD_VALUE;
1386 }
Peiyong Linff84a152019-05-17 18:36:19 -07001387
1388 // Use hasWideColorDisplay to override built-in display.
1389 const auto displayId = display->getId();
1390 if (displayId && displayId == getInternalDisplayIdLocked()) {
1391 *outIsWideColorDisplay = hasWideColorDisplay;
1392 return NO_ERROR;
1393 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394 *outIsWideColorDisplay = display->hasWideColorGamut();
1395 return NO_ERROR;
1396}
1397
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001398status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001399 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001400 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001401
Dominik Laskowski6505f792019-09-18 11:10:05 -07001402 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1403 mEventQueue->setEventConnection(
1404 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001405 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001406 }));
1407
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001408 return NO_ERROR;
1409}
1410
1411status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001412 Mutex::Autolock lock(mStateLock);
1413 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414}
1415
Lloyd Pique755e3192018-01-31 16:46:15 -08001416status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1417 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001418 // Try to acquire a lock for 1s, fail gracefully
1419 const status_t err = mStateLock.timedLock(s2ns(1));
1420 const bool locked = (err == NO_ERROR);
1421 if (!locked) {
1422 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1423 return TIMED_OUT;
1424 }
1425
1426 outLayers->clear();
1427 mCurrentState.traverseInZOrder([&](Layer* layer) {
1428 outLayers->push_back(layer->getLayerDebugInfo());
1429 });
1430
1431 mStateLock.unlock();
1432 return NO_ERROR;
1433}
1434
Peiyong Linc6780972018-10-28 15:24:08 -07001435status_t SurfaceFlinger::getCompositionPreference(
1436 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1437 Dataspace* outWideColorGamutDataspace,
1438 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001439 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001440 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001441 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001442 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001443 return NO_ERROR;
1444}
1445
Dan Stozaec460082018-12-17 15:35:09 -08001446status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1447 const sp<IBinder>& stopLayerHandle,
1448 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001449 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001450 return BAD_VALUE;
1451 }
1452 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001453 return NO_ERROR;
1454}
1455
Dan Stozaec460082018-12-17 15:35:09 -08001456status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001457 if (!listener) {
1458 return BAD_VALUE;
1459 }
Dan Stozaec460082018-12-17 15:35:09 -08001460 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001461 return NO_ERROR;
1462}
Dan Gittik57e63c52019-01-18 16:37:54 +00001463
1464status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1465 bool* outSupport) const {
1466 if (!displayToken || !outSupport) {
1467 return BAD_VALUE;
1468 }
1469 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1470 if (!displayId) {
1471 return NAME_NOT_FOUND;
1472 }
1473 *outSupport =
1474 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1475 return NO_ERROR;
1476}
1477
1478status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1479 float brightness) const {
1480 if (!displayToken) {
1481 return BAD_VALUE;
1482 }
1483 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1484 if (!displayId) {
1485 return NAME_NOT_FOUND;
1486 }
1487 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1488}
1489
Ady Abraham8532d012019-05-08 14:50:56 -07001490status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1491 PowerHint powerHint = static_cast<PowerHint>(hintId);
1492
1493 if (powerHint == PowerHint::INTERACTION) {
1494 mScheduler->notifyTouchEvent();
1495 }
1496
1497 return NO_ERROR;
1498}
1499
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001500// ----------------------------------------------------------------------------
1501
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001502sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001503 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001504 const auto& handle =
1505 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001506
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001507 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001508}
1509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001510// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511
1512void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001513 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001514}
1515
1516void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001517 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001518 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001519 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001520}
1521
1522void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001523 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001524 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001525 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526}
1527
1528void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001529 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001530 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531}
1532
1533status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001534 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001535 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001536}
1537
1538status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001539 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001540 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001541 if (res == NO_ERROR) {
1542 msg->wait();
1543 }
1544 return res;
1545}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001546
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001547void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001548 do {
1549 waitForEvent();
1550 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001551}
1552
Dominik Laskowski83b88212018-12-11 13:34:06 -08001553nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001554 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001555 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1556 return 0;
1557 }
1558
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001559 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001560}
1561
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001562void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001563 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001564 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001565 ATRACE_NAME("SF onVsync");
1566
Steven Thomas3cfac282017-02-06 12:29:30 -08001567 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001568 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001569 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001570 return;
1571 }
1572
Dominik Laskowski075d3172018-05-24 15:50:06 -07001573 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001574 return;
1575 }
1576
Dominik Laskowski075d3172018-05-24 15:50:06 -07001577 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001578 // For now, we don't do anything with external display vsyncs.
1579 return;
1580 }
1581
Alec Mourif8e689c2019-05-20 18:32:22 -07001582 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001583 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001584 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001585 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001586 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001587}
1588
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001590 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1591 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592}
1593
Ady Abraham2139f732019-11-13 18:56:40 -08001594bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001595 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001596}
1597
Ady Abraham2139f732019-11-13 18:56:40 -08001598void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1599 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001600 const auto display = getDefaultDisplayDeviceLocked();
1601 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001602 return;
1603 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001604 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001605
Ana Krulec7d1d6832018-12-27 11:10:09 -08001606 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001607 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1608 ALOGV("Skipping config %d as it is not part of allowed configs",
1609 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001610 return;
1611 }
1612
Ady Abraham2139f732019-11-13 18:56:40 -08001613 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001614}
1615
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001616void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001617 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001618 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001619 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001620
Lloyd Piqueba04e622017-12-14 17:11:26 -08001621 // Ignore events that do not have the right sequenceId.
1622 if (sequenceId != getBE().mComposerSequenceId) {
1623 return;
1624 }
1625
Steven Thomasb02664d2017-07-26 18:48:28 -07001626 // Only lock if we're not on the main thread. This function is normally
1627 // called on a hwbinder thread, but for the primary display it's called on
1628 // the main thread with the state lock already held, so don't attempt to
1629 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001630 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001631
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001632 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001633
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001634 if (std::this_thread::get_id() == mMainThreadId) {
1635 // Process all pending hot plug events immediately if we are on the main thread.
1636 processDisplayHotplugEventsLocked();
1637 }
1638
Lloyd Piqueba04e622017-12-14 17:11:26 -08001639 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001640}
1641
Ady Abraham7159f572019-10-11 11:10:18 -07001642void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001643 int32_t sequenceId, hwc2_display_t /*display*/,
1644 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1645 Mutex::Autolock lock(mStateLock);
1646 if (sequenceId != getBE().mComposerSequenceId) {
1647 return;
1648 }
1649 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001650}
1651
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001652void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1653 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1654 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1655}
1656
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001657void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001658 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001659 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001660 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001661 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001662 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001663}
1664
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001665void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001666 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001667
1668 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1669 // display power state.
1670 postMessageAsync(new LambdaMessage(
1671 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1672}
1673
1674void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1675 ATRACE_CALL();
1676
Ady Abraham27c70212019-06-11 10:52:26 -07001677 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1678
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001679 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001680 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1681 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001682 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001683 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001684 }
Mathias Agopian86303202012-07-24 22:46:10 -07001685}
1686
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001687// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001688void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001689 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690 // Clear the drawing state so that the logic inside of
1691 // handleTransactionLocked will fire. It will determine the delta between
1692 // mCurrentState and mDrawingState and re-apply all changes when we make the
1693 // transition.
1694 mDrawingState.displays.clear();
1695 mDisplays.clear();
1696}
1697
Steven Thomas050b2c82017-03-06 11:45:16 -08001698void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001699 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001700 if (!mVrFlinger)
1701 return;
1702 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001703 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001704 return;
1705 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001706
Lloyd Pique441d5042018-10-18 16:49:51 -07001707 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001708 ALOGE("Vr flinger is only supported for remote hardware composer"
1709 " service connections. Ignoring request to transition to vr"
1710 " flinger.");
1711 mVrFlingerRequestsDisplay = false;
1712 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001713 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001714
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001715 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001716
Steven Thomas0123ac62018-07-12 11:32:34 -07001717 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001718 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001719
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001720 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001721
1722 // Clear out all the output layers from the composition engine for all
1723 // displays before destroying the hardware composer interface. This ensures
1724 // any HWC layers are destroyed through that interface before it becomes
1725 // invalid.
1726 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001727 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001728 }
1729
Steven Thomas0123ac62018-07-12 11:32:34 -07001730 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1731 // called below. Clear the reference now so we don't accidentally use it
1732 // later.
1733 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001734
Steven Thomasb02664d2017-07-26 18:48:28 -07001735 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001736 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001738
Steven Thomasb02664d2017-07-26 18:48:28 -07001739 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001740 // Delete the current instance before creating the new one
1741 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1742 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1743 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001744 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001745
Lloyd Pique441d5042018-10-18 16:49:51 -07001746 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001747 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001748
1749 if (vrFlingerRequestsDisplay) {
1750 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001751 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001752
1753 mVisibleRegionsDirty = true;
1754 invalidateHwcGeometry();
1755
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001756 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001757 display = getDefaultDisplayDeviceLocked();
1758 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001759 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001760
Steven Thomasb02664d2017-07-26 18:48:28 -07001761 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001762 const nsecs_t vsyncPeriod = getVsyncPeriod();
1763 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001764
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001765 // The present fences returned from vr_hwc are not an accurate
1766 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001767 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001768
Steven Thomasb02664d2017-07-26 18:48:28 -07001769 // Use phase of 0 since phase is not known.
1770 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001771 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001772 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001773
Ana Krulecc2870422019-01-29 19:00:58 -08001774 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001775
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001776 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001777 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001778}
1779
Ady Abraham11579302019-09-19 12:35:58 -07001780bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1781 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001782 // We are storing the last 2 present fences. If sf's phase offset is to be
1783 // woken up before the actual vsync but targeting the next vsync, we need to check
1784 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001785 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1786 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001787
Ady Abraham11579302019-09-19 12:35:58 -07001788 if (fence == Fence::NO_FENCE) {
1789 return false;
1790 }
1791
1792 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1793 fence->wait(graceTimeMs);
1794 }
1795
1796 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001797}
1798
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001799void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001800 DisplayStatInfo stats;
1801 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001802 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001803 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001804 mExpectedPresentTime.store(
1805 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001806}
1807
Dominik Laskowski22488f62019-03-28 09:53:04 -07001808void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001809 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001810 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001811 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001812 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001813 // calculate the expected present time once and use the cached
1814 // value throughout this frame to make sure all layers are
1815 // seeing this same value.
1816 populateExpectedPresentTime();
1817
Ady Abraham11579302019-09-19 12:35:58 -07001818 // When Backpressure propagation is enabled we want to give a small grace period
1819 // for the present fence to fire instead of just giving up on this frame to handle cases
1820 // where present fence is just about to get signaled.
1821 const int graceTimeForPresentFenceMs =
1822 (mPropagateBackpressure &&
1823 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1824 ? 1
1825 : 0;
1826 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1827 previousFrameMissed(
1828 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001829 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1830 mHadDeviceComposition && frameMissed};
1831 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1832 mHadClientComposition && frameMissed};
1833
Alec Mouricc0fc602019-02-26 21:45:19 -08001834 if (frameMissed) {
1835 mFrameMissedCount++;
1836 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001837 if (mMissedFrameJankCount == 0) {
1838 mMissedFrameJankStart = systemTime();
1839 }
1840 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001841 }
1842
Alec Mouri40189b02019-03-05 15:07:54 -08001843 if (hwcFrameMissed) {
1844 mHwcFrameMissedCount++;
1845 }
1846
1847 if (gpuFrameMissed) {
1848 mGpuFrameMissedCount++;
1849 }
1850
Ady Abrahamadb9a992019-09-19 21:21:55 +00001851 if (frameMissed && mPropagateBackpressure) {
1852 if ((hwcFrameMissed && !gpuFrameMissed) ||
1853 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001854 signalLayerUpdate();
1855 break;
1856 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001857 }
Dan Stoza50182882016-07-08 12:02:20 -07001858
Alec Mouri5f487d42020-02-06 09:26:19 -08001859 // Our jank window is always at least 100ms since we missed a
1860 // frame...
1861 static constexpr nsecs_t kMinJankyDuration =
1862 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1863 // ...but if it's larger than 1s then we missed the trace cutoff.
1864 static constexpr nsecs_t kMaxJankyDuration =
1865 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1866 // If we're in a user build then don't push any atoms
1867 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1868 const auto displayDevice = getDefaultDisplayDeviceLocked();
1869 // Only report jank when the display is on, as displays in DOZE
1870 // power mode may operate at a different frame rate than is
1871 // reported in their config, which causes noticeable (but less
1872 // severe) jank.
1873 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1874 const nsecs_t currentTime = systemTime();
1875 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1876 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1877 ATRACE_NAME("Jank detected");
1878 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1879 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1880 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1881 jankyDurationMillis, mMissedFrameJankCount);
1882 }
1883
1884 // We either reported a jank event or we missed the trace
1885 // window, so clear counters here.
1886 if (jankDuration > kMinJankyDuration) {
1887 mMissedFrameJankCount = 0;
1888 mMissedFrameJankStart = 0;
1889 }
1890 }
1891 }
1892
Steven Thomas050b2c82017-03-06 11:45:16 -08001893 // Now that we're going to make it to the handleMessageTransaction()
1894 // call below it's safe to call updateVrFlinger(), which will
1895 // potentially trigger a display handoff.
1896 updateVrFlinger();
1897
Dan Stoza6b9454d2014-11-07 16:00:59 -08001898 bool refreshNeeded = handleMessageTransaction();
1899 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001900
Ana Krulecc84d09b2019-11-02 23:10:29 +01001901 // Layers need to get updated (in the previous line) before we can use them for
1902 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001903 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1904 // and may eventually call to ~Layer() if it holds the last reference
1905 {
1906 Mutex::Autolock _l(mStateLock);
1907 mScheduler->chooseRefreshRateForContent();
1908 }
1909
Ana Krulecc84d09b2019-11-02 23:10:29 +01001910 if (performSetActiveConfig()) {
1911 break;
1912 }
1913
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001914 updateCursorAsync();
1915 updateInputFlinger();
1916
Dan Stoza58784442014-12-02 16:58:17 -08001917 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001918 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001919 // Signal a refresh if a transaction modified the window state,
1920 // a new buffer was latched, or if HWC has requested a full
1921 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001922 if (mFrameStartTime <= 0) {
1923 // We should only use the time of the first invalidate
1924 // message that signals a refresh as the beginning of the
1925 // frame. Otherwise the real frame time will be
1926 // underestimated.
1927 mFrameStartTime = frameStart;
1928 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001929 signalRefresh();
1930 }
1931 break;
1932 }
1933 case MessageQueue::REFRESH: {
1934 handleMessageRefresh();
1935 break;
1936 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001937 }
1938}
1939
Dan Stoza6b9454d2014-11-07 16:00:59 -08001940bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001941 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001942 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001943
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001944 bool flushedATransaction = flushTransactionQueues();
1945
1946 bool runHandleTransaction = transactionFlags &&
1947 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1948
1949 if (runHandleTransaction) {
1950 handleTransaction(eTransactionMask);
1951 } else {
1952 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001953 }
1954
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001955 if (transactionFlushNeeded()) {
1956 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001957 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001958
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001959 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001960}
1961
Mathias Agopian4fec8732012-06-29 14:12:52 -07001962void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001963 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001964
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001965 mRefreshPending = false;
1966
Lloyd Piqueab039b52019-02-13 14:22:42 -08001967 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001968 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001969 for (const auto& [_, display] : mDisplays) {
1970 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1971 }
1972 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001973 if (auto layerFE = layer->getCompositionEngineLayerFE())
1974 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001975 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001976 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1977 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001978 if (auto layerFE = layer->getCompositionEngineLayerFE())
1979 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001980 }
1981
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001982 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001983 refreshArgs.outputColorSetting = useColorManagement
1984 ? mDisplayColorSetting
1985 : compositionengine::OutputColorSetting::kUnmanaged;
1986 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1987 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001988
1989 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1990 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001991 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001992
1993 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1994 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1995 mDrawingState.colorMatrixChanged = false;
1996 }
1997
1998 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1999
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002000 if (mDebugRegion != 0) {
2001 refreshArgs.devOptFlashDirtyRegionsDelay =
2002 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2003 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002004
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002005 mGeometryInvalid = false;
2006
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002007 // Store the present time just before calling to the composition engine so we could notify
2008 // the scheduler.
2009 const auto presentTime = systemTime();
2010
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002011 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002012 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2013 // Reset the frame start time now that we've recorded this frame.
2014 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002015
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002016 mScheduler->onDisplayRefreshed(presentTime);
2017
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002019 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002020
Lloyd Pique66d68602019-02-13 14:23:31 -08002021 mHadClientComposition =
2022 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2023 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002024 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2025 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002026 });
2027 mHadDeviceComposition =
2028 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2029 auto& displayDevice = tokenDisplayPair.second;
2030 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2031 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002032 mReusedClientComposition =
2033 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2034 auto& displayDevice = tokenDisplayPair.second;
2035 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2036 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002037
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002038 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002039
David Sodman7e4ae112018-02-09 15:02:28 -08002040 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002041 if (mVisibleRegionsDirty) {
2042 mVisibleRegionsDirty = false;
2043 if (mTracingEnabled) {
2044 mTracing.notify("visibleRegionsDirty");
2045 }
2046 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002047
2048 if (mCompositionEngine->needsAnotherUpdate()) {
2049 signalLayerUpdate();
2050 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002051}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002052
David Sodmanfa9b2af2017-12-24 13:28:59 -08002053
2054bool SurfaceFlinger::handleMessageInvalidate() {
2055 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002056 bool refreshNeeded = handlePageFlip();
2057
Vishnu Nair4351ad52019-02-11 14:13:02 -08002058 if (mVisibleRegionsDirty) {
2059 computeLayerBounds();
2060 }
2061
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002062 for (auto& layer : mLayersPendingRefresh) {
2063 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002064 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002065 invalidateLayerStack(layer, visibleReg);
2066 }
2067 mLayersPendingRefresh.clear();
2068 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002069}
2070
Ana Krulece588e312018-09-18 12:32:24 -07002071void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2072 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 // Update queue of past composite+present times and determine the
2074 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002075 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002077 while (!getBE().mCompositePresentTimes.empty()) {
2078 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002079 // Cached values should have been updated before calling this method,
2080 // which helps avoid duplicate syscalls.
2081 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2082 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2083 break;
2084 }
2085 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002086 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002087 }
2088
2089 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002090 while (getBE().mCompositePresentTimes.size() > 16) {
2091 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002092 }
2093
Ana Krulece588e312018-09-18 12:32:24 -07002094 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002095}
2096
Ana Krulece588e312018-09-18 12:32:24 -07002097void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2098 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002099 // Integer division and modulo round toward 0 not -inf, so we need to
2100 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002101 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2102 ? (stats.vsyncPeriod -
2103 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2104 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002105
Ady Abraham9e16a482019-12-03 17:19:41 -08002106 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002107 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002108 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002109 }
2110
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111 // Snap the latency to a value that removes scheduling jitter from the
2112 // composition and present times, which often have >1ms of jitter.
2113 // Reducing jitter is important if an app attempts to extrapolate
2114 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002115 // Snapping also allows an app to precisely calculate
2116 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002117 nsecs_t bias = stats.vsyncPeriod / 2;
2118 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2119 nsecs_t snappedCompositeToPresentLatency =
2120 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002121
David Sodman99974d22017-11-28 12:04:33 -08002122 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002123 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2124 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002125 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002126}
2127
David Sodman2b406362017-12-15 13:33:47 -08002128void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002129{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 ATRACE_CALL();
2131 ALOGV("postComposition");
2132
Brian Andersonf6386862016-10-31 16:34:13 -07002133 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002134 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002135 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002136 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002137 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002139
David Sodman73beded2017-11-15 11:56:06 -08002140 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002141 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002142 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002143 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002144 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2145 ->getRenderSurface()
2146 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002147 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002148 } else {
2149 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2150 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002151
David Sodman73beded2017-11-15 11:56:06 -08002152 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002153 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2154 mPreviousPresentFences[0] = displayDevice
2155 ? getHwComposer().getPresentFence(*displayDevice->getId())
2156 : Fence::NO_FENCE;
2157 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002158 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002159
Ana Krulece588e312018-09-18 12:32:24 -07002160 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002161 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002162
Lloyd Piqueab039b52019-02-13 14:22:42 -08002163 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2164 // be sampled a little later than when we started doing work for this frame,
2165 // but that should be okay since updateCompositorTiming has snapping logic.
2166 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2167 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002168 CompositorTiming compositorTiming;
2169 {
David Sodman99974d22017-11-28 12:04:33 -08002170 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2171 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002172 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173
Edgar Arriaga844fa672020-01-16 14:21:42 -08002174 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002175 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2176 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002177 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002178 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002179 }
Robert Carr2047fae2016-11-28 14:09:09 -08002180 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002181
Ady Abraham92fa2f42020-02-11 15:33:56 -08002182 if (displayDevice && displayDevice->isPrimary() &&
2183 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002184 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002185 }
2186
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002187 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002188 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2189 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002190 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002191 }
2192 }
2193
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002194 if (mAnimCompositionPending) {
2195 mAnimCompositionPending = false;
2196
Brian Anderson4e606e32017-03-16 15:34:57 -07002197 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002198 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002199 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002200 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002201 // The HWC doesn't support present fences, so use the refresh
2202 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002203 const nsecs_t presentTime =
2204 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002205 mAnimFrameTracker.setActualPresentTime(presentTime);
2206 }
2207 mAnimFrameTracker.advanceFrame();
2208 }
Dan Stozab90cf072015-03-05 11:05:59 -08002209
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002210 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002211 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002212 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002213 }
2214
Vishnu Nair9b079a22020-01-21 14:36:08 -08002215 if (mReusedClientComposition) {
2216 mTimeStats->incrementClientCompositionReusedFrames();
2217 }
2218
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002219 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002220
Alec Mouri717bcb62020-02-10 17:07:19 -08002221 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2222 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2223 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2224
Lloyd Pique32cbe282018-10-19 13:09:22 -07002225 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2226 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002227 return;
2228 }
2229
2230 nsecs_t currentTime = systemTime();
2231 if (mHasPoweredOff) {
2232 mHasPoweredOff = false;
2233 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002234 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002235 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002236 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2237 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002238 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002239 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002240 }
David Sodman4a36e932017-11-07 14:29:47 -08002241 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002242 }
David Sodman4a36e932017-11-07 14:29:47 -08002243 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002244
2245 {
2246 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002247 if (mTexturePool.size() < mTexturePoolSize) {
2248 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002249 const size_t offset = mTexturePool.size();
2250 mTexturePool.resize(mTexturePoolSize);
2251 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2252 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002253 } else if (mTexturePool.size() > mTexturePoolSize) {
2254 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2255 const size_t offset = mTexturePoolSize;
2256 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2257 mTexturePool.resize(mTexturePoolSize);
2258 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002259 }
2260 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002261
Ady Abrahambe0f9482019-04-24 15:41:53 -07002262 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002263 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002264
Kevin DuBois413287f2019-02-25 08:46:47 -08002265 if (mLumaSampling && mRegionSamplingThread) {
2266 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002267 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002268
2269 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2270 // side-effect of getTotalSize(), so we check that again here
2271 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002272 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002273 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2274 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002275}
2276
Vishnu Nair4351ad52019-02-11 14:13:02 -08002277void SurfaceFlinger::computeLayerBounds() {
2278 for (const auto& pair : mDisplays) {
2279 const auto& displayDevice = pair.second;
2280 const auto display = displayDevice->getCompositionDisplay();
2281 for (const auto& layer : mDrawingState.layersSortedByZ) {
2282 // only consider the layers on the given layer stack
2283 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002284 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002285 }
2286
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002287 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2288 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002289 }
2290 }
2291}
2292
David Sodmanfa9b2af2017-12-24 13:28:59 -08002293void SurfaceFlinger::postFrame()
2294{
2295 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 const auto display = getDefaultDisplayDeviceLocked();
2297 if (display && getHwComposer().isConnected(*display->getId())) {
2298 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002299 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2300 logFrameStats();
2301 }
2302 }
2303}
2304
Mathias Agopian87baae12012-07-31 12:38:26 -07002305void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306{
Mathias Agopian841cde52012-03-01 15:44:37 -08002307 ATRACE_CALL();
2308
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002309 // here we keep a copy of the drawing state (that is the state that's
2310 // going to be overwritten by handleTransactionLocked()) outside of
2311 // mStateLock so that the side-effects of the State assignment
2312 // don't happen with mStateLock held (which can cause deadlocks).
2313 State drawingState(mDrawingState);
2314
Mathias Agopianca4d3602011-05-19 15:38:14 -07002315 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002316 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317
Mathias Agopianca4d3602011-05-19 15:38:14 -07002318 // Here we're guaranteed that some transaction flags are set
2319 // so we can call handleTransactionLocked() unconditionally.
2320 // We call getTransactionFlags(), which will also clear the flags,
2321 // with mStateLock held to guarantee that mCurrentState won't change
2322 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002323
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002324 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002325 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002326 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002327
Mathias Agopianca4d3602011-05-19 15:38:14 -07002328 mDebugInTransaction = 0;
2329 invalidateHwcGeometry();
2330 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002331}
2332
Lloyd Piqueba04e622017-12-14 17:11:26 -08002333void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2334 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002335 const std::optional<DisplayIdentificationInfo> info =
2336 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002337
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339 continue;
2340 }
2341
Dominik Laskowski55c85402020-01-21 16:25:47 -08002342 const DisplayId displayId = info->id;
2343 const auto it = mPhysicalDisplayTokens.find(displayId);
2344
Lloyd Piqueba04e622017-12-14 17:11:26 -08002345 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002346 if (it == mPhysicalDisplayTokens.end()) {
2347 ALOGV("Creating display %s", to_string(displayId).c_str());
2348
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002349 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002350 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002351 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002352
Dominik Laskowski075d3172018-05-24 15:50:06 -07002353 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002354 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002355 state.isSecure = true; // All physical displays are currently considered secure.
2356 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002357
2358 sp<IBinder> token = new BBinder();
2359 mCurrentState.displays.add(token, state);
2360 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2361
Dominik Laskowski075d3172018-05-24 15:50:06 -07002362 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002363 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002364 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002365 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366
Dominik Laskowski55c85402020-01-21 16:25:47 -08002367 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 if (index >= 0) {
2369 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2370 mInterceptor->saveDisplayDeletion(state.sequenceId);
2371 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002372 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002373 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002374 }
2375
2376 processDisplayChangesLocked();
2377 }
2378
2379 mPendingHotplugEvents.clear();
2380}
2381
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002382void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002383 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2384 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002385}
2386
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002388 const wp<IBinder>& displayToken,
2389 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002390 const DisplayDeviceState& state,
2391 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002393 auto displayId = compositionDisplay->getDisplayId();
2394 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002395 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002397 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002398 creationArgs.hasWideColorGamut = false;
2399 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002400
Dominik Laskowski55c85402020-01-21 16:25:47 -08002401 if (const auto& physical = state.physical) {
2402 creationArgs.connectionType = physical->type;
2403 }
2404
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002405 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 creationArgs.isPrimary = isInternalDisplay;
2407
2408 if (useColorManagement && displayId) {
2409 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002411 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002412 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002414
Dominik Laskowski7e045462018-05-30 13:02:02 -07002415 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002416 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002417 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002418 }
tangrobin6753a022018-08-10 10:58:54 +08002419 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 if (displayId) {
2422 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002423 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002425 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426
Lloyd Pique90c115d2018-09-18 21:39:42 -07002427 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002429 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430
Lloyd Pique99d3da52018-01-22 17:48:03 -08002431 // Make sure that composition can never be stalled by a virtual display
2432 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002433 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002434 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002435 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2436 }
2437
Dominik Laskowski718f9602019-11-09 20:01:35 -08002438 creationArgs.physicalOrientation =
2439 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002440
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002442 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443
Lloyd Pique9370a482019-10-03 17:58:30 -07002444 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445
2446 if (maxFrameBufferAcquiredBuffers >= 3) {
2447 nativeWindowSurface->preallocateBuffers();
2448 }
2449
2450 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002451 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002452 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002454 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002456 display->getCompositionDisplay()->setColorProfile(
2457 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2458 RenderIntent::COLORIMETRIC,
2459 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 if (!state.isVirtual()) {
2461 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002462 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2463 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002464 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002465
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 display->setLayerStack(state.layerStack);
2467 display->setProjection(state.orientation, state.viewport, state.frame);
2468 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002470 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471}
2472
Marin Shalamanovae685592020-02-12 17:12:22 +01002473void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2474 const DisplayDeviceState& state) {
2475 int width = 0;
2476 int height = 0;
2477 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2478 if (state.physical) {
2479 const auto& activeConfig =
2480 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2481 width = activeConfig->getWidth();
2482 height = activeConfig->getHeight();
2483 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2484 } else if (state.surface != nullptr) {
2485 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2486 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2487 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2488 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2489 int intPixelFormat;
2490 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2491 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2492 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2493 } else {
2494 // Virtual displays without a surface are dormant:
2495 // they have external state (layer stack, projection,
2496 // etc.) but no internal state (i.e. a DisplayDevice).
2497 return;
2498 }
2499
2500 compositionengine::DisplayCreationArgsBuilder builder;
2501 if (const auto& physical = state.physical) {
2502 builder.setPhysical({physical->id, physical->type});
2503 }
2504 builder.setPixels(ui::Size(width, height));
2505 builder.setPixelFormat(pixelFormat);
2506 builder.setIsSecure(state.isSecure);
2507 builder.setLayerStackId(state.layerStack);
2508 builder.setPowerAdvisor(&mPowerAdvisor);
2509 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2510 builder.setName(state.displayName);
2511 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2512
2513 sp<compositionengine::DisplaySurface> displaySurface;
2514 sp<IGraphicBufferProducer> producer;
2515 sp<IGraphicBufferProducer> bqProducer;
2516 sp<IGraphicBufferConsumer> bqConsumer;
2517 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2518
2519 std::optional<DisplayId> displayId = compositionDisplay->getId();
2520
2521 if (state.isVirtual()) {
2522 sp<VirtualDisplaySurface> vds =
2523 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2524 bqConsumer, state.displayName);
2525
2526 displaySurface = vds;
2527 producer = vds;
2528 } else {
2529 ALOGE_IF(state.surface != nullptr,
2530 "adding a supported display, but rendering "
2531 "surface is provided (%p), ignoring it",
2532 state.surface.get());
2533
2534 LOG_ALWAYS_FATAL_IF(!displayId);
2535 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2536 maxGraphicsWidth, maxGraphicsHeight);
2537 producer = bqProducer;
2538 }
2539
2540 if (displaySurface != nullptr) {
2541 mDisplays.emplace(displayToken,
2542 setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2543 displaySurface, producer));
2544 if (!state.isVirtual()) {
2545 LOG_ALWAYS_FATAL_IF(!displayId);
2546 dispatchDisplayHotplugEvent(displayId->value, true);
2547 }
2548
2549 const auto displayDevice = mDisplays[displayToken];
2550 if (displayDevice->isPrimary()) {
2551 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2552 displayDevice->getHeight());
2553 }
2554 }
2555}
2556
2557void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2558 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2559 // Save display ID before disconnecting.
2560 const auto displayId = display->getId();
2561 display->disconnect();
2562
2563 if (!display->isVirtual()) {
2564 LOG_ALWAYS_FATAL_IF(!displayId);
2565 dispatchDisplayHotplugEvent(displayId->value, false);
2566 }
2567 }
2568
2569 mDisplays.erase(displayToken);
2570}
2571
2572void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2573 const DisplayDeviceState& currentState,
2574 const DisplayDeviceState& drawingState) {
2575 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2576 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
2577 if (currentBinder != drawingBinder) {
2578 // changing the surface is like destroying and recreating the DisplayDevice
2579 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2580 display->disconnect();
2581 }
2582 mDisplays.erase(displayToken);
2583 processDisplayAdded(displayToken, currentState);
2584 return;
2585 }
2586
2587 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2588 if (currentState.layerStack != drawingState.layerStack) {
2589 display->setLayerStack(currentState.layerStack);
2590 }
2591 if ((currentState.orientation != drawingState.orientation) ||
2592 (currentState.viewport != drawingState.viewport) ||
2593 (currentState.frame != drawingState.frame)) {
2594 display->setProjection(currentState.orientation, currentState.viewport,
2595 currentState.frame);
2596 }
2597 if (currentState.width != drawingState.width ||
2598 currentState.height != drawingState.height) {
2599 display->setDisplaySize(currentState.width, currentState.height);
2600 if (display->isPrimary()) {
2601 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2602 }
2603 }
2604 }
2605}
2606
Lloyd Pique347200f2017-12-14 17:00:15 -08002607void SurfaceFlinger::processDisplayChangesLocked() {
2608 // here we take advantage of Vector's copy-on-write semantics to
2609 // improve performance by skipping the transaction entirely when
2610 // know that the lists are identical
2611 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2612 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2613 if (!curr.isIdenticalTo(draw)) {
2614 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002615
2616 // find the displays that were removed
2617 // (ie: in drawing state but not in current state)
2618 // also handle displays that changed
2619 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002620 for (size_t i = 0; i < draw.size(); i++) {
2621 const wp<IBinder>& displayToken = draw.keyAt(i);
2622 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002623 if (j < 0) {
2624 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002625 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002626 } else {
2627 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002628 const DisplayDeviceState& currentState = curr[j];
2629 const DisplayDeviceState& drawingState = draw[i];
2630 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002631 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002632 }
2633
2634 // find displays that were added
2635 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002636 for (size_t i = 0; i < curr.size(); i++) {
2637 const wp<IBinder>& displayToken = curr.keyAt(i);
2638 if (draw.indexOfKey(displayToken) < 0) {
2639 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002640 }
2641 }
2642 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002643
2644 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002645}
2646
Mathias Agopian87baae12012-07-31 12:38:26 -07002647void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002648{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002649 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2650
Dan Stoza7dde5992015-05-22 09:51:44 -07002651 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002652 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002653 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002654 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 /*
2657 * Traversal of the children
2658 * (perform the transaction for each of them if needed)
2659 */
2660
Marissa Wall06255332019-03-27 13:48:27 -07002661 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002662 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002664 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
2666 const uint32_t flags = layer->doTransaction(0);
2667 if (flags & Layer::eVisibleRegion)
2668 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002669
2670 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002671 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002672 }
Robert Carr2047fae2016-11-28 14:09:09 -08002673 });
Marissa Wall06255332019-03-27 13:48:27 -07002674 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 }
2676
2677 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002678 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679 */
2680
Mathias Agopiane57f2922012-08-09 16:29:12 -07002681 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002683 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002686 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002687 // The transform hint might have changed for some layers
2688 // (either because a display has changed, or because a layer
2689 // as changed).
2690 //
2691 // Walk through all the layers in currentLayers,
2692 // and update their transform hint.
2693 //
2694 // If a layer is visible only on a single display, then that
2695 // display is used to calculate the hint, otherwise we use the
2696 // default display.
2697 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002698 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002699 // the hint is set before we acquire a buffer from the surface texture.
2700 //
2701 // NOTE: layer transactions have taken place already, so we use their
2702 // drawing state. However, SurfaceFlinger's own transaction has not
2703 // happened yet, so we must use the current state layer list
2704 // (soon to become the drawing state list).
2705 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002707 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002708 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002709 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002710 // NOTE: we rely on the fact that layers are sorted by
2711 // layerStack first (so we don't have to traverse the list
2712 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002714 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002715 currentlayerStack = layerStack;
2716 // figure out if this layerstack is mirrored
2717 // (more than one display) if so, pick the default display,
2718 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002719 hintDisplay = nullptr;
2720 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002721 if (display->getCompositionDisplay()
2722 ->belongsInOutput(layer->getLayerStack(),
2723 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002724 if (hintDisplay) {
2725 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002726 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002729 }
2730 }
2731 }
2732 }
Chet Haase91d25932013-04-11 15:24:55 -07002733
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002734 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002735 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2736 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002737
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002738 // could be null when this layer is using a layerStack
2739 // that is not visible on any display. Also can occur at
2740 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002741 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002742 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002743
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002744 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002745 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 if (hintDisplay) {
2747 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002748 }
Robert Carr2047fae2016-11-28 14:09:09 -08002749
2750 first = false;
2751 });
Mathias Agopian84300952012-11-21 16:02:13 -08002752 }
2753
2754
Mathias Agopian3559b072012-08-15 13:46:03 -07002755 /*
2756 * Perform our own transaction if needed
2757 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758
2759 if (mLayersAdded) {
2760 mLayersAdded = false;
2761 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002762 mVisibleRegionsDirty = true;
2763 }
2764
2765 // some layers might have been removed, so
2766 // we need to update the regions they're exposing.
2767 if (mLayersRemoved) {
2768 mLayersRemoved = false;
2769 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002770 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002771 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002772 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002773 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002774 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002775 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002776 }
Robert Carr2047fae2016-11-28 14:09:09 -08002777 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 }
2779
Vishnu Nairec0ab382019-02-13 15:32:56 -08002780 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002782}
2783
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002784void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002785 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002786 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002787 return;
2788 }
2789
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002790 if (mVisibleRegionsDirty || mInputInfoChanged) {
2791 mInputInfoChanged = false;
2792 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002793 } else if (mInputWindowCommands.syncInputWindows) {
2794 // If the caller requested to sync input windows, but there are no
2795 // changes to input windows, notify immediately.
2796 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002797 }
2798
Arthur Hung6cbb9752019-09-05 16:38:18 +08002799 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002800}
2801
2802void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002803 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002804
Robert Carra1257842020-01-31 13:48:28 -08002805 // We use a simple caching algorithm here. mInputDirty begins as true,
2806 // after we call setInputWindows we set it to false, so
2807 // in the future we wont call it again.. We set input dirty to true again
2808 // when any layer that hasInput() has a transaction performed on it
2809 // or when any parent or relative parent of such a layer has a transaction
2810 // performed on it. Not all of these transactions will really result in
2811 // input changes but all input changes will spring from these transactions
2812 // so the cache is safe but not optimal. It seems like it might be annoyingly
2813 // costly to cache and comapre the actual InputWindowHandle vector though.
2814 if (!mInputDirty) {
2815 return;
2816 }
2817
Robert Carr720e5062018-07-30 17:45:14 -07002818 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2819 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002820 // When calculating the screen bounds we ignore the transparent region since it may
2821 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002822 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002823 }
2824 });
chaviw291d88a2019-02-14 10:33:58 -08002825
2826 mInputFlinger->setInputWindows(inputHandles,
2827 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2828 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002829
2830 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002831}
2832
Vishnu Nairec0ab382019-02-13 15:32:56 -08002833void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002834 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002835 mPendingInputWindowCommands.clear();
2836}
2837
Riley Andrews03414a12014-07-01 14:22:59 -07002838void SurfaceFlinger::updateCursorAsync()
2839{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002840 compositionengine::CompositionRefreshArgs refreshArgs;
2841 for (const auto& [_, display] : mDisplays) {
2842 if (display->getId()) {
2843 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002844 }
2845 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002846
2847 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002848}
2849
Ady Abraham2139f732019-11-13 18:56:40 -08002850void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002851 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2852 // If this is called from the main thread mStateLock must be locked before
2853 // Currently the only way to call this function from the main thread is from
2854 // Sheduler::chooseRefreshRateForContent
2855
2856 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002857 changeRefreshRateLocked(refreshRate, event);
2858}
2859
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002860void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2861 if (mScheduler) {
2862 // In practice it's not allowed to hotplug in/out the primary display once it's been
2863 // connected during startup, but some tests do it, so just warn and return.
2864 ALOGW("Can't re-init scheduler");
2865 return;
2866 }
2867
Ady Abraham2139f732019-11-13 18:56:40 -08002868 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002869 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002870 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002871 primaryDisplayId),
2872 currentConfig);
2873 mRefreshRateStats =
2874 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2875 currentConfig, HWC_POWER_MODE_OFF);
2876 mRefreshRateStats->setConfigMode(currentConfig);
2877
Ady Abraham9e16a482019-12-03 17:19:41 -08002878 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2879
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002880 // start the EventThread
2881 mScheduler =
2882 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002883 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002884 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002885 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002886 impl::EventThread::InterceptVSyncsCallback());
2887 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002888 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002889 [this](nsecs_t timestamp) {
2890 mInterceptor->saveVSyncEvent(timestamp);
2891 });
2892
2893 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2894 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002895 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002896
2897 mRegionSamplingThread =
2898 new RegionSamplingThread(*this, *mScheduler,
2899 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002900 // Dispatch a config change request for the primary display on scheduler
2901 // initialization, so that the EventThreads always contain a reference to a
2902 // prior configuration.
2903 //
2904 // This is a bit hacky, but this avoids a back-pointer into the main SF
2905 // classes from EventThread, and there should be no run-time binder cost
2906 // anyway since there are no connected apps at this point.
2907 const nsecs_t vsyncPeriod =
2908 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2909 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2910 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002911}
2912
Mathias Agopian4fec8732012-06-29 14:12:52 -07002913void SurfaceFlinger::commitTransaction()
2914{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002915 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002916
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002917 mTransactionPending = false;
2918 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002919 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920}
2921
Lloyd Pique58e24a32019-08-01 15:50:14 -07002922void SurfaceFlinger::commitTransactionLocked() {
2923 if (!mLayersPendingRemoval.isEmpty()) {
2924 // Notify removed layers now that they can't be drawn from
2925 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002926 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002927
2928 // Ensure any buffers set to display on any children are released.
2929 if (l->isRemovedFromCurrentState()) {
2930 l->latchAndReleaseBuffer();
2931 }
2932
2933 // If the layer has been removed and has no parent, then it will not be reachable
2934 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2935 // ensure we can copy its current to drawing state.
2936 if (!l->getParent()) {
2937 mOffscreenLayers.emplace(l.get());
2938 }
2939 }
2940 mLayersPendingRemoval.clear();
2941 }
2942
2943 // If this transaction is part of a window animation then the next frame
2944 // we composite should be considered an animation as well.
2945 mAnimCompositionPending = mAnimTransactionPending;
2946
2947 mDrawingState = mCurrentState;
2948 // clear the "changed" flags in current state
2949 mCurrentState.colorMatrixChanged = false;
2950
Edgar Arriaga844fa672020-01-16 14:21:42 -08002951 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002952 layer->commitChildList();
2953
2954 // If the layer can be reached when traversing mDrawingState, then the layer is no
2955 // longer offscreen. Remove the layer from the offscreenLayer set.
2956 if (mOffscreenLayers.count(layer)) {
2957 mOffscreenLayers.erase(layer);
2958 }
2959 });
2960
2961 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002962 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002963}
2964
Nataniel Borges2b796da2019-02-15 13:32:18 -08002965void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2966 if (mTracingEnabledChanged) {
2967 mTracingEnabled = mTracing.isEnabled();
2968 mTracingEnabledChanged = false;
2969 }
2970
2971 // Synchronize with Tracing thread
2972 std::unique_lock<std::mutex> lock;
2973 if (mTracingEnabled) {
2974 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2975 }
2976
2977 lockedOperation();
2978
2979 // Synchronize with Tracing thread
2980 if (mTracingEnabled) {
2981 lock.unlock();
2982 }
2983}
2984
chaviw74d90ad2019-04-26 14:45:26 -07002985void SurfaceFlinger::commitOffscreenLayers() {
2986 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002987 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002988 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2989 if (!trFlags) return;
2990
2991 layer->doTransaction(0);
2992 layer->commitChildList();
2993 });
2994 }
2995}
2996
Chia-I Wuab0c3192017-08-01 11:29:00 -07002997void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002998 for (const auto& [token, displayDevice] : mDisplays) {
2999 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003000 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003001 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003002 }
3003 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003004}
3005
Dan Stoza6b9454d2014-11-07 16:00:59 -08003006bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007{
Ady Abraham09bd3922019-04-08 10:44:56 -07003008 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003009 ALOGV("handlePageFlip");
3010
Brian Andersond6927fb2016-07-23 23:37:30 -07003011 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003014 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003015 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003016
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003017 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3018
Eric Penner51c59cd2014-07-28 19:51:58 -07003019 // Store the set of layers that need updates. This set must not change as
3020 // buffers are being latched, as this could result in a deadlock.
3021 // Example: Two producers share the same command stream and:
3022 // 1.) Layer 0 is latched
3023 // 2.) Layer 0 gets a new frame
3024 // 2.) Layer 1 gets a new frame
3025 // 3.) Layer 1 is latched.
3026 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3027 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003028 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003029 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003030 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003031 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003032 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003033 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003034 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003035 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003036 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003037 } else {
3038 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003039 }
Robert Carr2047fae2016-11-28 14:09:09 -08003040 });
3041
chaviw49a108c2019-08-12 11:23:06 -07003042 // The client can continue submitting buffers for offscreen layers, but they will not
3043 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3044 // layers to ensure dequeueBuffer doesn't block indefinitely.
3045 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003046 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003047 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3048 }
3049
Lloyd Piquef2c79392018-12-20 16:23:33 -08003050 if (!mLayersWithQueuedFrames.empty()) {
3051 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3052 // writes to Layer current state. See also b/119481871
3053 Mutex::Autolock lock(mStateLock);
3054
3055 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003056 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003057 mLayersPendingRefresh.push_back(layer);
3058 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003059 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003060 if (layer->isBufferLatched()) {
3061 newDataLatched = true;
3062 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003063 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003064 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003065
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003066 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003067
3068 // If we will need to wake up at some time in the future to deal with a
3069 // queued frame that shouldn't be displayed during this vsync period, wake
3070 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003071 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003072 signalLayerUpdate();
3073 }
3074
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003075 // enter boot animation on first buffer latch
3076 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3077 ALOGI("Enter boot animation");
3078 mBootStage = BootStage::BOOTANIMATION;
3079 }
3080
Edgar Arriaga844fa672020-01-16 14:21:42 -08003081 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003082
Dan Stoza6b9454d2014-11-07 16:00:59 -08003083 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003084 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003085}
3086
Mathias Agopianad456f92011-01-13 17:53:01 -08003087void SurfaceFlinger::invalidateHwcGeometry()
3088{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003089 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003090}
3091
Robert Carrc0df3122019-04-11 13:18:21 -07003092status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3093 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3094 const sp<IBinder>& parentHandle,
3095 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003096 // add this layer to the current state list
3097 {
3098 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003099 sp<Layer> parent;
3100 if (parentHandle != nullptr) {
3101 parent = fromHandle(parentHandle);
3102 if (parent == nullptr) {
3103 return NAME_NOT_FOUND;
3104 }
3105 } else {
3106 parent = parentLayer;
3107 }
3108
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003109 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003110 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003111 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003112 return NO_MEMORY;
3113 }
Robert Carrc0df3122019-04-11 13:18:21 -07003114
3115 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3116
Robert Carrb89ea9d2018-12-10 13:01:14 -08003117 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003118 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003119 } else if (parent == nullptr) {
3120 lbc->onRemovedFromCurrentState();
3121 } else if (parent->isRemovedFromCurrentState()) {
3122 parent->addChild(lbc);
3123 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003124 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 parent->addChild(lbc);
3126 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003127
Yiwei Zhang243b3782018-05-15 17:40:04 -07003128 if (gbc != nullptr) {
3129 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3130 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3131 mMaxGraphicBufferProducerListSize,
3132 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3133 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003134 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003135 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3136 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3137 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3138 mNumLayers.load());
3139 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003140 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003141 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003142 }
3143
Mathias Agopian96f08192010-06-02 23:28:45 -07003144 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003145 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003146
Dan Stoza7d89d062015-04-30 13:29:25 -07003147 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003148}
3149
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003150uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003151 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003152}
3153
Mathias Agopian3f844832013-08-07 21:24:32 -07003154uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003155 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156}
3157
Mathias Agopian3f844832013-08-07 21:24:32 -07003158uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003159 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003160}
3161
3162uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003163 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003164 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003165 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003167 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
3169 return old;
3170}
3171
Marissa Wall713b63f2018-10-17 15:42:43 -07003172bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003173 // to prevent onHandleDestroyed from being called while the lock is held,
3174 // we must keep a copy of the transactions (specifically the composer
3175 // states) around outside the scope of the lock
3176 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003177 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003178 {
3179 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003180
Valerie Haufce31b82019-04-30 16:41:14 -07003181 auto it = mTransactionQueues.begin();
3182 while (it != mTransactionQueues.end()) {
3183 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003184
Valerie Haufce31b82019-04-30 16:41:14 -07003185 while (!transactionQueue.empty()) {
3186 const auto& transaction = transactionQueue.front();
3187 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003188 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003189 transaction.states)) {
3190 setTransactionFlags(eTransactionFlushNeeded);
3191 break;
3192 }
3193 transactions.push_back(transaction);
3194 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3195 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003196 transaction.buffer, transaction.postTime,
3197 transaction.privileged, transaction.hasListenerCallbacks,
3198 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003199 transactionQueue.pop();
3200 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003201 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003202
Valerie Haufce31b82019-04-30 16:41:14 -07003203 if (transactionQueue.empty()) {
3204 it = mTransactionQueues.erase(it);
3205 mTransactionCV.broadcast();
3206 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003207 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003208 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003209 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003210 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003211 return flushedATransaction;
3212}
3213
3214bool SurfaceFlinger::transactionFlushNeeded() {
3215 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003216}
3217
chaviwca27f252018-02-06 16:46:39 -08003218
Marissa Wall17b4e452018-12-26 16:32:34 -08003219bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003220 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003221 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003222 if (!useCachedExpectedPresentTime)
3223 populateExpectedPresentTime();
3224
3225 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003226 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3227 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3228 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3229 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3230 return false;
3231 }
3232
Marissa Wall713b63f2018-10-17 15:42:43 -07003233 for (const ComposerState& state : states) {
3234 const layer_state_t& s = state.state;
3235 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3236 continue;
3237 }
3238 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003239 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003240 }
3241 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003242 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003243}
3244
Valerie Hau9dab9732019-08-20 09:29:25 -07003245void SurfaceFlinger::setTransactionState(
3246 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3247 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3248 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3249 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003250 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003251
Valerie Haubc6ddb12019-03-08 11:10:15 -08003252 const int64_t postTime = systemTime();
3253
Robert Carr14167e02019-02-13 13:50:55 -08003254 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3255
Mathias Agopian698c0872011-06-28 19:09:31 -07003256 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003257
Marissa Wall713b63f2018-10-17 15:42:43 -07003258 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003259 auto itr = mTransactionQueues.find(applyToken);
3260 // if this is an animation frame, wait until prior animation frame has
3261 // been applied by SF
3262 if (flags & eAnimation) {
3263 while (itr != mTransactionQueues.end()) {
3264 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3265 if (CC_UNLIKELY(err != NO_ERROR)) {
3266 ALOGW_IF(err == TIMED_OUT,
3267 "setTransactionState timed out "
3268 "waiting for animation frame to apply");
3269 break;
3270 }
3271 itr = mTransactionQueues.find(applyToken);
3272 }
3273 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003274
3275 // Expected present time is computed and cached on invalidate, so it may be stale.
3276 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3277 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003278 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003279 uncacheBuffer, postTime, privileged,
3280 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003281 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003282 return;
3283 }
3284
Valerie Haubc6ddb12019-03-08 11:10:15 -08003285 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003286 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3287 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003288}
3289
Valerie Hau9dab9732019-08-20 09:29:25 -07003290void SurfaceFlinger::applyTransactionState(
3291 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3292 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3293 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3294 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3295 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003296 uint32_t transactionFlags = 0;
3297
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003298 if (flags & eAnimation) {
3299 // For window updates that are part of an animation we must wait for
3300 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003301 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003302 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003303 if (CC_UNLIKELY(err != NO_ERROR)) {
3304 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003305 // caller after a few seconds.
3306 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3307 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003308 mAnimTransactionPending = false;
3309 break;
3310 }
3311 }
3312 }
3313
chaviwca27f252018-02-06 16:46:39 -08003314 for (const DisplayState& display : displays) {
3315 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003316 }
3317
Valerie Hau9dab9732019-08-20 09:29:25 -07003318 // start and end registration for listeners w/ no surface so they can get their callback. Note
3319 // that listeners with SurfaceControls will start registration during setClientStateLocked
3320 // below.
3321 for (const auto& listener : listenerCallbacks) {
3322 mTransactionCompletedThread.startRegistration(listener);
3323 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003324 }
3325
Valerie Hau9dab9732019-08-20 09:29:25 -07003326 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003327 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003328 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003329 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3330 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003331 }
3332
Valerie Hau9dab9732019-08-20 09:29:25 -07003333 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003334 mTransactionCompletedThread.endRegistration(listenerCallback);
3335 }
3336
Marissa Walle2ffb422018-10-12 11:33:52 -07003337 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003338 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003339 mTransactionCompletedThread.sendCallbacks();
3340 }
3341 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003342
chaviw273171b2018-12-26 11:46:30 -08003343 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3344
Marissa Wall947d34e2019-03-29 14:03:53 -07003345 if (uncacheBuffer.isValid()) {
3346 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003347 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003348 }
3349
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003350 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3351 // anyway. This can be used as a flush mechanism for previous async transactions.
3352 // Empty animation transaction can be used to simulate back-pressure, so also force a
3353 // transaction for empty animation transactions.
3354 if (transactionFlags == 0 &&
3355 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003356 transactionFlags = eTransactionNeeded;
3357 }
3358
Marissa Wall06255332019-03-27 13:48:27 -07003359 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3360 // so we don't have to wake up again next frame to preform an uneeded traversal.
3361 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3362 transactionFlags = transactionFlags & (~eTraversalNeeded);
3363 mTraversalNeededMainThread = true;
3364 }
3365
Mathias Agopian386aa982011-11-07 21:58:03 -08003366 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003367 if (mInterceptor->isEnabled()) {
3368 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003369 }
Irvel468051e2016-06-13 16:44:44 -07003370
Mathias Agopian386aa982011-11-07 21:58:03 -08003371 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003372 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3373 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003374 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003375
3376 // if this is a synchronous transaction, wait for it to take effect
3377 // before returning.
3378 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003379 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003380 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003381 if (flags & eAnimation) {
3382 mAnimTransactionPending = true;
3383 }
chaviw4fe36852019-04-15 16:25:49 -07003384 if (mPendingInputWindowCommands.syncInputWindows) {
3385 mPendingSyncInputWindows = true;
3386 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003387
3388 // applyTransactionState can be called by either the main SF thread or by
3389 // another process through setTransactionState. While a given process may wish
3390 // to wait on synchronous transactions, the main SF thread should never
3391 // be blocked. Therefore, we only wait if isMainThread is false.
3392 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003393 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3394 if (CC_UNLIKELY(err != NO_ERROR)) {
3395 // just in case something goes wrong in SF, return to the
3396 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003397 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3398 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003399 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003400 break;
3401 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003402 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403 }
3404}
3405
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003406uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3407 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3408 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003409
Mathias Agopiane57f2922012-08-09 16:29:12 -07003410 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003411 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3412
3413 const uint32_t what = s.what;
3414 if (what & DisplayState::eSurfaceChanged) {
3415 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3416 state.surface = s.surface;
3417 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003418 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003419 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003420 if (what & DisplayState::eLayerStackChanged) {
3421 if (state.layerStack != s.layerStack) {
3422 state.layerStack = s.layerStack;
3423 flags |= eDisplayTransactionNeeded;
3424 }
3425 }
3426 if (what & DisplayState::eDisplayProjectionChanged) {
3427 if (state.orientation != s.orientation) {
3428 state.orientation = s.orientation;
3429 flags |= eDisplayTransactionNeeded;
3430 }
3431 if (state.frame != s.frame) {
3432 state.frame = s.frame;
3433 flags |= eDisplayTransactionNeeded;
3434 }
3435 if (state.viewport != s.viewport) {
3436 state.viewport = s.viewport;
3437 flags |= eDisplayTransactionNeeded;
3438 }
3439 }
3440 if (what & DisplayState::eDisplaySizeChanged) {
3441 if (state.width != s.width) {
3442 state.width = s.width;
3443 flags |= eDisplayTransactionNeeded;
3444 }
3445 if (state.height != s.height) {
3446 state.height = s.height;
3447 flags |= eDisplayTransactionNeeded;
3448 }
3449 }
3450
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 return flags;
3452}
3453
Robert Carr14167e02019-02-13 13:50:55 -08003454bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003455 IPCThreadState* ipc = IPCThreadState::self();
3456 const int pid = ipc->getCallingPid();
3457 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003458 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003459 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003460 return false;
3461 }
3462 return true;
3463}
3464
Marissa Wall3dad52d2019-03-22 14:03:19 -07003465uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003466 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3467 bool privileged,
3468 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003469 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003470
Valerie Hau9dab9732019-08-20 09:29:25 -07003471 for (auto& listener : s.listeners) {
3472 // note that startRegistration will not re-register if the listener has
3473 // already be registered for a prior surface control
3474 mTransactionCompletedThread.startRegistration(listener);
3475 listenerCallbacks.insert(listener);
3476 }
3477
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003478 sp<Layer> layer = nullptr;
3479 if (s.surface) {
3480 layer = fromHandle(s.surface);
3481 } else {
3482 // The client may provide us a null handle. Treat it as if the layer was removed.
3483 ALOGW("Attempt to set client state with a null layer handle");
3484 }
chaviw8b3871a2017-11-01 17:41:01 -07003485 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003486 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003487 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003488 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003489 }
chaviw8b3871a2017-11-01 17:41:01 -07003490 return 0;
3491 }
3492
chaviw8b3871a2017-11-01 17:41:01 -07003493 uint32_t flags = 0;
3494
Garfield Tan8a3083e2018-12-03 13:21:07 -08003495 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003496
3497 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3498 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003499 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003500 layer->pushPendingState();
3501 }
3502
Valerie Hau871d6352020-01-29 08:44:02 -08003503 // Only set by BLAST adapter layers
3504 if (what & layer_state_t::eProducerDisconnect) {
3505 layer->onDisconnect();
3506 }
3507
chaviw8b3871a2017-11-01 17:41:01 -07003508 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003509 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003510 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003511 }
chaviw8b3871a2017-11-01 17:41:01 -07003512 }
3513 if (what & layer_state_t::eLayerChanged) {
3514 // NOTE: index needs to be calculated before we update the state
3515 const auto& p = layer->getParent();
3516 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003517 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003518 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003519 mCurrentState.layersSortedByZ.removeAt(idx);
3520 mCurrentState.layersSortedByZ.add(layer);
3521 // we need traversal (state changed)
3522 // AND transaction (list changed)
3523 flags |= eTransactionNeeded|eTraversalNeeded;
3524 }
chaviw8b3871a2017-11-01 17:41:01 -07003525 } else {
3526 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003527 flags |= eTransactionNeeded|eTraversalNeeded;
3528 }
3529 }
chaviw8b3871a2017-11-01 17:41:01 -07003530 }
3531 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003532 // NOTE: index needs to be calculated before we update the state
3533 const auto& p = layer->getParent();
3534 if (p == nullptr) {
3535 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3536 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3537 mCurrentState.layersSortedByZ.removeAt(idx);
3538 mCurrentState.layersSortedByZ.add(layer);
3539 // we need traversal (state changed)
3540 // AND transaction (list changed)
3541 flags |= eTransactionNeeded|eTraversalNeeded;
3542 }
3543 } else {
3544 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3545 flags |= eTransactionNeeded|eTraversalNeeded;
3546 }
chaviw8b3871a2017-11-01 17:41:01 -07003547 }
3548 }
3549 if (what & layer_state_t::eSizeChanged) {
3550 if (layer->setSize(s.w, s.h)) {
3551 flags |= eTraversalNeeded;
3552 }
3553 }
3554 if (what & layer_state_t::eAlphaChanged) {
3555 if (layer->setAlpha(s.alpha))
3556 flags |= eTraversalNeeded;
3557 }
3558 if (what & layer_state_t::eColorChanged) {
3559 if (layer->setColor(s.color))
3560 flags |= eTraversalNeeded;
3561 }
Peiyong Lind3788632018-09-18 16:01:31 -07003562 if (what & layer_state_t::eColorTransformChanged) {
3563 if (layer->setColorTransform(s.colorTransform)) {
3564 flags |= eTraversalNeeded;
3565 }
3566 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003567 if (what & layer_state_t::eBackgroundColorChanged) {
3568 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3569 flags |= eTraversalNeeded;
3570 }
3571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003573 // TODO: b/109894387
3574 //
3575 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3576 // rotation. To see the problem observe that if we have a square parent, and a child
3577 // of the same size, then we rotate the child 45 degrees around it's center, the child
3578 // must now be cropped to a non rectangular 8 sided region.
3579 //
3580 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3581 // private API, and the WindowManager only uses rotation in one case, which is on a top
3582 // level layer in which cropping is not an issue.
3583 //
3584 // However given that abuse of rotation matrices could lead to surfaces extending outside
3585 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3586 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3587 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003588 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003589 flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eTransparentRegionChanged) {
3592 if (layer->setTransparentRegionHint(s.transparentRegion))
3593 flags |= eTraversalNeeded;
3594 }
3595 if (what & layer_state_t::eFlagsChanged) {
3596 if (layer->setFlags(s.flags, s.mask))
3597 flags |= eTraversalNeeded;
3598 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003599 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003600 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003601 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003602 if (what & layer_state_t::eCornerRadiusChanged) {
3603 if (layer->setCornerRadius(s.cornerRadius))
3604 flags |= eTraversalNeeded;
3605 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003606 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3607 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3608 }
chaviw8b3871a2017-11-01 17:41:01 -07003609 if (what & layer_state_t::eLayerStackChanged) {
3610 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3611 // We only allow setting layer stacks for top level layers,
3612 // everything else inherits layer stack from its parent.
3613 if (layer->hasParent()) {
3614 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003615 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003616 } else if (idx < 0) {
3617 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003618 "that also does not appear in the top level layer list. Something"
3619 " has gone wrong.",
3620 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003621 } else if (layer->setLayerStack(s.layerStack)) {
3622 mCurrentState.layersSortedByZ.removeAt(idx);
3623 mCurrentState.layersSortedByZ.add(layer);
3624 // we need traversal (state changed)
3625 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003626 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003627 }
3628 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003629 if (what & layer_state_t::eDeferTransaction_legacy) {
3630 if (s.barrierHandle_legacy != nullptr) {
3631 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3632 } else if (s.barrierGbp_legacy != nullptr) {
3633 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003634 if (authenticateSurfaceTextureLocked(gbp)) {
3635 const auto& otherLayer =
3636 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003637 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003638 } else {
3639 ALOGE("Attempt to defer transaction to to an"
3640 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003641 }
3642 }
chaviw8b3871a2017-11-01 17:41:01 -07003643 // We don't trigger a traversal here because if no other state is
3644 // changed, we don't want this to cause any more work
3645 }
chaviw8b3871a2017-11-01 17:41:01 -07003646 if (what & layer_state_t::eReparentChildren) {
3647 if (layer->reparentChildren(s.reparentHandle)) {
3648 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003649 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003650 }
chaviw8b3871a2017-11-01 17:41:01 -07003651 if (what & layer_state_t::eDetachChildren) {
3652 layer->detachChildren();
3653 }
3654 if (what & layer_state_t::eOverrideScalingModeChanged) {
3655 layer->setOverrideScalingMode(s.overrideScalingMode);
3656 // We don't trigger a traversal here because if no other state is
3657 // changed, we don't want this to cause any more work
3658 }
Marissa Wall61c58622018-07-18 10:12:20 -07003659 if (what & layer_state_t::eTransformChanged) {
3660 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3661 }
3662 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3663 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3664 flags |= eTraversalNeeded;
3665 }
3666 if (what & layer_state_t::eCropChanged) {
3667 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3668 }
Marissa Wall861616d2018-10-22 12:52:23 -07003669 if (what & layer_state_t::eFrameChanged) {
3670 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3671 }
Marissa Wall61c58622018-07-18 10:12:20 -07003672 if (what & layer_state_t::eAcquireFenceChanged) {
3673 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3674 }
3675 if (what & layer_state_t::eDataspaceChanged) {
3676 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3677 }
3678 if (what & layer_state_t::eHdrMetadataChanged) {
3679 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3680 }
3681 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3682 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3683 }
3684 if (what & layer_state_t::eApiChanged) {
3685 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3686 }
3687 if (what & layer_state_t::eSidebandStreamChanged) {
3688 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3689 }
Robert Carr720e5062018-07-30 17:45:14 -07003690 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003691 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003692 layer->setInputInfo(s.inputInfo);
3693 flags |= eTraversalNeeded;
3694 } else {
3695 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3696 }
Robert Carr720e5062018-07-30 17:45:14 -07003697 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003698 if (what & layer_state_t::eMetadataChanged) {
3699 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3700 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003701 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3702 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3703 flags |= eTraversalNeeded;
3704 }
3705 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003706 if (what & layer_state_t::eShadowRadiusChanged) {
3707 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3708 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003709 if (what & layer_state_t::eFrameRateSelectionPriority) {
3710 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3711 flags |= eTraversalNeeded;
3712 }
3713 }
Steven Thomas3172e202020-01-06 19:25:30 -08003714 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003715 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3716 "SurfaceFlinger::setClientStateLocked") &&
3717 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3718 Layer::FrameRate::convertCompatibility(
3719 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003720 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003721 }
Steven Thomas3172e202020-01-06 19:25:30 -08003722 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003723 // This has to happen after we reparent children because when we reparent to null we remove
3724 // child layers from current state and remove its relative z. If the children are reparented in
3725 // the same transaction, then we have to make sure we reparent the children first so we do not
3726 // lose its relative z order.
3727 if (what & layer_state_t::eReparent) {
3728 bool hadParent = layer->hasParent();
3729 if (layer->reparent(s.parentHandleForChild)) {
3730 if (!hadParent) {
3731 mCurrentState.layersSortedByZ.remove(layer);
3732 }
3733 flags |= eTransactionNeeded | eTraversalNeeded;
3734 }
3735 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003736 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003737 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3738 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003739 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3740 }
3741 }
Marissa Wall78b72202019-03-15 14:58:34 -07003742 bool bufferChanged = what & layer_state_t::eBufferChanged;
3743 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3744 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003745 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003746 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003747 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3748 if (success) {
3749 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3750 success = ClientCache::getInstance()
3751 .registerErasedRecipient(s.cachedBuffer,
3752 wp<ClientCache::ErasedRecipient>(this));
3753 if (!success) {
3754 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3755 }
3756 }
Marissa Wall78b72202019-03-15 14:58:34 -07003757 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003758 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003759 } else if (bufferChanged) {
3760 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003761 }
Marissa Wall78b72202019-03-15 14:58:34 -07003762 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003763 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3764 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003765 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003766 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003767 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003768 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3769 // Do not put anything that updates layer state or modifies flags after
3770 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003771 return flags;
3772}
3773
chaviw273171b2018-12-26 11:46:30 -08003774uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3775 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003776 if (inputWindowCommands.syncInputWindows) {
3777 flags |= eTraversalNeeded;
3778 }
3779
Vishnu Nairec0ab382019-02-13 15:32:56 -08003780 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003781 return flags;
3782}
3783
chaviwfe94a222019-08-21 13:52:59 -07003784status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3785 sp<IBinder>* outHandle) {
3786 if (!mirrorFromHandle) {
3787 return NAME_NOT_FOUND;
3788 }
3789
3790 sp<Layer> mirrorLayer;
3791 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003792 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003793
3794 {
3795 Mutex::Autolock _l(mStateLock);
3796 mirrorFrom = fromHandle(mirrorFromHandle);
3797 if (!mirrorFrom) {
3798 return NAME_NOT_FOUND;
3799 }
3800
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003801 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3802 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003803 if (result != NO_ERROR) {
3804 return result;
3805 }
3806
3807 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3808 }
3809
3810 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3811}
3812
Marissa Wall2d814fb2019-04-09 18:52:57 +00003813status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3814 uint32_t h, PixelFormat format, uint32_t flags,
3815 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003816 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003817 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3818 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003819 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003820 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003821 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003822 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003823 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003824
Robert Carrc0df3122019-04-11 13:18:21 -07003825 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3826 "Expected only one of parentLayer or parentHandle to be non-null. "
3827 "Programmer error?");
3828
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003829 status_t result = NO_ERROR;
3830
3831 sp<Layer> layer;
3832
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003833 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003834
Evan Roskya1f1e152019-01-24 16:17:46 -08003835 bool primaryDisplayOnly = false;
3836
3837 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3838 // TODO b/64227542
3839 if (metadata.has(METADATA_WINDOW_TYPE)) {
3840 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3841 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003842 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003843 primaryDisplayOnly = true;
3844 }
3845 }
3846
Mathias Agopian3165cc22012-08-08 19:42:09 -07003847 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003848 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003849 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3850 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003851
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003853 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003854 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003855 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003856 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003857 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003858 // check if buffer size is set for color layer.
3859 if (w > 0 || h > 0) {
3860 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3861 int(w), int(h));
3862 return BAD_VALUE;
3863 }
3864
Vishnu Nairfa247b12020-02-11 08:58:26 -08003865 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3866 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003867 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003868 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003869 // check if buffer size is set for container layer.
3870 if (w > 0 || h > 0) {
3871 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3872 int(w), int(h));
3873 return BAD_VALUE;
3874 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003875 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3876 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003877 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003878 default:
3879 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880 break;
3881 }
3882
Dan Stoza7d89d062015-04-30 13:29:25 -07003883 if (result != NO_ERROR) {
3884 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003886
Evan Roskya1f1e152019-01-24 16:17:46 -08003887 if (primaryDisplayOnly) {
3888 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003889 }
3890
Robert Carrb89ea9d2018-12-10 13:01:14 -08003891 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003892 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3893 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003894 if (result != NO_ERROR) {
3895 return result;
3896 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003897 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003898
3899 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003900 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901}
3902
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3904 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003905
3906 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003907 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003908
Dan Stoza436ccf32018-06-21 12:10:12 -07003909 // Grab the state lock since we're accessing mCurrentState
3910 Mutex::Autolock lock(mStateLock);
3911
Cody Northropbc755282017-03-31 12:00:08 -06003912 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003913 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003914 while (matchFound) {
3915 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003916 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003917 if (layer->getName() == uniqueName) {
3918 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003919 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003920 }
3921 });
3922 }
3923
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003924 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003925 return uniqueName;
3926}
3927
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003928status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003929 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003930 LayerMetadata metadata, PixelFormat& format,
3931 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003932 sp<IGraphicBufferProducer>* gbp,
3933 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003935 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 case PIXEL_FORMAT_TRANSPARENT:
3937 case PIXEL_FORMAT_TRANSLUCENT:
3938 format = PIXEL_FORMAT_RGBA_8888;
3939 break;
3940 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003941 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 break;
3943 }
3944
chaviwb4c6e582019-08-16 14:35:07 -07003945 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003946 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003947 args.textureName = getNewTexture();
3948 {
3949 // Grab the SF state lock during this since it's the only safe way to access
3950 // RenderEngine when creating a BufferLayerConsumer
3951 // TODO: Check if this lock is still needed here
3952 Mutex::Autolock lock(mStateLock);
3953 layer = getFactory().createBufferQueueLayer(args);
3954 }
3955
Marissa Wallfd668622018-05-10 10:21:13 -07003956 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003957 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003958 *handle = layer->getHandle();
3959 *gbp = layer->getProducer();
3960 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003961 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003962
Marissa Wallfd668622018-05-10 10:21:13 -07003963 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003964 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965}
3966
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003967status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003968 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003969 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003970 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003971 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003972 args.displayDevice = getDefaultDisplayDevice();
3973 args.textureName = getNewTexture();
3974 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003975 if (outTransformHint) {
3976 *outTransformHint = layer->getTransformHint();
3977 }
Marissa Wall61c58622018-07-18 10:12:20 -07003978 *handle = layer->getHandle();
3979 *outLayer = layer;
3980
3981 return NO_ERROR;
3982}
3983
Vishnu Nairfa247b12020-02-11 08:58:26 -08003984status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3985 uint32_t h, uint32_t flags, LayerMetadata metadata,
3986 sp<IBinder>* handle, sp<Layer>* outLayer) {
3987 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003988 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003989 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003991}
3992
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003993status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003994 uint32_t w, uint32_t h, uint32_t flags,
3995 LayerMetadata metadata, sp<IBinder>* handle,
3996 sp<Layer>* outLayer) {
3997 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003998 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003999 *handle = (*outLayer)->getHandle();
4000 return NO_ERROR;
4001}
4002
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004003void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004004 mLayersPendingRemoval.add(layer);
4005 mLayersRemoved = true;
4006 setTransactionFlags(eTransactionNeeded);
4007}
4008
Robert Carr695d5282018-12-18 15:27:58 -08004009void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004010{
Robert Carr2e102c92018-10-23 12:11:15 -07004011 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004012 // If a layer has a parent, we allow it to out-live it's handle
4013 // with the idea that the parent holds a reference and will eventually
4014 // be cleaned up. However no one cleans up the top-level so we do so
4015 // here.
4016 if (layer->getParent() == nullptr) {
4017 mCurrentState.layersSortedByZ.remove(layer);
4018 }
4019 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004020
4021 auto it = mLayersByLocalBinderToken.begin();
4022 while (it != mLayersByLocalBinderToken.end()) {
4023 if (it->second == layer) {
4024 it = mLayersByLocalBinderToken.erase(it);
4025 } else {
4026 it++;
4027 }
4028 }
4029
Robert Carr695d5282018-12-18 15:27:58 -08004030 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004031}
4032
Mathias Agopianb60314a2012-04-10 22:09:54 -07004033// ---------------------------------------------------------------------------
4034
Andy McFadden13a082e2012-08-24 10:16:42 -07004035void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004036 const auto display = getDefaultDisplayDeviceLocked();
4037 if (!display) return;
4038
4039 const sp<IBinder> token = display->getDisplayToken().promote();
4040 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004041
Jesse Hall01e29052013-02-19 16:13:35 -08004042 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004043 Vector<ComposerState> state;
4044 Vector<DisplayState> displays;
4045 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004046 d.what = DisplayState::eDisplayProjectionChanged |
4047 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004048 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004049 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004050 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004051 d.frame.makeInvalid();
4052 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004053 d.width = 0;
4054 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004055 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004056 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4057 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004058
Dominik Laskowskie9774092018-12-11 10:04:24 -08004059 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004060
Dominik Laskowski83b88212018-12-11 13:34:06 -08004061 const nsecs_t vsyncPeriod = getVsyncPeriod();
4062 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004063
Brian Andersond0010582017-03-07 13:20:31 -08004064 // Use phase of 0 since phase is not known.
4065 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004066 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004067 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004068}
4069
4070void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004071 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004072 postMessageAsync(
4073 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004074}
4075
Ady Abraham27c70212019-06-11 10:52:26 -07004076void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4077 if (mHWCVsyncState != enabled) {
4078 getHwComposer().setVsyncEnabled(displayId, enabled);
4079 mHWCVsyncState = enabled;
4080 }
4081}
4082
Dominik Laskowskie9774092018-12-11 10:04:24 -08004083void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004084 if (display->isVirtual()) {
4085 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004086 return;
4087 }
4088
Dominik Laskowski075d3172018-05-24 15:50:06 -07004089 const auto displayId = display->getId();
4090 LOG_ALWAYS_FATAL_IF(!displayId);
4091
Dominik Laskowski34157762018-10-31 13:07:19 -07004092 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004093
4094 int currentMode = display->getPowerMode();
4095 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004096 return;
4097 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004099 display->setPowerMode(mode);
4100
Lloyd Pique4dccc412018-01-22 17:21:36 -08004101 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004102 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004103 }
4104
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004105 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004106 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004107 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004108 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004109 mScheduler->onScreenAcquired(mAppConnectionHandle);
4110 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004113 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004114 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004115 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004116
4117 struct sched_param param = {0};
4118 param.sched_priority = 1;
4119 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4120 ALOGW("Couldn't set SCHED_FIFO on display on");
4121 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004122 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004123 // Turn off the display
4124 struct sched_param param = {0};
4125 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4126 ALOGW("Couldn't set SCHED_OTHER on display off");
4127 }
4128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004129 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004130 mScheduler->disableHardwareVsync(true);
4131 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004132 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004133
Ady Abraham27c70212019-06-11 10:52:26 -07004134 // Make sure HWVsync is disabled before turning off the display
4135 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4136
Dominik Laskowski075d3172018-05-24 15:50:06 -07004137 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004138 mVisibleRegionsDirty = true;
4139 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004140 } else if (mode == HWC_POWER_MODE_DOZE ||
4141 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004142 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004143 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004144 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004145 mScheduler->onScreenAcquired(mAppConnectionHandle);
4146 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004147 }
4148 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4149 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004150 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004151 mScheduler->disableHardwareVsync(true);
4152 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004153 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004154 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004155 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004156 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004158 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004159
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004160 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004161 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004162 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004163 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004164 }
4165
Dominik Laskowski34157762018-10-31 13:07:19 -07004166 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004167}
4168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004169void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004170 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171 const auto display = getDisplayDevice(displayToken);
4172 if (!display) {
4173 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4174 displayToken.get());
4175 } else if (display->isVirtual()) {
4176 ALOGW("Attempt to set power mode %d for virtual display", mode);
4177 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004178 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004179 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004180 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004181}
4182
4183// ---------------------------------------------------------------------------
4184
Dominik Laskowskic2867142019-01-21 11:33:38 -08004185status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4186 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004187 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004188
Mathias Agopianbd115332013-04-18 16:41:04 -07004189 IPCThreadState* ipc = IPCThreadState::self();
4190 const int pid = ipc->getCallingPid();
4191 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004192
Mathias Agopianbd115332013-04-18 16:41:04 -07004193 if ((uid != AID_SHELL) &&
4194 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004195 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4196 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004198 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004199 // (this would indicate SF is stuck, but we want to be able to
4200 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004201 status_t err = mStateLock.timedLock(s2ns(1));
4202 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004203 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004204 StringAppendF(&result,
4205 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4206 "(no locks held)\n",
4207 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004208 }
4209
Dominik Laskowskic2867142019-01-21 11:33:38 -08004210 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004211 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004212 {"--dispsync"s,
4213 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004214 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004215 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4216 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4217 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4218 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4219 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4220 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004221 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004222 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4223 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004224
Dominik Laskowskic2867142019-01-21 11:33:38 -08004225 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004226
Dominik Laskowski46470112019-08-02 13:13:11 -07004227 const auto it = dumpers.find(flag);
4228 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004229 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004230 } else if (!asProto) {
4231 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004232 }
4233
Mathias Agopian9795c422009-08-26 16:36:26 -07004234 if (locked) {
4235 mStateLock.unlock();
4236 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004237
Dominik Laskowski46470112019-08-02 13:13:11 -07004238 if (it == dumpers.end()) {
4239 const LayersProto layersProto = dumpProtoFromMainThread();
4240 if (asProto) {
4241 result.append(layersProto.SerializeAsString());
4242 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004243 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004244 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4245 result.append(LayerProtoParser::layerTreeToString(layerTree));
4246 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004247 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004248 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004250 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004251 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004252 return NO_ERROR;
4253}
4254
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004255status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4256 if (asProto && mTracing.isEnabled()) {
4257 mTracing.writeToFileAsync();
4258 }
4259
4260 return doDump(fd, DumpArgs(), asProto);
4261}
4262
Dominik Laskowskic2867142019-01-21 11:33:38 -08004263void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004264 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004265 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004266}
4267
Dominik Laskowskic2867142019-01-21 11:33:38 -08004268void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004269 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004270
Dominik Laskowskic2867142019-01-21 11:33:38 -08004271 if (args.size() > 1) {
4272 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004273 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004274 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004275 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004276 }
Robert Carr2047fae2016-11-28 14:09:09 -08004277 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004278 } else {
4279 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004280 }
4281}
4282
Dominik Laskowskic2867142019-01-21 11:33:38 -08004283void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004284 const bool clearAll = args.size() < 2;
4285 const auto name = clearAll ? String8() : String8(args[1]);
4286
Edgar Arriaga844fa672020-01-16 14:21:42 -08004287 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004288 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004289 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004290 }
Robert Carr2047fae2016-11-28 14:09:09 -08004291 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004292
Svetoslavd85084b2014-03-20 10:28:31 -07004293 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004294}
4295
Dominik Laskowskic2867142019-01-21 11:33:38 -08004296void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4297 mTimeStats->parseArgs(asProto, args, result);
4298}
4299
Jamie Gennis6547ff42013-07-16 20:12:42 -07004300// This should only be called from the main thread. Otherwise it would need
4301// the lock and should use mCurrentState rather than mDrawingState.
4302void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004303 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004304 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004305 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004306
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004307 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004308}
4309
Yiwei Zhang5434a782018-12-05 18:06:32 -08004310void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004311 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004312
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004313 if (isLayerTripleBufferingDisabled())
4314 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004315
Yiwei Zhang5434a782018-12-05 18:06:32 -08004316 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4317 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4318 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4319 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4320 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4321 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004322 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004323}
4324
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004325void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004326 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004327
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004328 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004329 result.append("\n");
4330
Ady Abraham9e16a482019-12-03 17:19:41 -08004331 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004332 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004333 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004334 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004335
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004336 HwcConfigIndexType defaultConfig;
4337 float minFps, maxFps;
4338 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004339 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004340 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004341 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004342 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004343 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4344 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004345
Ana Krulecc2870422019-01-29 19:00:58 -08004346 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004347}
4348
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4350 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004351 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4352 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004353 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004354 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004356 }
David Sodman4a36e932017-11-07 14:29:47 -08004357 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004358 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004359 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004360 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4361 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004362}
4363
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004364void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4365 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004366 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4367 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004368 for (const auto& segment : history) {
4369 if (!segment.usedThirdBuffer) {
4370 stats.twoBufferTime += segment.totalTime;
4371 }
4372 if (segment.occupancyAverage < 1.0f) {
4373 stats.doubleBufferedTime += segment.totalTime;
4374 } else if (segment.occupancyAverage < 2.0f) {
4375 stats.tripleBufferedTime += segment.totalTime;
4376 }
4377 ++stats.numSegments;
4378 stats.totalTime += segment.totalTime;
4379 }
4380}
4381
Yiwei Zhang5434a782018-12-05 18:06:32 -08004382void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4383 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004384
4385 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4386 const size_t count = currentLayers.size();
4387 for (size_t i=0 ; i<count ; i++) {
4388 currentLayers[i]->dumpFrameEvents(result);
4389 }
4390}
4391
Yiwei Zhang5434a782018-12-05 18:06:32 -08004392void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004393 result.append("Buffering stats:\n");
4394 result.append(" [Layer name] <Active time> <Two buffer> "
4395 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004396 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004397 typedef std::tuple<std::string, float, float, float> BufferTuple;
4398 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004399 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004400 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004401 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004402 if (stats.numSegments == 0) {
4403 continue;
4404 }
4405 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4406 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4407 stats.totalTime;
4408 float doubleBufferRatio = static_cast<float>(
4409 stats.doubleBufferedTime) / stats.totalTime;
4410 float tripleBufferRatio = static_cast<float>(
4411 stats.tripleBufferedTime) / stats.totalTime;
4412 sorted.insert({activeTime, {name, twoBufferRatio,
4413 doubleBufferRatio, tripleBufferRatio}});
4414 }
4415 for (const auto& sortedPair : sorted) {
4416 float activeTime = sortedPair.first;
4417 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004418 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4419 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004420 }
4421 result.append("\n");
4422}
4423
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004425 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004426 const auto displayId = display->getId();
4427 if (!displayId) {
4428 continue;
4429 }
4430 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004431 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 continue;
4433 }
4434
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435 StringAppendF(&result,
4436 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4437 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004438 uint8_t port;
4439 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004440 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004441 result.append("no identification data\n");
4442 continue;
4443 }
4444
4445 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004446 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004447 continue;
4448 }
4449
4450 const auto edid = parseEdid(data);
4451 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004452 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004453 continue;
4454 }
4455
Yiwei Zhang5434a782018-12-05 18:06:32 -08004456 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004457 result.append(edid->displayName.data(), edid->displayName.length());
4458 result.append("\"\n");
4459 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004460}
4461
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004462void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4463 std::string& result) const {
4464 hwc2_display_t hwcDisplayId;
4465 uint8_t port;
4466 DisplayIdentificationData data;
4467
4468 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4469 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4470 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4471 }
4472}
4473
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004475 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4477 StringAppendF(&result, "DisplayColorSetting: %s\n",
4478 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004479
4480 // TODO: print out if wide-color mode is active or not
4481
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004482 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004483 const auto displayId = display->getId();
4484 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004485 continue;
4486 }
4487
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004489 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004490 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004492 }
4493
Lloyd Pique32cbe282018-10-19 13:09:22 -07004494 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495 StringAppendF(&result, " Current color mode: %s (%d)\n",
4496 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004497 }
4498 result.append("\n");
4499}
4500
Vishnu Nair8406fd72019-07-30 11:29:31 -07004501LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004502 Mutex::Autolock _l(mStateLock);
4503 const auto device = getDefaultDisplayDeviceLocked();
chaviw1d044282017-09-27 12:19:28 -07004504 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004505 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004506 layer->writeToProto(layersProto, traceFlags, device);
chaviw08f3cb22020-01-13 13:17:21 -08004507 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004508
chaviw1d044282017-09-27 12:19:28 -07004509 return layersProto;
4510}
4511
Alec Mouri6b9e9912020-01-21 10:50:24 -08004512void SurfaceFlinger::dumpHwc(std::string& result) const {
4513 getHwComposer().dump(result);
4514}
4515
Vishnu Nair0f085c62019-08-30 08:49:12 -07004516void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4517 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4518 // it.
4519 LayerProto* rootProto = layersProto.add_layers();
4520 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4521 rootProto->set_id(offscreenRootLayerId);
4522 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004523 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004524
4525 for (Layer* offscreenLayer : mOffscreenLayers) {
4526 // Add layer as child of the fake root
4527 rootProto->add_children(offscreenLayer->sequence);
4528
4529 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004530 LayerProto* layerProto =
4531 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004532 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004533 }
4534}
4535
Vishnu Nair8406fd72019-07-30 11:29:31 -07004536LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4537 LayersProto layersProto;
4538 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4539 return layersProto;
4540}
4541
Vishnu Nair0f085c62019-08-30 08:49:12 -07004542void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4543 result.append("Offscreen Layers:\n");
4544 postMessageSync(new LambdaMessage([&]() {
4545 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004546 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004547 layer->dumpCallingUidPid(result);
4548 });
4549 }
4550 }));
4551}
4552
Dominik Laskowskic2867142019-01-21 11:33:38 -08004553void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4554 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 Colorizer colorizer(colorize);
4556
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004557 // figure out if we're stuck somewhere
4558 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004559 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4561
4562 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004563 * Dump library configuration.
4564 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004565
4566 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004567 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004568 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004569 appendSfConfigString(result);
4570 appendUiConfigString(result);
4571 appendGuiConfigString(result);
4572 result.append("\n");
4573
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004574 result.append("\nDisplay identification data:\n");
4575 dumpDisplayIdentificationData(result);
4576
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004577 result.append("\nWide-Color information:\n");
4578 dumpWideColorInfo(result);
4579
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004580 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004581 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004582 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004583 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004584 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004585
Andy McFadden41d67d72014-04-25 16:58:34 -07004586 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004587 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004588 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004589 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004590 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004591
Dan Stozab90cf072015-03-05 11:05:59 -08004592 dumpStaticScreenStats(result);
4593 result.append("\n");
4594
Alec Mouri40189b02019-03-05 15:07:54 -08004595 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4596 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4597 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004598
Dan Stozae77c7662016-05-13 11:37:28 -07004599 dumpBufferingStats(result);
4600
Andy McFadden4803b742012-09-24 19:07:20 -07004601 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004602 * Dump the visible layer list
4603 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004604 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004605 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4607 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004609
Chia-I Wu2f884132018-09-13 15:17:58 -07004610 {
Lloyd Pique207def92019-02-28 16:09:52 -08004611 StringAppendF(&result, "Composition layers\n");
4612 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004613 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004614 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004615
4616 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4617 layer->getDebugName() ? layer->getDebugName()
4618 : "<unknown>");
4619 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004620 });
4621 }
4622
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004623 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004624 * Dump Display state
4625 */
4626
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004627 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004629 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004630 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004631 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004632 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004633 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004634
4635 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004636 * Dump CompositionEngine state
4637 */
4638
4639 mCompositionEngine->dump(result);
4640
4641 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004642 * Dump SurfaceFlinger global state
4643 */
4644
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004645 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004646 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004647 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004648
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004649 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004650
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004651 DebugEGLImageTracker::getInstance()->dump(result);
4652
Dominik Laskowski075d3172018-05-24 15:50:06 -07004653 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004654 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4655 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004656 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4657 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004658 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result,
4660 " transaction-flags : %08x\n"
4661 " gpu_to_cpu_unsupported : %d\n",
4662 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004664 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004665 displayId && getHwComposer().isConnected(*displayId)) {
4666 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result,
4668 " refresh-rate : %f fps\n"
4669 " x-dpi : %f\n"
4670 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004671 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4672 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004673 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676
Dan Stozae22aec72016-08-01 13:20:59 -07004677 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004678 * Tracing state
4679 */
4680 mTracing.dump(result);
4681 result.append("\n");
4682
4683 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004684 * HWC layer minidump
4685 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004686 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004687 const auto displayId = display->getId();
4688 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004689 continue;
4690 }
4691
Yiwei Zhang5434a782018-12-05 18:06:32 -08004692 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004693 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004694 const sp<DisplayDevice> displayDevice = display;
4695 mCurrentState.traverseInZOrder(
4696 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004697 result.append("\n");
4698 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004699
4700 /*
4701 * Dump HWComposer state
4702 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004704 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004706 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004707 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004708 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004709
4710 /*
4711 * Dump gralloc state
4712 */
4713 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4714 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004715
4716 /*
4717 * Dump VrFlinger state if in use.
4718 */
4719 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4720 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004722 result.append("\n");
4723 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004724
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004725 result.append(mTimeStats->miniDump());
4726 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727}
4728
Chia-I Wu28f320b2018-05-03 11:02:56 -07004729void SurfaceFlinger::updateColorMatrixLocked() {
4730 mat4 colorMatrix;
4731 if (mGlobalSaturationFactor != 1.0f) {
4732 // Rec.709 luma coefficients
4733 float3 luminance{0.213f, 0.715f, 0.072f};
4734 luminance *= 1.0f - mGlobalSaturationFactor;
4735 mat4 saturationMatrix = mat4(
4736 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4737 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4738 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4739 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4740 );
4741 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4742 } else {
4743 colorMatrix = mClientColorMatrix * mDaltonizer();
4744 }
4745
4746 if (mCurrentState.colorMatrix != colorMatrix) {
4747 mCurrentState.colorMatrix = colorMatrix;
4748 mCurrentState.colorMatrixChanged = true;
4749 setTransactionFlags(eTransactionNeeded);
4750 }
4751}
4752
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004753status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004754#pragma clang diagnostic push
4755#pragma clang diagnostic error "-Wswitch-enum"
4756 switch (static_cast<ISurfaceComposerTag>(code)) {
4757 // These methods should at minimum make sure that the client requested
4758 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004759 case BOOT_FINISHED:
4760 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004761 case CREATE_DISPLAY:
4762 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004763 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 case GET_ANIMATION_FRAME_STATS:
4765 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004766 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004767 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004768 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004769 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4770 case SET_AUTO_LOW_LATENCY_MODE:
4771 case GET_GAME_CONTENT_TYPE_SUPPORT:
4772 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004773 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004774 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004775 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004776 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004777 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004778 case NOTIFY_POWER_HINT:
4779 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004780 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4781 IPCThreadState* ipc = IPCThreadState::self();
4782 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4783 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004784 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004785 }
Robert Carr1db73f62016-12-21 12:58:51 -08004786 return OK;
4787 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004788 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004789 IPCThreadState* ipc = IPCThreadState::self();
4790 const int pid = ipc->getCallingPid();
4791 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4793 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004794 return PERMISSION_DENIED;
4795 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004797 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 // Used by apps to hook Choreographer to SurfaceFlinger.
4799 case CREATE_DISPLAY_EVENT_CONNECTION:
4800 // The following calls are currently used by clients that do not
4801 // request necessary permissions. However, they do not expose any secret
4802 // information, so it is OK to pass them.
4803 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004804 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004806 case GET_PHYSICAL_DISPLAY_IDS:
4807 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004808 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004809 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004810 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004811 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004812 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004813 case GET_DISPLAY_STATS:
4814 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4815 // Calling setTransactionState is safe, because you need to have been
4816 // granted a reference to Client* and Handle* to do anything with it.
4817 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004818 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004819 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004820 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004821 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004822 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004823 // setFrameRate() is deliberately available for apps to call without any
4824 // special permissions.
4825 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004826 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4827 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004828 return OK;
4829 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004830 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004831 case CAPTURE_SCREEN:
4832 case ADD_REGION_SAMPLING_LISTENER:
4833 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004834 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004835 IPCThreadState* ipc = IPCThreadState::self();
4836 const int pid = ipc->getCallingPid();
4837 const int uid = ipc->getCallingUid();
4838 if ((uid != AID_GRAPHICS) &&
4839 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4840 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4841 return PERMISSION_DENIED;
4842 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004843 return OK;
4844 }
chaviw93df2ea2019-04-30 16:45:12 -07004845 case CAPTURE_SCREEN_BY_ID: {
4846 IPCThreadState* ipc = IPCThreadState::self();
4847 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004848 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004849 return OK;
4850 }
4851 return PERMISSION_DENIED;
4852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004854
4855 // These codes are used for the IBinder protocol to either interrogate the recipient
4856 // side of the transaction for its canonical interface descriptor or to dump its state.
4857 // We let them pass by default.
4858 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4859 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4860 code == IBinder::SYSPROPS_TRANSACTION) {
4861 return OK;
4862 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004863 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004865 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4867 return OK;
4868 }
4869 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4870 return PERMISSION_DENIED;
4871#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004872}
4873
Ana Krulec13be8ad2018-08-21 02:43:56 +00004874status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4875 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004876 status_t credentialCheck = CheckTransactCodeCredentials(code);
4877 if (credentialCheck != OK) {
4878 return credentialCheck;
4879 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004880
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4882 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004883 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004884 IPCThreadState* ipc = IPCThreadState::self();
4885 const int uid = ipc->getCallingUid();
4886 if (CC_UNLIKELY(uid != AID_SYSTEM
4887 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004888 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004889 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004890 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 return PERMISSION_DENIED;
4892 }
4893 int n;
4894 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004895 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004896 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004897 return NO_ERROR;
4898 case 1002: // SHOW_UPDATES
4899 n = data.readInt32();
4900 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004901 invalidateHwcGeometry();
4902 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004903 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004905 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004906 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004908 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004909 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004910 setTransactionFlags(
4911 eTransactionNeeded|
4912 eDisplayTransactionNeeded|
4913 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004914 return NO_ERROR;
4915 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004916 case 1006:{ // send empty update
4917 signalRefresh();
4918 return NO_ERROR;
4919 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004920 case 1008: // toggle use of hw composer
4921 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004922 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004923 invalidateHwcGeometry();
4924 repaintEverything();
4925 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004926 case 1009: // toggle use of transform hint
4927 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004928 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004929 invalidateHwcGeometry();
4930 repaintEverything();
4931 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004932 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004933 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004934 reply->writeInt32(0);
4935 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004936 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004937 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938 return NO_ERROR;
4939 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004940 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004941 if (!display) {
4942 return NAME_NOT_FOUND;
4943 }
4944
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004945 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004946 return NO_ERROR;
4947 }
4948 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004949 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004950 // daltonize
4951 n = data.readInt32();
4952 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004953 case 1:
4954 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4955 break;
4956 case 2:
4957 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4958 break;
4959 case 3:
4960 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4961 break;
4962 default:
4963 mDaltonizer.setType(ColorBlindnessType::None);
4964 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004965 }
4966 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004967 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004968 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004969 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004970 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004971
4972 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004973 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004974 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004976 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004977 // apply a color matrix
4978 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004979 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004980 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004981 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004982 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004983 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004984 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004985 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004986 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004987 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004988 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004989
4990 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4991 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004992 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004993 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4994 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4995 }
4996
Chia-I Wu28f320b2018-05-03 11:02:56 -07004997 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004998 return NO_ERROR;
4999 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005000 case 1016: { // Unused.
5001 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005002 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005003 case 1017: {
5004 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005005 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005006 return NO_ERROR;
5007 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005008 case 1018: { // Modify Choreographer's phase offset
5009 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005010 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005011 return NO_ERROR;
5012 }
5013 case 1019: { // Modify SurfaceFlinger's phase offset
5014 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005015 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005016 return NO_ERROR;
5017 }
Irvel468051e2016-06-13 16:44:44 -07005018 case 1020: { // Layer updates interceptor
5019 n = data.readInt32();
5020 if (n) {
5021 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005022 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005023 }
5024 else{
5025 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005026 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005027 }
5028 return NO_ERROR;
5029 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005030 case 1021: { // Disable HWC virtual displays
5031 n = data.readInt32();
5032 mUseHwcVirtualDisplays = !n;
5033 return NO_ERROR;
5034 }
Romain Guy0147a172017-06-01 13:53:56 -07005035 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005036 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005037 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005038
Chia-I Wu28f320b2018-05-03 11:02:56 -07005039 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005040 return NO_ERROR;
5041 }
Romain Guy54f154a2017-10-24 21:40:32 +01005042 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005043 int32_t colorMode;
5044
Chia-I Wu0d711262018-05-21 15:19:35 -07005045 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005046 if (data.readInt32(&colorMode) == NO_ERROR) {
5047 mForceColorMode = static_cast<ColorMode>(colorMode);
5048 }
Romain Guy54f154a2017-10-24 21:40:32 +01005049 invalidateHwcGeometry();
5050 repaintEverything();
5051 return NO_ERROR;
5052 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005053 // Deprecate, use 1030 to check whether the device is color managed.
5054 case 1024: {
5055 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005056 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005057 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005058 n = data.readInt32();
5059 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005060 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005061 Mutex::Autolock lock(mStateLock);
5062 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005063 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005064 reply->writeInt32(NO_ERROR);
5065 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005066 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005067 bool writeFile = false;
5068 {
5069 Mutex::Autolock lock(mStateLock);
5070 mTracingEnabledChanged = true;
5071 writeFile = mTracing.disable();
5072 }
5073
5074 if (writeFile) {
5075 reply->writeInt32(mTracing.writeToFile());
5076 } else {
5077 reply->writeInt32(NO_ERROR);
5078 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005079 }
5080 return NO_ERROR;
5081 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005082 case 1026: { // Get layer tracing status
5083 reply->writeBool(mTracing.isEnabled());
5084 return NO_ERROR;
5085 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005086 // Is a DisplayColorSetting supported?
5087 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005088 const auto display = getDefaultDisplayDevice();
5089 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005090 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005091 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005092
5093 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5094 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005095 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005096 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005097 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005098 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005099 reply->writeBool(true);
5100 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005101 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005102 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005103 break;
5104 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005105 reply->writeBool(
5106 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005107 break;
5108 }
5109 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005110 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005111 // Is VrFlinger active?
5112 case 1028: {
5113 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005114 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005115 return NO_ERROR;
5116 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005117 // Set buffer size for SF tracing (value in KB)
5118 case 1029: {
5119 n = data.readInt32();
5120 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5121 ALOGW("Invalid buffer size: %d KB", n);
5122 reply->writeInt32(BAD_VALUE);
5123 return BAD_VALUE;
5124 }
5125
5126 ALOGD("Updating trace buffer to %d KB", n);
5127 mTracing.setBufferSize(n * 1024);
5128 reply->writeInt32(NO_ERROR);
5129 return NO_ERROR;
5130 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005131 // Is device color managed?
5132 case 1030: {
5133 reply->writeBool(useColorManagement);
5134 return NO_ERROR;
5135 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005136 // Override default composition data space
5137 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5138 // && adb shell stop zygote && adb shell start zygote
5139 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5140 // adb shell stop zygote && adb shell start zygote
5141 case 1031: {
5142 Mutex::Autolock _l(mStateLock);
5143 n = data.readInt32();
5144 if (n) {
5145 n = data.readInt32();
5146 if (n) {
5147 Dataspace dataspace = static_cast<Dataspace>(n);
5148 if (!validateCompositionDataspace(dataspace)) {
5149 return BAD_VALUE;
5150 }
5151 mDefaultCompositionDataspace = dataspace;
5152 }
5153 n = data.readInt32();
5154 if (n) {
5155 Dataspace dataspace = static_cast<Dataspace>(n);
5156 if (!validateCompositionDataspace(dataspace)) {
5157 return BAD_VALUE;
5158 }
5159 mWideColorGamutCompositionDataspace = dataspace;
5160 }
5161 } else {
5162 // restore composition data space.
5163 mDefaultCompositionDataspace = defaultCompositionDataspace;
5164 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5165 }
5166 return NO_ERROR;
5167 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005168 // Set trace flags
5169 case 1033: {
5170 n = data.readUint32();
5171 ALOGD("Updating trace flags to 0x%x", n);
5172 mTracing.setTraceFlags(n);
5173 reply->writeInt32(NO_ERROR);
5174 return NO_ERROR;
5175 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005176 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005177 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005178 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005179 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005180 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005181 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005182 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005183 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005184 } else {
5185 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005186 }
5187 return NO_ERROR;
5188 }
Ady Abraham34392f72019-04-10 11:29:27 -07005189 case 1035: {
5190 n = data.readInt32();
5191 mDebugDisplayConfigSetByBackdoor = false;
5192 if (n >= 0) {
5193 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005194 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005195 if (result != NO_ERROR) {
5196 return result;
5197 }
5198 mDebugDisplayConfigSetByBackdoor = true;
5199 }
5200 return NO_ERROR;
5201 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005202 }
5203 }
5204 return err;
5205}
5206
Steven Thomas6d8110b2017-08-31 18:24:21 -07005207void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005208 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005209 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005210}
5211
Ana Krulec7d1d6832018-12-27 11:10:09 -08005212void SurfaceFlinger::repaintEverythingForHWC() {
5213 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005214 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005215 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005216}
5217
Ady Abrahama09852a2020-02-20 14:23:42 -08005218void SurfaceFlinger::kernelTimerChanged(bool expired) {
5219 static bool updateOverlay =
5220 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5221 if (!updateOverlay || !mRefreshRateOverlay) return;
5222
5223 // Update the overlay on the main thread to avoid race conditions with
5224 // mRefreshRateConfigs->getCurrentRefreshRate()
5225 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5226 if (mRefreshRateOverlay) {
5227 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5228 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005229 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005230 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5231 if (mDesiredActiveConfigChanged) {
5232 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5233 mDesiredActiveConfig.configId);
5234 }
5235
5236 return mRefreshRateConfigs->getCurrentRefreshRate();
5237 }();
5238 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5239
5240 if (current != min) {
5241 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5242 mEventQueue->invalidate();
5243 }
5244 }
5245 }));
5246}
5247
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005248// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5249class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005250public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005251 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5252 ~WindowDisconnector() {
5253 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005254 }
5255
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005256private:
5257 ANativeWindow* mWindow;
5258 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005259};
5260
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005261status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005262 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005263 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5264 const Rect& sourceCrop, uint32_t reqWidth,
5265 uint32_t reqHeight, bool useIdentityTransform,
5266 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005268
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005269 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005270
Dominik Laskowski718f9602019-11-09 20:01:35 -08005271 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5272 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5273 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5274 renderAreaRotation = ui::Transform::ROT_0;
5275 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005276
Chia-I Wu20261cb2018-08-23 12:55:44 -07005277 sp<DisplayDevice> display;
5278 {
5279 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005280
Chia-I Wu20261cb2018-08-23 12:55:44 -07005281 display = getDisplayDeviceLocked(displayToken);
5282 if (!display) return BAD_VALUE;
5283
Chia-I Wucb023152018-08-28 12:57:23 -07005284 // set the requested width/height to the logical display viewport size
5285 // by default
5286 if (reqWidth == 0 || reqHeight == 0) {
5287 reqWidth = uint32_t(display->getViewport().width());
5288 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005289 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005290 }
5291
Peiyong Lin0e003c92018-09-17 11:09:51 -07005292 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005293 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005294
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005295 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5296 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005297 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005298 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005299}
5300
chaviw93df2ea2019-04-30 16:45:12 -07005301static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5302 switch (colorMode) {
5303 case ColorMode::DISPLAY_P3:
5304 case ColorMode::BT2100_PQ:
5305 case ColorMode::BT2100_HLG:
5306 case ColorMode::DISPLAY_BT2020:
5307 return Dataspace::DISPLAY_P3;
5308 default:
5309 return Dataspace::V0_SRGB;
5310 }
5311}
5312
5313const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5314 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5315 if (displayToken) {
5316 return getDisplayDeviceLocked(displayToken);
5317 }
5318 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5319 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005320 return getDisplayByLayerStack(displayOrLayerStack);
5321}
5322
5323const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005324 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005325 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005326 return display;
5327 }
5328 }
5329 return nullptr;
5330}
5331
5332status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5333 sp<GraphicBuffer>* outBuffer) {
5334 sp<DisplayDevice> display;
5335 uint32_t width;
5336 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005337 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005338 {
5339 Mutex::Autolock _l(mStateLock);
5340 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5341 if (!display) {
5342 return BAD_VALUE;
5343 }
5344
5345 width = uint32_t(display->getViewport().width());
5346 height = uint32_t(display->getViewport().height());
5347
Dominik Laskowski718f9602019-11-09 20:01:35 -08005348 const auto orientation = display->getOrientation();
5349 captureOrientation = ui::Transform::toRotationFlags(orientation);
5350
5351 switch (captureOrientation) {
5352 case ui::Transform::ROT_90:
5353 captureOrientation = ui::Transform::ROT_270;
5354 break;
5355
5356 case ui::Transform::ROT_270:
5357 captureOrientation = ui::Transform::ROT_90;
5358 break;
5359
5360 case ui::Transform::ROT_INVALID:
5361 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5362 captureOrientation = ui::Transform::ROT_0;
5363 break;
5364
5365 default:
5366 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005367 }
chaviw93df2ea2019-04-30 16:45:12 -07005368 *outDataspace =
5369 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5370 }
5371
5372 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5373 false /* captureSecureLayers */);
5374
5375 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5376 std::placeholders::_1);
5377 bool ignored = false;
5378 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5379 false /* useIdentityTransform */,
5380 ignored /* outCapturedSecureLayers */);
5381}
5382
Robert Carr866455f2019-04-02 16:28:26 -07005383status_t SurfaceFlinger::captureLayers(
5384 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5385 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5386 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5387 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005388 ATRACE_CALL();
5389
5390 class LayerRenderArea : public RenderArea {
5391 public:
Robert Carr578038f2018-03-09 12:25:24 -08005392 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005393 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005394 bool childrenOnly, const Rect& displayViewport)
5395 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005396 mLayer(layer),
5397 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005398 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005399 mFlinger(flinger),
5400 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005401 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005402 Rect getBounds() const override {
5403 const Layer::State& layerState(mLayer->getDrawingState());
5404 return mLayer->getBufferSize(layerState);
5405 }
Marissa Wall61c58622018-07-18 10:12:20 -07005406 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005407 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005408 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005409 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005410 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005411 }
chaviwa76b2712017-09-20 12:02:26 -07005412 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005413 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005414 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005415 Rect getSourceCrop() const override {
5416 if (mCrop.isEmpty()) {
5417 return getBounds();
5418 } else {
5419 return mCrop;
5420 }
5421 }
Robert Carr578038f2018-03-09 12:25:24 -08005422 class ReparentForDrawing {
5423 public:
5424 const sp<Layer>& oldParent;
5425 const sp<Layer>& newParent;
5426
Vishnu Nair4351ad52019-02-11 14:13:02 -08005427 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5428 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005429 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005430 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005431 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5432 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005433 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005434 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005435 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005436 };
5437
5438 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005439 const Rect sourceCrop = getSourceCrop();
5440 // no need to check rotation because there is none
5441 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5442 sourceCrop.height() != getReqHeight();
5443
Robert Carr578038f2018-03-09 12:25:24 -08005444 if (!mChildrenOnly) {
5445 mTransform = mLayer->getTransform().inverse();
5446 drawLayers();
5447 } else {
5448 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005449 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5450 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005451 // In the "childrenOnly" case we reparent the children to a screenshot
5452 // layer which has no properties set and which does not draw.
5453 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005454 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5455 "Screenshot Parent"s, w, h, 0,
5456 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005457
Vishnu Nair4351ad52019-02-11 14:13:02 -08005458 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005459 drawLayers();
5460 }
5461 }
chaviwa76b2712017-09-20 12:02:26 -07005462
chaviwa76b2712017-09-20 12:02:26 -07005463 private:
chaviw7206d492017-11-10 16:16:12 -08005464 const sp<Layer> mLayer;
5465 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005466
Peiyong Linefefaac2018-08-17 12:27:51 -07005467 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005468 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005469
5470 SurfaceFlinger* mFlinger;
5471 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005472 };
5473
Robert Carrc0df3122019-04-11 13:18:21 -07005474 int reqWidth = 0;
5475 int reqHeight = 0;
5476 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005477 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005478 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005479 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005480 {
5481 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005482
Robert Carrc0df3122019-04-11 13:18:21 -07005483 parent = fromHandle(layerHandleBinder);
5484 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5485 ALOGE("captureLayers called with an invalid or removed parent");
5486 return NAME_NOT_FOUND;
5487 }
5488
5489 const int uid = IPCThreadState::self()->getCallingUid();
5490 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5491 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5492 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5493 return PERMISSION_DENIED;
5494 }
5495
Vishnu Nairefc42e22019-12-03 17:36:12 -08005496 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005497 if (sourceCrop.width() <= 0) {
5498 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005499 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005500 }
5501
5502 if (sourceCrop.height() <= 0) {
5503 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005504 crop.bottom = parentSourceBounds.getHeight();
5505 }
5506
5507 if (crop.isEmpty() || frameScale <= 0.0f) {
5508 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5509 // crop was not specified, or an invalid frame scale was provided.
5510 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005511 }
5512 reqWidth = crop.width() * frameScale;
5513 reqHeight = crop.height() * frameScale;
5514
5515 for (const auto& handle : excludeHandles) {
5516 sp<Layer> excludeLayer = fromHandle(handle);
5517 if (excludeLayer != nullptr) {
5518 excludeLayers.emplace(excludeLayer);
5519 } else {
5520 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5521 return NAME_NOT_FOUND;
5522 }
5523 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005524
5525 auto display = getDisplayByLayerStack(parent->getLayerStack());
5526 if (!display) {
5527 return BAD_VALUE;
5528 }
5529
5530 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005531 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005532
Chia-I Wu20261cb2018-08-23 12:55:44 -07005533 // really small crop or frameScale
5534 if (reqWidth <= 0) {
5535 reqWidth = 1;
5536 }
5537 if (reqHeight <= 0) {
5538 reqHeight = 1;
5539 }
5540
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005541 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5542 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005543 auto traverseLayers = [parent, childrenOnly,
5544 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005545 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5546 if (!layer->isVisible()) {
5547 return;
Robert Carr578038f2018-03-09 12:25:24 -08005548 } else if (childrenOnly && layer == parent.get()) {
5549 return;
chaviwa76b2712017-09-20 12:02:26 -07005550 }
Robert Carr866455f2019-04-02 16:28:26 -07005551
5552 sp<Layer> p = layer;
5553 while (p != nullptr) {
5554 if (excludeLayers.count(p) != 0) {
5555 return;
5556 }
5557 p = p->getParent();
5558 }
5559
chaviwa76b2712017-09-20 12:02:26 -07005560 visitor(layer);
5561 });
5562 };
Robert Carr108b2c72019-04-02 16:32:58 -07005563
5564 bool outCapturedSecureLayers = false;
5565 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5566 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005567}
5568
5569status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5570 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005571 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005572 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005573 bool useIdentityTransform,
5574 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005575 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005576
Peiyong Lin0e003c92018-09-17 11:09:51 -07005577 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005578 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5579 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005580 *outBuffer =
5581 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5582 static_cast<android_pixel_format>(reqPixelFormat), 1,
5583 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584
Robert Carr108b2c72019-04-02 16:32:58 -07005585 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5586 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005587}
5588
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005589status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5590 TraverseLayersFunction traverseLayers,
5591 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005592 bool useIdentityTransform,
5593 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 // This mutex protects syncFd and captureResult for communication of the return values from the
5595 // main thread back to this Binder thread
5596 std::mutex captureMutex;
5597 std::condition_variable captureCondition;
5598 std::unique_lock<std::mutex> captureLock(captureMutex);
5599 int syncFd = -1;
5600 std::optional<status_t> captureResult;
5601
Robert Carr03480e22018-01-04 16:02:06 -08005602 const int uid = IPCThreadState::self()->getCallingUid();
5603 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5604
Dominik Laskowski8c001672018-05-30 16:52:06 -07005605 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005606 // If there is a refresh pending, bug out early and tell the binder thread to try again
5607 // after the refresh.
5608 if (mRefreshPending) {
5609 ATRACE_NAME("Skipping screenshot for now");
5610 std::unique_lock<std::mutex> captureLock(captureMutex);
5611 captureResult = std::make_optional<status_t>(EAGAIN);
5612 captureCondition.notify_one();
5613 return;
5614 }
5615
5616 status_t result = NO_ERROR;
5617 int fd = -1;
5618 {
5619 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005620 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005621 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005622 useIdentityTransform, forSystem, &fd,
5623 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005624 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005625 }
5626
5627 {
5628 std::unique_lock<std::mutex> captureLock(captureMutex);
5629 syncFd = fd;
5630 captureResult = std::make_optional<status_t>(result);
5631 captureCondition.notify_one();
5632 }
5633 });
5634
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005635 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005637 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638 while (*captureResult == EAGAIN) {
5639 captureResult.reset();
5640 result = postMessageAsync(message);
5641 if (result != NO_ERROR) {
5642 return result;
5643 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005644 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005645 }
5646 result = *captureResult;
5647 }
5648
5649 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005650 sync_wait(syncFd, -1);
5651 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005652 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005653
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005654 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005655}
5656
chaviwa76b2712017-09-20 12:02:26 -07005657void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005658 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005659 const sp<GraphicBuffer>& buffer,
5660 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005661 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005662
chaviwa76b2712017-09-20 12:02:26 -07005663 const auto reqWidth = renderArea.getReqWidth();
5664 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005665 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005666 const auto transform = renderArea.getTransform();
5667 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005668 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005669
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005670 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005671 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005672
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005673 // assume that bounds are never offset, and that they are the same as the
5674 // buffer bounds.
5675 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005676 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005677 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005678
5679 // Now take into account the rotation flag. We append a transform that
5680 // rotates the layer stack about the origin, then translate by buffer
5681 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005682 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005683 int displacementX = 0;
5684 int displacementY = 0;
5685 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5686 switch (rotation) {
5687 case ui::Transform::ROT_90:
5688 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005689 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005690 break;
5691 case ui::Transform::ROT_180:
5692 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005693 displacementY = renderArea.getBounds().getWidth();
5694 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695 break;
5696 case ui::Transform::ROT_270:
5697 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005698 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699 break;
5700 default:
5701 break;
5702 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005703
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005704 // We need to transform the clipping window into the right spot.
5705 // First, rotate the clipping rectangle by the rotation hint to get the
5706 // right orientation
5707 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5708 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5709 const vec4 rotClipTL = rotMatrix * clipTL;
5710 const vec4 rotClipBR = rotMatrix * clipBR;
5711 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5712 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5713 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5714 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5715
5716 // Now reposition the clipping rectangle with the displacement vector
5717 // computed above.
5718 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005719 clientCompositionDisplay.clip =
5720 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5721 newClipRight + displacementX, newClipBottom + displacementY);
5722
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005723 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005724 clientCompositionDisplay.globalTransform =
5725 clipTransform * clientCompositionDisplay.globalTransform;
5726
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005727 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5728 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005729
chaviw50da5042018-04-09 13:49:37 -07005730 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005731
Vishnu Nair9b079a22020-01-21 14:36:08 -08005732 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005733 fillLayer.source.buffer.buffer = nullptr;
5734 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5735 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5736 fillLayer.alpha = half(alpha);
5737 clientCompositionLayers.push_back(fillLayer);
5738
5739 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005740 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005741 const bool supportProtectedContent = false;
5742 Region clip(renderArea.getBounds());
5743 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5744 clip,
5745 useIdentityTransform,
5746 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5747 renderArea.isSecure(),
5748 supportProtectedContent,
5749 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005750 displayViewport,
5751 clientCompositionDisplay.outputDataspace,
5752 true, /* realContentIsVisible */
5753 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005754 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005755 std::vector<compositionengine::LayerFE::LayerSettings> results =
5756 layer->prepareClientCompositionList(targetSettings);
5757 clientCompositionLayers.insert(clientCompositionLayers.end(),
5758 std::make_move_iterator(results.begin()),
5759 std::make_move_iterator(results.end()));
5760 results.clear();
5761
chaviwa76b2712017-09-20 12:02:26 -07005762 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005763
Vishnu Nair9b079a22020-01-21 14:36:08 -08005764 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5765 clientCompositionLayers.reserve(clientCompositionLayers.size());
5766 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5767 std::back_inserter(clientCompositionLayerPointers),
5768 [](compositionengine::LayerFE::LayerSettings& settings)
5769 -> renderengine::LayerSettings* { return &settings; });
5770
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005771 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005772 // Use an empty fence for the buffer fence, since we just created the buffer so
5773 // there is no need for synchronization with the GPU.
5774 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005775 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005776 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005777 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005778 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005779
5780 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005781}
5782
chaviwa76b2712017-09-20 12:02:26 -07005783status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5784 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005785 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005786 bool useIdentityTransform, bool forSystem,
5787 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005788 ATRACE_CALL();
5789
chaviwa76b2712017-09-20 12:02:26 -07005790 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005791 outCapturedSecureLayers =
5792 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005793 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005794
Robert Carr03480e22018-01-04 16:02:06 -08005795 // We allow the system server to take screenshots of secure layers for
5796 // use in situations like the Screen-rotation animation and place
5797 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005798 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005799 ALOGW("FB is protected: PERMISSION_DENIED");
5800 return PERMISSION_DENIED;
5801 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005802 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005803 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005804}
5805
chaviw95ef3c42019-02-14 10:55:09 -08005806void SurfaceFlinger::setInputWindowsFinished() {
5807 Mutex::Autolock _l(mStateLock);
5808
5809 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005810
chaviw95ef3c42019-02-14 10:55:09 -08005811 mTransactionCV.broadcast();
5812}
chaviw5f21a5e2019-02-14 10:00:34 -08005813
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005814// ---------------------------------------------------------------------------
5815
Edgar Arriaga844fa672020-01-16 14:21:42 -08005816void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5817 layersSortedByZ.traverse(visitor);
5818}
5819
Dan Stoza412903f2017-04-27 13:42:17 -07005820void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5821 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005822}
5823
Dan Stoza412903f2017-04-27 13:42:17 -07005824void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5825 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005826}
5827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005828void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005829 const LayerVector::Visitor& visitor) {
5830 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005831 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005832 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005833 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005834 continue;
5835 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005836 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005837 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005838 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005839 return;
5840 }
chaviwa76b2712017-09-20 12:02:26 -07005841 if (!layer->isVisible()) {
5842 return;
5843 }
5844 visitor(layer);
5845 });
5846 }
5847}
5848
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005849status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5850 HwcConfigIndexType defaultConfig,
5851 float minRefreshRate,
5852 float maxRefreshRate) {
5853 Mutex::Autolock lock(mStateLock);
5854
Dominik Laskowski22488f62019-03-28 09:53:04 -07005855 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005856 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5857 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5858 // it should go thru setDesiredActiveConfig, similar to primary display.
5859 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5860 const auto displayId = display->getId();
5861 LOG_ALWAYS_FATAL_IF(!displayId);
5862
5863 HWC2::VsyncPeriodChangeConstraints constraints;
5864 constraints.desiredTimeNanos = systemTime();
5865 constraints.seamlessRequired = false;
5866
5867 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005868 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5869 constraints, &timeline) < 0) {
5870 return BAD_VALUE;
5871 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005872 if (timeline.refreshRequired) {
5873 repaintEverythingForHWC();
5874 }
5875
Ady Abrahamdfa37362020-01-21 18:02:39 -08005876 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005877 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005878 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5879 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005880 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005881 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005882 }
5883
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005884 if (mDebugDisplayConfigSetByBackdoor) {
5885 // ignore this request as config is overridden by backdoor
5886 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005887 }
5888
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005889 bool policyChanged;
5890 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5891 &policyChanged) < 0) {
5892 return BAD_VALUE;
5893 }
5894 if (!policyChanged) {
5895 return NO_ERROR;
5896 }
5897
5898 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5899 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005900
5901 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5902 // that listeners that care about a change in allowed configs can get the notification.
5903 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005904 const nsecs_t vsyncPeriod =
5905 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005906 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005907 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005908
Ana Krulec3f6a2062020-01-23 15:48:01 -08005909 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005910 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005911 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5912 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5913 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5914 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5915 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5916
5917 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5918 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5919 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005920 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005921 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005922 }
5923
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005924 return NO_ERROR;
5925}
5926
Ana Krulec0782b882019-10-15 17:34:54 -07005927status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005928 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005929 float maxRefreshRate) {
5930 ATRACE_CALL();
5931
5932 if (!displayToken) {
5933 return BAD_VALUE;
5934 }
5935
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005936 status_t result = NO_ERROR;
5937
Ana Krulec234bb162019-11-10 22:55:55 +01005938 postMessageSync(new LambdaMessage([&]() {
5939 const auto display = getDisplayDeviceLocked(displayToken);
5940 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005941 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005942 ALOGE("Attempt to set desired display configs for invalid display token %p",
5943 displayToken.get());
5944 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005945 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005946 ALOGW("Attempt to set desired display configs for virtual display");
5947 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005948 result =
5949 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5950 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005951 }
5952 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005953
5954 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005955}
5956
5957status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005958 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005959 float* outMinRefreshRate,
5960 float* outMaxRefreshRate) {
5961 ATRACE_CALL();
5962
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005963 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005964 return BAD_VALUE;
5965 }
5966
5967 Mutex::Autolock lock(mStateLock);
5968 const auto display = getDisplayDeviceLocked(displayToken);
5969 if (!display) {
5970 return NAME_NOT_FOUND;
5971 }
5972
5973 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005974 HwcConfigIndexType defaultConfig;
5975 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5976 *outDefaultConfig = defaultConfig.value();
5977 return NO_ERROR;
5978 } else if (display->isVirtual()) {
5979 return BAD_VALUE;
5980 } else {
5981 const auto displayId = display->getId();
5982 if (!displayId) {
5983 return BAD_VALUE;
5984 }
5985 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5986 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5987 *outMinRefreshRate = 1e9f / vsyncPeriod;
5988 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5989 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005990 }
Ana Krulec0782b882019-10-15 17:34:54 -07005991}
5992
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005993void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005994 mFlinger->setInputWindowsFinished();
5995}
5996
Robert Carrc0df3122019-04-11 13:18:21 -07005997sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005998 BBinder* b = nullptr;
5999 if (handle) {
6000 b = handle->localBinder();
6001 }
Robert Carrc0df3122019-04-11 13:18:21 -07006002 if (b == nullptr) {
6003 return nullptr;
6004 }
6005 auto it = mLayersByLocalBinderToken.find(b);
6006 if (it != mLayersByLocalBinderToken.end()) {
6007 return it->second.promote();
6008 }
6009 return nullptr;
6010}
6011
Dominik Laskowski75848362019-11-11 17:57:20 -08006012void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006013 mNumLayers++;
6014 mScheduler->registerLayer(layer);
6015}
6016
6017void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6018 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006019 removeFromOffscreenLayers(layer);
6020}
6021
6022// WARNING: ONLY CALL THIS FROM LAYER DTOR
6023// Here we add children in the current state to offscreen layers and remove the
6024// layer itself from the offscreen layer list. Since
6025// this is the dtor, it is safe to access the current state. This keeps us
6026// from dangling children layers such that they are not reachable from the
6027// Drawing state nor the offscreen layer list
6028// See b/141111965
6029void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6030 for (auto& child : layer->getCurrentChildren()) {
6031 mOffscreenLayers.emplace(child.get());
6032 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006033 mOffscreenLayers.erase(layer);
6034}
6035
Alec Mouri4545a8a2019-08-08 20:05:32 -07006036void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6037 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6038}
6039
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006040status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6041 float lightPosY, float lightPosZ,
6042 float lightRadius) {
6043 Mutex::Autolock _l(mStateLock);
6044 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6045 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6046 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6047 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6048 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6049
6050 // these values are overridden when calculating the shadow settings for a layer.
6051 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6052 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006053 return NO_ERROR;
6054}
6055
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006056const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6057 const {
6058 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6059 // on the work to remove the table in that bug rather than adding more to
6060 // it.
6061 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6062 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6063 // supported, and exposed via the
6064 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6065 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6066 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6067 };
6068 return genericLayerMetadataKeyMap;
6069}
6070
Steven Thomas62a4cf82020-01-31 12:04:03 -08006071status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6072 int8_t compatibility) {
6073 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6074 return BAD_VALUE;
6075 }
6076
6077 Mutex::Autolock lock(mStateLock);
6078 if (authenticateSurfaceTextureLocked(surface)) {
6079 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6080 if (layer->setFrameRate(
6081 Layer::FrameRate(frameRate,
6082 Layer::FrameRate::convertCompatibility(compatibility)))) {
6083 setTransactionFlags(eTraversalNeeded);
6084 }
6085 } else {
6086 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6087 return BAD_VALUE;
6088 }
6089 return NO_ERROR;
6090}
6091
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006092} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006093
Mathias Agopian3f844832013-08-07 21:24:32 -07006094#if defined(__gl_h_)
6095#error "don't include gl/gl.h in this file"
6096#endif
6097
6098#if defined(__gl2_h_)
6099#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006100#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006101
6102// TODO(b/129481165): remove the #pragma below and fix conversion issues
6103#pragma clang diagnostic pop // ignored "-Wconversion"