blob: f3755f466c9f12fb665632e6b48e5ab285b66632 [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 Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-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 Piqueaad4ebf2019-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600220bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800221ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700222bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700223bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700224Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
225ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
226Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800228bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700229
Kalle Raitaa099a242017-01-11 11:17:29 -0800230std::string getHwcServiceName() {
231 char value[PROPERTY_VALUE_MAX] = {};
232 property_get("debug.sf.hwc_service_name", value, "default");
233 ALOGI("Using HWComposer service: '%s'", value);
234 return std::string(value);
235}
236
237bool useTrebleTestingOverride() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.treble_testing_override", value, "false");
240 ALOGI("Treble testing override: '%s'", value);
241 return std::string(value) == "true";
242}
243
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
245 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Enhanced");
252 default:
253 return std::string("Unknown ") +
254 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256}
257
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
261 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700263 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700264 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700265 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700266 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800267 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
268 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800269
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700270SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800271 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800280
Steven Thomas050b2c82017-03-06 11:45:16 -0800281 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 mDefaultCompositionDataspace =
291 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700292 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
293 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 defaultCompositionDataspace = mDefaultCompositionDataspace;
295 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
296 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
297 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
298 wideColorGamutCompositionPixelFormat =
299 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700300
Yichi Chenda901bf2019-06-28 14:58:27 +0800301 mColorSpaceAgnosticDataspace =
302 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800305
Dominik Laskowski718f9602019-11-09 20:01:35 -0800306 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
307 switch (primary_display_orientation(Values::ORIENTATION_0)) {
308 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800309 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800310 case Values::ORIENTATION_90:
311 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800312 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800313 case Values::ORIENTATION_180:
314 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800315 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800316 case Values::ORIENTATION_270:
317 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
319 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800321
Sundong Ahn85131bd2019-02-18 15:51:53 +0900322 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324 // debugging stuff...
325 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700326
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700328 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700329
Alec Mouri989ddbe2020-02-06 09:26:19 -0800330 property_get("ro.build.type", value, "user");
331 mIsUserBuild = strcmp(value, "user") == 0;
332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333 property_get("debug.sf.showupdates", value, "0");
334 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700335
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700336 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000337
338 // DDMS debugging deprecated (b/120782499)
339 property_get("debug.sf.ddms", value, "0");
340 int debugDdms = atoi(value);
341 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700342
343 property_get("debug.sf.disable_backpressure", value, "0");
344 mPropagateBackpressure = !atoi(value);
345 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700346
Ady Abrahamadb9a992019-09-19 21:21:55 +0000347 property_get("debug.sf.enable_gl_backpressure", value, "0");
348 mPropagateBackpressureClientComposition = atoi(value);
349 ALOGI_IF(mPropagateBackpressureClientComposition,
350 "Enabling backpressure propagation for Client Composition");
351
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800352 property_get("debug.sf.enable_hwc_vds", value, "0");
353 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800354 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800355
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800356 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800357 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800358 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700359
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800360 property_get("ro.surface_flinger.supports_background_blur", value, "0");
361 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800362 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800363 bool disableBlurs = atoi(value);
364 mEnableBlurs = supportsBlurs && !disableBlurs;
365 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
366 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("ro.sf.blurs_are_expensive", value, "0");
368 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800369
Yiwei Zhang243b3782018-05-15 17:40:04 -0700370 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700371 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
372 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
373
Dan Stozaec460082018-12-17 15:35:09 -0800374 property_get("debug.sf.luma_sampling", value, "1");
375 mLumaSampling = atoi(value);
376
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800377 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800378 mDisableClientCompositionCache = atoi(value);
379
Romain Guy11d63f42017-07-20 12:47:14 -0700380 // We should be reading 'persist.sys.sf.color_saturation' here
381 // but since /data may be encrypted, we need to wait until after vold
382 // comes online to attempt to read the property. The property is
383 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800384
385 if (useTrebleTestingOverride()) {
386 // Without the override SurfaceFlinger cannot connect to HIDL
387 // services that are not listed in the manifests. Considered
388 // deriving the setting from the set service name, but it
389 // would be brittle if the name that's not 'default' is used
390 // for production purposes later on.
391 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
392 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800393
394 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395}
396
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800397void SurfaceFlinger::onFirstRef()
398{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800399 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400}
401
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700402SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403
Dan Stozac7014012014-02-14 15:03:43 -0800404void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405{
406 // the window manager died on us. prepare its eulogy.
407
Andy McFadden13a082e2012-08-24 10:16:42 -0700408 // restore initial conditions (default device unblank, etc)
409 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410
411 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413}
414
Robert Carr1db73f62016-12-21 12:58:51 -0800415static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700416 status_t err = client->initCheck();
417 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419 }
Robert Carr1db73f62016-12-21 12:58:51 -0800420 return nullptr;
421}
422
423sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
424 return initClient(new Client(this));
425}
426
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700427sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
428 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429{
430 class DisplayToken : public BBinder {
431 sp<SurfaceFlinger> flinger;
432 virtual ~DisplayToken() {
433 // no more references, this display must be terminated
434 Mutex::Autolock _l(flinger->mStateLock);
435 flinger->mCurrentState.displays.removeItem(this);
436 flinger->setTransactionFlags(eDisplayTransactionNeeded);
437 }
438 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700439 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 : flinger(flinger) {
441 }
442 };
443
444 sp<BBinder> token = new DisplayToken(this);
445
446 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 // Display ID is assigned when virtual display is allocated by HWC.
448 DisplayDeviceState state;
449 state.isSecure = secure;
450 state.displayName = displayName;
451 mCurrentState.displays.add(token, state);
452 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 return token;
454}
455
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700456void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 Mutex::Autolock _l(mStateLock);
458
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
460 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 return;
463 }
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
466 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 ALOGE("destroyDisplay called for non-virtual display");
468 return;
469 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 mInterceptor->saveDisplayDeletion(state.sequenceId);
471 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 setTransactionFlags(eDisplayTransactionNeeded);
473}
474
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800475std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
476 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 const auto internalDisplayId = getInternalDisplayIdLocked();
479 if (!internalDisplayId) {
480 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 }
482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483 std::vector<PhysicalDisplayId> displayIds;
484 displayIds.reserve(mPhysicalDisplayTokens.size());
485 displayIds.push_back(internalDisplayId->value);
486
487 for (const auto& [id, token] : mPhysicalDisplayTokens) {
488 if (id != *internalDisplayId) {
489 displayIds.push_back(id.value);
490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800493 return displayIds;
494}
495
496sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
497 Mutex::Autolock lock(mStateLock);
498 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499}
500
Ady Abraham37965d42018-11-01 13:43:32 -0700501status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
502 if (!outGetColorManagement) {
503 return BAD_VALUE;
504 }
505 *outGetColorManagement = useColorManagement;
506 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700507}
508
Lloyd Pique441d5042018-10-18 16:49:51 -0700509HWComposer& SurfaceFlinger::getHwComposer() const {
510 return mCompositionEngine->getHwComposer();
511}
512
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700513renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
514 return mCompositionEngine->getRenderEngine();
515}
516
Lloyd Pique70d91362018-10-18 16:02:55 -0700517compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
518 return *mCompositionEngine.get();
519}
520
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521void SurfaceFlinger::bootFinished()
522{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700523 if (mStartPropertySetThread->join() != NO_ERROR) {
524 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526 const nsecs_t now = systemTime();
527 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000528 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529
Mikael Pessa90092f42019-08-26 17:22:04 -0700530 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000531 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700532
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 // wait patiently for the window manager death
534 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700535 mWindowManager = defaultServiceManager()->getService(name);
536 if (mWindowManager != 0) {
537 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538 }
Robert Carr720e5062018-07-30 17:45:14 -0700539 sp<IBinder> input(defaultServiceManager()->getService(
540 String16("inputflinger")));
541 if (input == nullptr) {
542 ALOGE("Failed to link to input service");
543 } else {
544 mInputFlinger = interface_cast<IInputFlinger>(input);
545 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546
Steven Thomas050b2c82017-03-06 11:45:16 -0800547 if (mVrFlinger) {
548 mVrFlinger->OnBootFinished();
549 }
550
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700552 // formerly we would just kill the process, but we now ask it to exit so it
553 // can choose where to stop the animation.
554 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700555
556 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
557 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
558 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700559
Ana Krulecbd6654b2019-02-15 15:18:15 -0800560 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800561 readPersistentProperties();
562 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800563
Ady Abraham8a82ba62020-01-17 12:43:17 -0800564 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
565 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
566 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
567 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569}
570
Dan Stoza436ccf32018-06-21 12:10:12 -0700571uint32_t SurfaceFlinger::getNewTexture() {
572 {
573 std::lock_guard lock(mTexturePoolMutex);
574 if (!mTexturePool.empty()) {
575 uint32_t name = mTexturePool.back();
576 mTexturePool.pop_back();
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
578 return name;
579 }
580
581 // The pool was too small, so increase it for the future
582 ++mTexturePoolSize;
583 }
584
585 // The pool was empty, so we need to get a new texture name directly using a
586 // blocking call to the main thread
587 uint32_t name = 0;
588 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
589 return name;
590}
591
Mathias Agopian3f844832013-08-07 21:24:32 -0700592void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700593 std::lock_guard lock(mTexturePoolMutex);
594 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
595 // to actually delete this or not based on mTexturePoolSize
596 mTexturePool.push_back(texture);
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700608 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800609 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700610 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
611 renderengine::RenderEngineCreationArgs::Builder()
612 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
613 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
614 .setUseColorManagerment(useColorManagement)
615 .setEnableProtectedContext(enable_protected_contents(false))
616 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800617 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700618 .setContextPriority(useContextPriority
619 ? renderengine::RenderEngine::ContextPriority::HIGH
620 : renderengine::RenderEngine::ContextPriority::MEDIUM)
621 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800622 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700623
624 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
625 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700626 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800627 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800628 // Process any initial hotplug and resulting display changes.
629 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700630 const auto display = getDefaultDisplayDeviceLocked();
631 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700632 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700633 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800634
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700636 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700637 // This callback is called from the vr flinger dispatch thread. We
638 // need to call signalTransaction(), which requires holding
639 // mStateLock when we're not on the main thread. Acquiring
640 // mStateLock from the vr flinger dispatch thread might trigger a
641 // deadlock in surface flinger (see b/66916578), so post a message
642 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700643 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700644 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
645 mVrFlingerRequestsDisplay = requestDisplay;
646 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700647 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700649 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
650 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700651 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700652 .value_or(0),
653 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800654 if (!mVrFlinger) {
655 ALOGE("Failed to start vrflinger");
656 }
657 }
658
Mathias Agopian92a979a2012-08-02 18:32:23 -0700659 // initialize our drawing state
660 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700661
Andy McFadden13a082e2012-08-24 10:16:42 -0700662 // set initial conditions (e.g. unblank default device)
663 initializeDisplays();
664
Steven Thomas137d4bc2019-07-25 16:55:14 -0700665 char primeShaderCache[PROPERTY_VALUE_MAX];
666 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
667 if (atoi(primeShaderCache)) {
668 getRenderEngine().primeCache();
669 }
Dan Stoza4e637772016-07-28 13:31:51 -0700670
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700672
673 const bool presentFenceReliable =
674 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
675 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700676
677 if (mStartPropertySetThread->Start() != NO_ERROR) {
678 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800679 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700682}
683
Romain Guy11d63f42017-07-20 12:47:14 -0700684void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700685 Mutex::Autolock _l(mStateLock);
686
Romain Guy11d63f42017-07-20 12:47:14 -0700687 char value[PROPERTY_VALUE_MAX];
688
689 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700691 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800692 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100693
694 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700695 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800696
697 property_get("persist.sys.sf.color_mode", value, "0");
698 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700699}
700
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800702 // Start boot animation service by setting a property mailbox
703 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800705 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 if (mStartPropertySetThread->join() != NO_ERROR) {
707 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709}
710
Mathias Agopian875d8e12013-06-07 15:35:48 -0700711size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700712 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700713}
714
Mathias Agopian875d8e12013-06-07 15:35:48 -0700715size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700716 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700717}
718
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800719// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800720
Jamie Gennis582270d2011-08-17 18:19:00 -0700721bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800722 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800723 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800724 return authenticateSurfaceTextureLocked(bufferProducer);
725}
726
727bool SurfaceFlinger::authenticateSurfaceTextureLocked(
728 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800729 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800730 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800731}
732
Brian Anderson6b376712017-04-04 10:51:39 -0700733status_t SurfaceFlinger::getSupportedFrameTimestamps(
734 std::vector<FrameEvent>* outSupported) const {
735 *outSupported = {
736 FrameEvent::REQUESTED_PRESENT,
737 FrameEvent::ACQUIRE,
738 FrameEvent::LATCH,
739 FrameEvent::FIRST_REFRESH_START,
740 FrameEvent::LAST_REFRESH_START,
741 FrameEvent::GPU_COMPOSITION_DONE,
742 FrameEvent::DEQUEUE_READY,
743 FrameEvent::RELEASE,
744 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700745 ConditionalLock _l(mStateLock,
746 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700747 if (!getHwComposer().hasCapability(
748 HWC2::Capability::PresentFenceIsNotReliable)) {
749 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
750 }
751 return NO_ERROR;
752}
753
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800754status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
755 if (!displayToken || !state) {
756 return BAD_VALUE;
757 }
758
759 Mutex::Autolock lock(mStateLock);
760
761 const auto display = getDisplayDeviceLocked(displayToken);
762 if (!display) {
763 return NAME_NOT_FOUND;
764 }
765
766 state->layerStack = display->getLayerStack();
767 state->orientation = display->getOrientation();
768
769 const Rect viewport = display->getViewport();
770 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
771
772 return NO_ERROR;
773}
774
775status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
776 if (!displayToken || !info) {
777 return BAD_VALUE;
778 }
779
780 Mutex::Autolock lock(mStateLock);
781
782 const auto display = getDisplayDeviceLocked(displayToken);
783 if (!display) {
784 return NAME_NOT_FOUND;
785 }
786
Dominik Laskowski55c85402020-01-21 16:25:47 -0800787 if (const auto connectionType = display->getConnectionType())
788 info->connectionType = *connectionType;
789 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800790 return INVALID_OPERATION;
791 }
792
793 if (mEmulatedDisplayDensity) {
794 info->density = mEmulatedDisplayDensity;
795 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800796 info->density = info->connectionType == DisplayConnectionType::Internal
797 ? mInternalDisplayDensity
798 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800799 }
800
801 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200802 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800803
804 return NO_ERROR;
805}
806
Dominik Laskowski22488f62019-03-28 09:53:04 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800808 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski22488f62019-03-28 09:53:04 -0700813 Mutex::Autolock lock(mStateLock);
814
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800815 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700816 if (!displayId) {
817 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800820 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700826
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800827 auto width = hwConfig->getWidth();
828 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 auto xDpi = hwConfig->getDpiX();
831 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700832
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800833 if (isInternal &&
834 (internalDisplayOrientation == ui::ROTATION_90 ||
835 internalDisplayOrientation == ui::ROTATION_270)) {
836 std::swap(width, height);
837 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 }
839
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800841
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800842 if (mEmulatedDisplayDensity) {
843 config.xDpi = mEmulatedDisplayDensity;
844 config.yDpi = mEmulatedDisplayDensity;
845 } else {
846 config.xDpi = xDpi;
847 config.yDpi = yDpi;
848 }
849
850 const nsecs_t period = hwConfig->getVsyncPeriod();
851 config.refreshRate = 1e9f / period;
852
853 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
854 config.appVsyncOffset = offsets.late.app;
855 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856
Andy McFadden91b2ca82014-06-13 14:04:23 -0700857 // This is how far in advance a buffer must be queued for
858 // presentation at a given time. If you want a buffer to appear
859 // on the screen at time N, you must submit the buffer before
860 // (N - presentationDeadline).
861 //
862 // Normally it's one full refresh period (to give SF a chance to
863 // latch the buffer), but this can be reduced by configuring a
864 // DispSync offset. Any additional delays introduced by the hardware
865 // composer or panel must be accounted for here.
866 //
867 // We add an additional 1ms to allow for processing time and
868 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800869 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700870
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700872 }
873
Dan Stoza7f7da322014-05-02 15:26:25 -0700874 return NO_ERROR;
875}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700876
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
878 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700879 return BAD_VALUE;
880 }
881
Ana Krulecc2870422019-01-29 19:00:58 -0800882 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700883 return NO_ERROR;
884}
885
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700886int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
887 const auto display = getDisplayDevice(displayToken);
888 if (!display) {
889 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800890 return BAD_VALUE;
891 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700892
Steven Thomasc9098452019-09-30 17:15:05 -0700893 if (display->isPrimary()) {
894 std::lock_guard<std::mutex> lock(mActiveConfigLock);
895 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800896 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700897 }
Steven Thomasc9098452019-09-30 17:15:05 -0700898 }
Ady Abraham2139f732019-11-13 18:56:40 -0800899
900 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700901}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700902
Ady Abraham03b02dd2019-03-21 15:40:11 -0700903void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800904 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800905 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
906 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800907
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800908 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800909 // config twice. However event generation config might have changed so we need to update it
910 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800911 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700912 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
913 mDesiredActiveConfig = info;
914 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800915
916 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800917 // This will trigger HWC refresh without resetting the idle timer.
918 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700919 // Start receiving vsync samples now, so that we can detect a period
920 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800921 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700922 // As we called to set period, we will call to onRefreshRateChangeCompleted once
923 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700924 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800925
Ady Abraham9e16a482019-12-03 17:19:41 -0800926 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
927 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800929 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700930
931 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800932 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700933 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800934}
935
936status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
937 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800938
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100939 if (!displayToken) {
940 return BAD_VALUE;
941 }
Ady Abraham838de062019-02-04 10:24:03 -0800942
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100943 status_t result = NO_ERROR;
944
945 postMessageSync(new LambdaMessage([&]() {
946 const auto display = getDisplayDeviceLocked(displayToken);
947 if (!display) {
948 ALOGE("Attempt to set allowed display configs for invalid display token %p",
949 displayToken.get());
950 result = BAD_VALUE;
951 } else if (display->isVirtual()) {
952 ALOGW("Attempt to set allowed display configs for virtual display");
953 result = BAD_VALUE;
954 } else {
955 HwcConfigIndexType config(mode);
956 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
957 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
958 refreshRate.fps);
959 }
960 }));
961
962 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963}
964
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965void SurfaceFlinger::setActiveConfigInternal() {
966 ATRACE_CALL();
967
Dominik Laskowski22488f62019-03-28 09:53:04 -0700968 const auto display = getDefaultDisplayDeviceLocked();
969 if (!display) {
970 return;
971 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972
Dominik Laskowski22488f62019-03-28 09:53:04 -0700973 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800974 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700975 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800976 display->setActiveConfig(mUpcomingActiveConfig.configId);
977
Ady Abraham2139f732019-11-13 18:56:40 -0800978 auto refreshRate =
979 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800980 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
981 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800982 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700983
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800984 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700985 const nsecs_t vsyncPeriod =
986 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
987 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800988 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700989 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800990 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991}
992
Ady Abraham53852a52019-05-28 18:07:44 -0700993void SurfaceFlinger::desiredActiveConfigChangeDone() {
994 std::lock_guard<std::mutex> lock(mActiveConfigLock);
995 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
996 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700997
Kevin DuBois5988f482020-01-17 09:03:32 -0800998 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800999 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001000 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001001 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1002 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001003}
1004
Dominik Laskowski22488f62019-03-28 09:53:04 -07001005bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001006 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001007 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001009 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001011 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012 return true;
1013 }
1014
1015 // We received the present fence from the HWC, so we assume it successfully updated
1016 // the config, hence we update SF.
1017 mCheckPendingFence = false;
1018 setActiveConfigInternal();
1019 }
1020
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001021 // Store the local variable to release the lock.
1022 ActiveConfigInfo desiredActiveConfig;
1023 {
1024 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001025 if (!mDesiredActiveConfigChanged) {
1026 return false;
1027 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028 desiredActiveConfig = mDesiredActiveConfig;
1029 }
1030
Ady Abraham2139f732019-11-13 18:56:40 -08001031 auto refreshRate =
1032 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1033 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1034 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001035 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1037 // display is not valid or we are already in the requested mode
1038 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001039 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001041 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001042
Ady Abraham838de062019-02-04 10:24:03 -08001043 // Desired active config was set, it is different than the config currently in use, however
1044 // allowed configs might have change by the time we process the refresh.
1045 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001046 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001047 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001048 return false;
1049 }
Alec Mouri7f015182019-07-11 13:56:22 -07001050
Ady Abrahamb838aed2019-02-12 15:30:16 -08001051 mUpcomingActiveConfig = desiredActiveConfig;
1052 const auto displayId = display->getId();
1053 LOG_ALWAYS_FATAL_IF(!displayId);
1054
Ady Abraham2139f732019-11-13 18:56:40 -08001055 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001057 // TODO(b/142753666) use constrains
1058 HWC2::VsyncPeriodChangeConstraints constraints;
1059 constraints.desiredTimeNanos = systemTime();
1060 constraints.seamlessRequired = false;
1061
1062 HWC2::VsyncPeriodChangeTimeline outTimeline;
1063 auto status =
1064 getHwComposer().setActiveConfigWithConstraints(*displayId,
1065 mUpcomingActiveConfig.configId.value(),
1066 constraints, &outTimeline);
1067 if (status != NO_ERROR) {
1068 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1069 return false;
1070 }
1071
1072 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1073 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001074 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001075 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001076}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1079 Vector<ColorMode>* outColorModes) {
1080 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001081 return BAD_VALUE;
1082 }
1083
Peiyong Lina52f0292018-03-14 17:26:31 -07001084 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001085 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001086 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001087 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1088
1089 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1090 if (!displayId) {
1091 return NAME_NOT_FOUND;
1092 }
1093
Dominik Laskowski075d3172018-05-24 15:50:06 -07001094 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001095 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001096 }
Michael Wright28f24d02016-07-12 13:30:53 -07001097 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001098
1099 // If it's built-in display and the configuration claims it's not wide color capable,
1100 // filter out all wide color modes. The typical reason why this happens is that the
1101 // hardware is not good enough to support GPU composition of wide color, and thus the
1102 // OEMs choose to disable this capability.
1103 if (isInternalDisplay && !hasWideColorDisplay) {
1104 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1105 isWideColorMode);
1106 } else {
1107 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1108 }
Michael Wright28f24d02016-07-12 13:30:53 -07001109
1110 return NO_ERROR;
1111}
1112
Daniel Solomon42d04562019-01-20 21:03:19 -08001113status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1114 ui::DisplayPrimaries &primaries) {
1115 if (!displayToken) {
1116 return BAD_VALUE;
1117 }
1118
1119 // Currently we only support this API for a single internal display.
1120 if (getInternalDisplayToken() != displayToken) {
1121 return BAD_VALUE;
1122 }
1123
1124 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1125 return NO_ERROR;
1126}
1127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1129 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001130 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001131 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001133}
1134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001136 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 Vector<ColorMode> modes;
1138 getDisplayColorModes(displayToken, &modes);
1139 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1140 if (mode < ColorMode::NATIVE || !exists) {
1141 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1142 decodeColorMode(mode).c_str(), mode, displayToken.get());
1143 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001144 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001145 const auto display = getDisplayDevice(displayToken);
1146 if (!display) {
1147 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1148 decodeColorMode(mode).c_str(), mode, displayToken.get());
1149 } else if (display->isVirtual()) {
1150 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1151 decodeColorMode(mode).c_str(), mode);
1152 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001153 display->getCompositionDisplay()->setColorProfile(
1154 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1155 RenderIntent::COLORIMETRIC,
1156 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157 }
1158 }));
1159
Michael Wright28f24d02016-07-12 13:30:53 -07001160 return NO_ERROR;
1161}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001162
Galia Peycheva5492cb52019-10-30 14:13:16 +01001163status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1164 bool* outSupport) const {
1165 Mutex::Autolock _l(mStateLock);
1166
1167 if (!displayToken) {
1168 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1169 return BAD_VALUE;
1170 }
1171 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1172 if (!displayId) {
1173 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1174 displayToken.get());
1175 return NAME_NOT_FOUND;
1176 }
1177 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1178 HWC2::DisplayCapability::AutoLowLatencyMode);
1179 return NO_ERROR;
1180}
1181
1182void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1183 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1184}
1185
1186void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1187 if (!displayToken) {
1188 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1189 return;
1190 }
1191 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1192 if (!displayId) {
1193 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1194 displayToken.get());
1195 return;
1196 }
1197
1198 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1199}
1200
1201status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1202 bool* outSupport) const {
1203 Mutex::Autolock _l(mStateLock);
1204
1205 if (!displayToken) {
1206 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1207 return BAD_VALUE;
1208 }
1209 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1210 if (!displayId) {
1211 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1212 displayToken.get());
1213 return NAME_NOT_FOUND;
1214 }
1215
1216 std::vector<HWC2::ContentType> outSupportedContentTypes;
1217 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1218 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1219 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1220 return NO_ERROR;
1221}
1222
1223void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1224 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1225}
1226
1227void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1228 if (!displayToken) {
1229 ALOGE("setGameContentType() failed. Missing display token.");
1230 return;
1231 }
1232 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1233 if (!displayId) {
1234 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1235 displayToken.get());
1236 return;
1237 }
1238
1239 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1240 getHwComposer().setContentType(*displayId, type);
1241}
1242
Svetoslavd85084b2014-03-20 10:28:31 -07001243status_t SurfaceFlinger::clearAnimationFrameStats() {
1244 Mutex::Autolock _l(mStateLock);
1245 mAnimFrameTracker.clearStats();
1246 return NO_ERROR;
1247}
1248
1249status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1250 Mutex::Autolock _l(mStateLock);
1251 mAnimFrameTracker.getStats(outStats);
1252 return NO_ERROR;
1253}
1254
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001255status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1256 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001257 Mutex::Autolock _l(mStateLock);
1258
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001259 const auto display = getDisplayDeviceLocked(displayToken);
1260 if (!display) {
1261 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001262 return BAD_VALUE;
1263 }
1264
Peiyong Linfb069302018-04-25 14:34:31 -07001265 // At this point the DisplayDeivce should already be set up,
1266 // meaning the luminance information is already queried from
1267 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001268 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001269 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1270 capabilities.getDesiredMaxLuminance(),
1271 capabilities.getDesiredMaxAverageLuminance(),
1272 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001273
1274 return NO_ERROR;
1275}
1276
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001277std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1278 const DisplayDevice& display) const {
1279 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1280 // avoid repetitive HAL IPC and EDID parsing.
1281 const auto displayId = display.getId();
1282 LOG_FATAL_IF(!displayId);
1283
1284 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1285 LOG_FATAL_IF(!hwcDisplayId);
1286
1287 uint8_t port;
1288 DisplayIdentificationData data;
1289 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1290 ALOGV("%s: No identification data.", __FUNCTION__);
1291 return {};
1292 }
1293
1294 const auto info = parseDisplayIdentificationData(port, data);
1295 if (!info) {
1296 return {};
1297 }
1298 return info->deviceProductInfo;
1299}
1300
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001301status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1302 ui::PixelFormat* outFormat,
1303 ui::Dataspace* outDataspace,
1304 uint8_t* outComponentMask) const {
1305 if (!outFormat || !outDataspace || !outComponentMask) {
1306 return BAD_VALUE;
1307 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001308 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001309 if (!display || !display->getId()) {
1310 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1311 return BAD_VALUE;
1312 }
1313 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1314 outDataspace, outComponentMask);
1315}
1316
Kevin DuBois74e53772018-11-19 10:52:38 -08001317status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1318 bool enable, uint8_t componentMask,
1319 uint64_t maxFrames) const {
1320 const auto display = getDisplayDevice(displayToken);
1321 if (!display || !display->getId()) {
1322 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1323 return BAD_VALUE;
1324 }
1325
1326 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1327 componentMask, maxFrames);
1328}
1329
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001330status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1331 uint64_t maxFrames, uint64_t timestamp,
1332 DisplayedFrameStats* outStats) const {
1333 const auto display = getDisplayDevice(displayToken);
1334 if (!display || !display->getId()) {
1335 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1336 return BAD_VALUE;
1337 }
1338
1339 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1340 outStats);
1341}
1342
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001343status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1344 if (!outSupported) {
1345 return BAD_VALUE;
1346 }
1347 *outSupported = getRenderEngine().supportsProtectedContent();
1348 return NO_ERROR;
1349}
1350
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001351status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1352 bool* outIsWideColorDisplay) const {
1353 if (!displayToken || !outIsWideColorDisplay) {
1354 return BAD_VALUE;
1355 }
1356 Mutex::Autolock _l(mStateLock);
1357 const auto display = getDisplayDeviceLocked(displayToken);
1358 if (!display) {
1359 return BAD_VALUE;
1360 }
Peiyong Linff84a152019-05-17 18:36:19 -07001361
1362 // Use hasWideColorDisplay to override built-in display.
1363 const auto displayId = display->getId();
1364 if (displayId && displayId == getInternalDisplayIdLocked()) {
1365 *outIsWideColorDisplay = hasWideColorDisplay;
1366 return NO_ERROR;
1367 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001368 *outIsWideColorDisplay = display->hasWideColorGamut();
1369 return NO_ERROR;
1370}
1371
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001372status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001373 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001374 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001375
Dominik Laskowski6505f792019-09-18 11:10:05 -07001376 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1377 mEventQueue->setEventConnection(
1378 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001379 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001380 }));
1381
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001382 return NO_ERROR;
1383}
1384
1385status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001386 Mutex::Autolock lock(mStateLock);
1387 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001388}
1389
Lloyd Pique755e3192018-01-31 16:46:15 -08001390status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1391 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001392 // Try to acquire a lock for 1s, fail gracefully
1393 const status_t err = mStateLock.timedLock(s2ns(1));
1394 const bool locked = (err == NO_ERROR);
1395 if (!locked) {
1396 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1397 return TIMED_OUT;
1398 }
1399
1400 outLayers->clear();
1401 mCurrentState.traverseInZOrder([&](Layer* layer) {
1402 outLayers->push_back(layer->getLayerDebugInfo());
1403 });
1404
1405 mStateLock.unlock();
1406 return NO_ERROR;
1407}
1408
Peiyong Linc6780972018-10-28 15:24:08 -07001409status_t SurfaceFlinger::getCompositionPreference(
1410 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1411 Dataspace* outWideColorGamutDataspace,
1412 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001413 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001414 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001415 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001416 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001417 return NO_ERROR;
1418}
1419
Dan Stozaec460082018-12-17 15:35:09 -08001420status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1421 const sp<IBinder>& stopLayerHandle,
1422 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001423 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001424 return BAD_VALUE;
1425 }
1426 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001427 return NO_ERROR;
1428}
1429
Dan Stozaec460082018-12-17 15:35:09 -08001430status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001431 if (!listener) {
1432 return BAD_VALUE;
1433 }
Dan Stozaec460082018-12-17 15:35:09 -08001434 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001435 return NO_ERROR;
1436}
Dan Gittik57e63c52019-01-18 16:37:54 +00001437
1438status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1439 bool* outSupport) const {
1440 if (!displayToken || !outSupport) {
1441 return BAD_VALUE;
1442 }
1443 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1444 if (!displayId) {
1445 return NAME_NOT_FOUND;
1446 }
1447 *outSupport =
1448 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1449 return NO_ERROR;
1450}
1451
1452status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1453 float brightness) const {
1454 if (!displayToken) {
1455 return BAD_VALUE;
1456 }
1457 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1458 if (!displayId) {
1459 return NAME_NOT_FOUND;
1460 }
1461 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1462}
1463
Ady Abraham8532d012019-05-08 14:50:56 -07001464status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1465 PowerHint powerHint = static_cast<PowerHint>(hintId);
1466
1467 if (powerHint == PowerHint::INTERACTION) {
1468 mScheduler->notifyTouchEvent();
1469 }
1470
1471 return NO_ERROR;
1472}
1473
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001474// ----------------------------------------------------------------------------
1475
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001476sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001477 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001478 const auto& handle =
1479 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001480
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001481 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001482}
1483
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001484// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001485
1486void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001487 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001488}
1489
1490void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001491 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001492 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001493 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001494}
1495
1496void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001497 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001498 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001499 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001500}
1501
1502void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001503 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001504 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001505}
1506
1507status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001508 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001509 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001510}
1511
1512status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001513 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001514 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001515 if (res == NO_ERROR) {
1516 msg->wait();
1517 }
1518 return res;
1519}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001520
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001521void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001522 do {
1523 waitForEvent();
1524 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001525}
1526
Dominik Laskowski83b88212018-12-11 13:34:06 -08001527nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001528 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001529 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1530 return 0;
1531 }
1532
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001533 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001534}
1535
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001536void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001537 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001538 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001539 ATRACE_NAME("SF onVsync");
1540
Steven Thomas3cfac282017-02-06 12:29:30 -08001541 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001542 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001543 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 return;
1545 }
1546
Dominik Laskowski075d3172018-05-24 15:50:06 -07001547 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001548 return;
1549 }
1550
Dominik Laskowski075d3172018-05-24 15:50:06 -07001551 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001552 // For now, we don't do anything with external display vsyncs.
1553 return;
1554 }
1555
Alec Mourif8e689c2019-05-20 18:32:22 -07001556 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001557 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001558 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001559 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001560 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001561}
1562
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001563void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001564 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1565 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001566}
1567
Ady Abraham2139f732019-11-13 18:56:40 -08001568bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001569 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001570}
1571
Ady Abraham2139f732019-11-13 18:56:40 -08001572void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1573 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001574 const auto display = getDefaultDisplayDeviceLocked();
1575 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001576 return;
1577 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001578 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001579
Ana Krulec7d1d6832018-12-27 11:10:09 -08001580 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001581 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1582 ALOGV("Skipping config %d as it is not part of allowed configs",
1583 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001584 return;
1585 }
1586
Ady Abraham2139f732019-11-13 18:56:40 -08001587 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001588}
1589
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001590void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001591 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001592 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001593 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594
Lloyd Piqueba04e622017-12-14 17:11:26 -08001595 // Ignore events that do not have the right sequenceId.
1596 if (sequenceId != getBE().mComposerSequenceId) {
1597 return;
1598 }
1599
Steven Thomasb02664d2017-07-26 18:48:28 -07001600 // Only lock if we're not on the main thread. This function is normally
1601 // called on a hwbinder thread, but for the primary display it's called on
1602 // the main thread with the state lock already held, so don't attempt to
1603 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001604 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001605
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001606 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001607
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001608 if (std::this_thread::get_id() == mMainThreadId) {
1609 // Process all pending hot plug events immediately if we are on the main thread.
1610 processDisplayHotplugEventsLocked();
1611 }
1612
Lloyd Piqueba04e622017-12-14 17:11:26 -08001613 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001614}
1615
Ady Abraham7159f572019-10-11 11:10:18 -07001616void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001617 int32_t sequenceId, hwc2_display_t /*display*/,
1618 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1619 Mutex::Autolock lock(mStateLock);
1620 if (sequenceId != getBE().mComposerSequenceId) {
1621 return;
1622 }
1623 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001624}
1625
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001626void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1627 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1628 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1629}
1630
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001631void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001632 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001633 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001634 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001635 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001636 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001637}
1638
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001639void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001640 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001641
1642 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1643 // display power state.
1644 postMessageAsync(new LambdaMessage(
1645 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1646}
1647
1648void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1649 ATRACE_CALL();
1650
Ady Abraham27c70212019-06-11 10:52:26 -07001651 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1652
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001653 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001654 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1655 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001656 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001657 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001658 }
Mathias Agopian86303202012-07-24 22:46:10 -07001659}
1660
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001661// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001662void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001663 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001664 // Clear the drawing state so that the logic inside of
1665 // handleTransactionLocked will fire. It will determine the delta between
1666 // mCurrentState and mDrawingState and re-apply all changes when we make the
1667 // transition.
1668 mDrawingState.displays.clear();
1669 mDisplays.clear();
1670}
1671
Steven Thomas050b2c82017-03-06 11:45:16 -08001672void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001673 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001674 if (!mVrFlinger)
1675 return;
1676 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001677 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001678 return;
1679 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001680
Lloyd Pique441d5042018-10-18 16:49:51 -07001681 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001682 ALOGE("Vr flinger is only supported for remote hardware composer"
1683 " service connections. Ignoring request to transition to vr"
1684 " flinger.");
1685 mVrFlingerRequestsDisplay = false;
1686 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001687 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001688
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001689 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690
Steven Thomas0123ac62018-07-12 11:32:34 -07001691 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001692 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001693
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001694 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001695
1696 // Clear out all the output layers from the composition engine for all
1697 // displays before destroying the hardware composer interface. This ensures
1698 // any HWC layers are destroyed through that interface before it becomes
1699 // invalid.
1700 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001701 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001702 }
1703
Steven Thomas0123ac62018-07-12 11:32:34 -07001704 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1705 // called below. Clear the reference now so we don't accidentally use it
1706 // later.
1707 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001708
Steven Thomasb02664d2017-07-26 18:48:28 -07001709 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001710 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001711 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001712
Steven Thomasb02664d2017-07-26 18:48:28 -07001713 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001714 // Delete the current instance before creating the new one
1715 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1716 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1717 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001718 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001719
Lloyd Pique441d5042018-10-18 16:49:51 -07001720 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001721 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001722
1723 if (vrFlingerRequestsDisplay) {
1724 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001725 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001726
1727 mVisibleRegionsDirty = true;
1728 invalidateHwcGeometry();
1729
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001730 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001731 display = getDefaultDisplayDeviceLocked();
1732 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001733 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001734
Steven Thomasb02664d2017-07-26 18:48:28 -07001735 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001736 const nsecs_t vsyncPeriod = getVsyncPeriod();
1737 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001738
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001739 // The present fences returned from vr_hwc are not an accurate
1740 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001741 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001742
Steven Thomasb02664d2017-07-26 18:48:28 -07001743 // Use phase of 0 since phase is not known.
1744 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001745 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001746 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001747
Ana Krulecc2870422019-01-29 19:00:58 -08001748 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001749
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001750 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001751 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001752}
1753
Ady Abraham11579302019-09-19 12:35:58 -07001754bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1755 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001756 // We are storing the last 2 present fences. If sf's phase offset is to be
1757 // woken up before the actual vsync but targeting the next vsync, we need to check
1758 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001759 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1760 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001761
Ady Abraham11579302019-09-19 12:35:58 -07001762 if (fence == Fence::NO_FENCE) {
1763 return false;
1764 }
1765
1766 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1767 fence->wait(graceTimeMs);
1768 }
1769
1770 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001771}
1772
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001773void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001774 DisplayStatInfo stats;
1775 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001776 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001777 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001778 mExpectedPresentTime.store(
1779 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001780}
1781
Dominik Laskowski22488f62019-03-28 09:53:04 -07001782void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001783 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001784 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001785 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001786 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001787 // calculate the expected present time once and use the cached
1788 // value throughout this frame to make sure all layers are
1789 // seeing this same value.
1790 populateExpectedPresentTime();
1791
Ady Abraham11579302019-09-19 12:35:58 -07001792 // When Backpressure propagation is enabled we want to give a small grace period
1793 // for the present fence to fire instead of just giving up on this frame to handle cases
1794 // where present fence is just about to get signaled.
1795 const int graceTimeForPresentFenceMs =
1796 (mPropagateBackpressure &&
1797 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1798 ? 1
1799 : 0;
1800 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1801 previousFrameMissed(
1802 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001803 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1804 mHadDeviceComposition && frameMissed};
1805 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1806 mHadClientComposition && frameMissed};
1807
Alec Mouricc0fc602019-02-26 21:45:19 -08001808 if (frameMissed) {
1809 mFrameMissedCount++;
1810 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001811 if (mMissedFrameJankCount == 0) {
1812 mMissedFrameJankStart = systemTime();
1813 }
1814 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001815 }
1816
Alec Mouri40189b02019-03-05 15:07:54 -08001817 if (hwcFrameMissed) {
1818 mHwcFrameMissedCount++;
1819 }
1820
1821 if (gpuFrameMissed) {
1822 mGpuFrameMissedCount++;
1823 }
1824
Ady Abrahamadb9a992019-09-19 21:21:55 +00001825 if (frameMissed && mPropagateBackpressure) {
1826 if ((hwcFrameMissed && !gpuFrameMissed) ||
1827 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001828 signalLayerUpdate();
1829 break;
1830 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001831 }
Dan Stoza50182882016-07-08 12:02:20 -07001832
Alec Mouri989ddbe2020-02-06 09:26:19 -08001833 // Our jank window is always at least 100ms since we missed a
1834 // frame...
1835 static constexpr nsecs_t kMinJankyDuration =
1836 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1837 // ...but if it's larger than 1s then we missed the trace cutoff.
1838 static constexpr nsecs_t kMaxJankyDuration =
1839 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1840 // If we're in a user build then don't push any atoms
1841 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1842 const auto displayDevice = getDefaultDisplayDeviceLocked();
1843 // Only report jank when the display is on, as displays in DOZE
1844 // power mode may operate at a different frame rate than is
1845 // reported in their config, which causes noticeable (but less
1846 // severe) jank.
1847 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1848 const nsecs_t currentTime = systemTime();
1849 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1850 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1851 ATRACE_NAME("Jank detected");
1852 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1853 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1854 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1855 jankyDurationMillis, mMissedFrameJankCount);
1856 }
1857
1858 // We either reported a jank event or we missed the trace
1859 // window, so clear counters here.
1860 if (jankDuration > kMinJankyDuration) {
1861 mMissedFrameJankCount = 0;
1862 mMissedFrameJankStart = 0;
1863 }
1864 }
1865 }
1866
Steven Thomas050b2c82017-03-06 11:45:16 -08001867 // Now that we're going to make it to the handleMessageTransaction()
1868 // call below it's safe to call updateVrFlinger(), which will
1869 // potentially trigger a display handoff.
1870 updateVrFlinger();
1871
Dan Stoza6b9454d2014-11-07 16:00:59 -08001872 bool refreshNeeded = handleMessageTransaction();
1873 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001874
Ana Krulecc84d09b2019-11-02 23:10:29 +01001875 // Layers need to get updated (in the previous line) before we can use them for
1876 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001877 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1878 // and may eventually call to ~Layer() if it holds the last reference
1879 {
1880 Mutex::Autolock _l(mStateLock);
1881 mScheduler->chooseRefreshRateForContent();
1882 }
1883
Ana Krulecc84d09b2019-11-02 23:10:29 +01001884 if (performSetActiveConfig()) {
1885 break;
1886 }
1887
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001888 updateCursorAsync();
1889 updateInputFlinger();
1890
Dan Stoza58784442014-12-02 16:58:17 -08001891 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001892 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001893 // Signal a refresh if a transaction modified the window state,
1894 // a new buffer was latched, or if HWC has requested a full
1895 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001896 if (mFrameStartTime <= 0) {
1897 // We should only use the time of the first invalidate
1898 // message that signals a refresh as the beginning of the
1899 // frame. Otherwise the real frame time will be
1900 // underestimated.
1901 mFrameStartTime = frameStart;
1902 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001903 signalRefresh();
1904 }
1905 break;
1906 }
1907 case MessageQueue::REFRESH: {
1908 handleMessageRefresh();
1909 break;
1910 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001911 }
1912}
1913
Dan Stoza6b9454d2014-11-07 16:00:59 -08001914bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001915 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001916 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001917
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001918 bool flushedATransaction = flushTransactionQueues();
1919
1920 bool runHandleTransaction = transactionFlags &&
1921 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1922
1923 if (runHandleTransaction) {
1924 handleTransaction(eTransactionMask);
1925 } else {
1926 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001927 }
1928
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001929 if (transactionFlushNeeded()) {
1930 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001931 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001932
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001933 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001934}
1935
Mathias Agopian4fec8732012-06-29 14:12:52 -07001936void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001938
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001939 mRefreshPending = false;
1940
Lloyd Piqueab039b52019-02-13 14:22:42 -08001941 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001942 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001943 for (const auto& [_, display] : mDisplays) {
1944 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1945 }
1946 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001947 if (auto layerFE = layer->getCompositionEngineLayerFE())
1948 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001949 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001950 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1951 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001952 if (auto layerFE = layer->getCompositionEngineLayerFE())
1953 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001954 }
1955
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001956 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001957 refreshArgs.outputColorSetting = useColorManagement
1958 ? mDisplayColorSetting
1959 : compositionengine::OutputColorSetting::kUnmanaged;
1960 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1961 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001962
1963 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1964 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001965 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001966
1967 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1968 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1969 mDrawingState.colorMatrixChanged = false;
1970 }
1971
1972 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1973
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001974 if (mDebugRegion != 0) {
1975 refreshArgs.devOptFlashDirtyRegionsDelay =
1976 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1977 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001978
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001979 mGeometryInvalid = false;
1980
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001981 // Store the present time just before calling to the composition engine so we could notify
1982 // the scheduler.
1983 const auto presentTime = systemTime();
1984
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001985 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001986 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1987 // Reset the frame start time now that we've recorded this frame.
1988 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001989
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001990 mScheduler->onDisplayRefreshed(presentTime);
1991
David Sodmanfa9b2af2017-12-24 13:28:59 -08001992 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001993 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001994
Lloyd Pique66d68602019-02-13 14:23:31 -08001995 mHadClientComposition =
1996 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1997 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001998 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1999 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002000 });
2001 mHadDeviceComposition =
2002 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2003 auto& displayDevice = tokenDisplayPair.second;
2004 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2005 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002006 mReusedClientComposition =
2007 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2008 auto& displayDevice = tokenDisplayPair.second;
2009 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2010 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002011
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002012 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002013
David Sodman7e4ae112018-02-09 15:02:28 -08002014 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002015 if (mVisibleRegionsDirty) {
2016 mVisibleRegionsDirty = false;
2017 if (mTracingEnabled) {
2018 mTracing.notify("visibleRegionsDirty");
2019 }
2020 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002021
2022 if (mCompositionEngine->needsAnotherUpdate()) {
2023 signalLayerUpdate();
2024 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002026
David Sodmanfa9b2af2017-12-24 13:28:59 -08002027
2028bool SurfaceFlinger::handleMessageInvalidate() {
2029 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002030 bool refreshNeeded = handlePageFlip();
2031
Vishnu Nair4351ad52019-02-11 14:13:02 -08002032 if (mVisibleRegionsDirty) {
2033 computeLayerBounds();
2034 }
2035
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002036 for (auto& layer : mLayersPendingRefresh) {
2037 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002038 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002039 invalidateLayerStack(layer, visibleReg);
2040 }
2041 mLayersPendingRefresh.clear();
2042 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002043}
2044
Ana Krulece588e312018-09-18 12:32:24 -07002045void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2046 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047 // Update queue of past composite+present times and determine the
2048 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002049 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002051 while (!getBE().mCompositePresentTimes.empty()) {
2052 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053 // Cached values should have been updated before calling this method,
2054 // which helps avoid duplicate syscalls.
2055 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2056 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2057 break;
2058 }
2059 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002060 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061 }
2062
2063 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002064 while (getBE().mCompositePresentTimes.size() > 16) {
2065 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066 }
2067
Ana Krulece588e312018-09-18 12:32:24 -07002068 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002069}
2070
Ana Krulece588e312018-09-18 12:32:24 -07002071void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2072 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 // Integer division and modulo round toward 0 not -inf, so we need to
2074 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002075 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2076 ? (stats.vsyncPeriod -
2077 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2078 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002079
Ady Abraham9e16a482019-12-03 17:19:41 -08002080 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002081 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002082 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002083 }
2084
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002085 // Snap the latency to a value that removes scheduling jitter from the
2086 // composition and present times, which often have >1ms of jitter.
2087 // Reducing jitter is important if an app attempts to extrapolate
2088 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002089 // Snapping also allows an app to precisely calculate
2090 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002091 nsecs_t bias = stats.vsyncPeriod / 2;
2092 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2093 nsecs_t snappedCompositeToPresentLatency =
2094 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002095
David Sodman99974d22017-11-28 12:04:33 -08002096 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002097 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2098 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002099 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002100}
2101
David Sodman2b406362017-12-15 13:33:47 -08002102void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002103{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 ATRACE_CALL();
2105 ALOGV("postComposition");
2106
Brian Andersonf6386862016-10-31 16:34:13 -07002107 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002108 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002109 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002110 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002111 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002112 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113
David Sodman73beded2017-11-15 11:56:06 -08002114 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002115 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002116 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002117 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002118 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2119 ->getRenderSurface()
2120 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002121 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002122 } else {
2123 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2124 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002125
David Sodman73beded2017-11-15 11:56:06 -08002126 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002127 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2128 mPreviousPresentFences[0] = displayDevice
2129 ? getHwComposer().getPresentFence(*displayDevice->getId())
2130 : Fence::NO_FENCE;
2131 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002132 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002133
Ana Krulece588e312018-09-18 12:32:24 -07002134 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002135 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002136
Lloyd Piqueab039b52019-02-13 14:22:42 -08002137 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2138 // be sampled a little later than when we started doing work for this frame,
2139 // but that should be okay since updateCompositorTiming has snapping logic.
2140 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2141 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002142 CompositorTiming compositorTiming;
2143 {
David Sodman99974d22017-11-28 12:04:33 -08002144 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2145 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002146 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002147
Edgar Arriaga844fa672020-01-16 14:21:42 -08002148 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002149 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2150 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002151 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002152 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002153 }
Robert Carr2047fae2016-11-28 14:09:09 -08002154 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002155
Ady Abraham92fa2f42020-02-11 15:33:56 -08002156 if (displayDevice && displayDevice->isPrimary() &&
2157 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002158 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002159 }
2160
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002161 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002162 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2163 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002164 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002165 }
2166 }
2167
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002168 if (mAnimCompositionPending) {
2169 mAnimCompositionPending = false;
2170
Brian Anderson4e606e32017-03-16 15:34:57 -07002171 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002172 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002173 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002174 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002175 // The HWC doesn't support present fences, so use the refresh
2176 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002177 const nsecs_t presentTime =
2178 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002179 mAnimFrameTracker.setActualPresentTime(presentTime);
2180 }
2181 mAnimFrameTracker.advanceFrame();
2182 }
Dan Stozab90cf072015-03-05 11:05:59 -08002183
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002184 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002185 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002186 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002187 }
2188
Vishnu Nair9b079a22020-01-21 14:36:08 -08002189 if (mReusedClientComposition) {
2190 mTimeStats->incrementClientCompositionReusedFrames();
2191 }
2192
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002193 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002194
Alec Mouri717bcb62020-02-10 17:07:19 -08002195 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2196 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2197 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2198
Lloyd Pique32cbe282018-10-19 13:09:22 -07002199 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2200 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002201 return;
2202 }
2203
2204 nsecs_t currentTime = systemTime();
2205 if (mHasPoweredOff) {
2206 mHasPoweredOff = false;
2207 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002208 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002209 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002210 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2211 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002212 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002213 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002214 }
David Sodman4a36e932017-11-07 14:29:47 -08002215 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002216 }
David Sodman4a36e932017-11-07 14:29:47 -08002217 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002218
2219 {
2220 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002221 if (mTexturePool.size() < mTexturePoolSize) {
2222 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002223 const size_t offset = mTexturePool.size();
2224 mTexturePool.resize(mTexturePoolSize);
2225 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2226 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002227 } else if (mTexturePool.size() > mTexturePoolSize) {
2228 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2229 const size_t offset = mTexturePoolSize;
2230 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2231 mTexturePool.resize(mTexturePoolSize);
2232 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002233 }
2234 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002235
Ady Abrahambe0f9482019-04-24 15:41:53 -07002236 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002237 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002238
Kevin DuBois413287f2019-02-25 08:46:47 -08002239 if (mLumaSampling && mRegionSamplingThread) {
2240 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002241 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002242
2243 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2244 // side-effect of getTotalSize(), so we check that again here
2245 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002246 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002247 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2248 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002249}
2250
Vishnu Nair4351ad52019-02-11 14:13:02 -08002251void SurfaceFlinger::computeLayerBounds() {
2252 for (const auto& pair : mDisplays) {
2253 const auto& displayDevice = pair.second;
2254 const auto display = displayDevice->getCompositionDisplay();
2255 for (const auto& layer : mDrawingState.layersSortedByZ) {
2256 // only consider the layers on the given layer stack
2257 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002258 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002259 }
2260
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002261 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2262 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002263 }
2264 }
2265}
2266
David Sodmanfa9b2af2017-12-24 13:28:59 -08002267void SurfaceFlinger::postFrame()
2268{
2269 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002270 const auto display = getDefaultDisplayDeviceLocked();
2271 if (display && getHwComposer().isConnected(*display->getId())) {
2272 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2274 logFrameStats();
2275 }
2276 }
2277}
2278
Mathias Agopian87baae12012-07-31 12:38:26 -07002279void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002280{
Mathias Agopian841cde52012-03-01 15:44:37 -08002281 ATRACE_CALL();
2282
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002283 // here we keep a copy of the drawing state (that is the state that's
2284 // going to be overwritten by handleTransactionLocked()) outside of
2285 // mStateLock so that the side-effects of the State assignment
2286 // don't happen with mStateLock held (which can cause deadlocks).
2287 State drawingState(mDrawingState);
2288
Mathias Agopianca4d3602011-05-19 15:38:14 -07002289 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002290 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291
Mathias Agopianca4d3602011-05-19 15:38:14 -07002292 // Here we're guaranteed that some transaction flags are set
2293 // so we can call handleTransactionLocked() unconditionally.
2294 // We call getTransactionFlags(), which will also clear the flags,
2295 // with mStateLock held to guarantee that mCurrentState won't change
2296 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002297
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002298 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002299 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002300 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002301
Mathias Agopianca4d3602011-05-19 15:38:14 -07002302 mDebugInTransaction = 0;
2303 invalidateHwcGeometry();
2304 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002305}
2306
Lloyd Piqueba04e622017-12-14 17:11:26 -08002307void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2308 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002309 const std::optional<DisplayIdentificationInfo> info =
2310 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311
Dominik Laskowski075d3172018-05-24 15:50:06 -07002312 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002313 continue;
2314 }
2315
Dominik Laskowski55c85402020-01-21 16:25:47 -08002316 const DisplayId displayId = info->id;
2317 const auto it = mPhysicalDisplayTokens.find(displayId);
2318
Lloyd Piqueba04e622017-12-14 17:11:26 -08002319 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002320 if (it == mPhysicalDisplayTokens.end()) {
2321 ALOGV("Creating display %s", to_string(displayId).c_str());
2322
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002323 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002324 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002325 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002326
Dominik Laskowski075d3172018-05-24 15:50:06 -07002327 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002328 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 state.isSecure = true; // All physical displays are currently considered secure.
2330 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002331
2332 sp<IBinder> token = new BBinder();
2333 mCurrentState.displays.add(token, state);
2334 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2335
Dominik Laskowski075d3172018-05-24 15:50:06 -07002336 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002337 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002338 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002339 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340
Dominik Laskowski55c85402020-01-21 16:25:47 -08002341 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002342 if (index >= 0) {
2343 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2344 mInterceptor->saveDisplayDeletion(state.sequenceId);
2345 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002346 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002347 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002348 }
2349
2350 processDisplayChangesLocked();
2351 }
2352
2353 mPendingHotplugEvents.clear();
2354}
2355
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002356void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002357 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2358 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002359}
2360
Lloyd Pique99d3da52018-01-22 17:48:03 -08002361sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002362 const wp<IBinder>& displayToken,
2363 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002364 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002366 auto displayId = compositionDisplay->getDisplayId();
2367 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002368 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.isSecure = state.isSecure;
2370 creationArgs.displaySurface = dispSurface;
2371 creationArgs.hasWideColorGamut = false;
2372 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002373
Dominik Laskowski55c85402020-01-21 16:25:47 -08002374 if (const auto& physical = state.physical) {
2375 creationArgs.connectionType = physical->type;
2376 }
2377
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002378 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002379 creationArgs.isPrimary = isInternalDisplay;
2380
2381 if (useColorManagement && displayId) {
2382 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002384 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387
Dominik Laskowski7e045462018-05-30 13:02:02 -07002388 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002390 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391 }
tangrobin6753a022018-08-10 10:58:54 +08002392 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 if (displayId) {
2395 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002397 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002398 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399
Lloyd Pique90c115d2018-09-18 21:39:42 -07002400 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002402 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404 // Make sure that composition can never be stalled by a virtual display
2405 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002406 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002407 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2409 }
2410
Dominik Laskowski718f9602019-11-09 20:01:35 -08002411 creationArgs.physicalOrientation =
2412 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002413
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002415 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002416
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002417 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002418
2419 if (maxFrameBufferAcquiredBuffers >= 3) {
2420 nativeWindowSurface->preallocateBuffers();
2421 }
2422
2423 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002424 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002425 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002427 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002428 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002429 display->getCompositionDisplay()->setColorProfile(
2430 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2431 RenderIntent::COLORIMETRIC,
2432 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 if (!state.isVirtual()) {
2434 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002435 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2436 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002437 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 display->setLayerStack(state.layerStack);
2440 display->setProjection(state.orientation, state.viewport, state.frame);
2441 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002442
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444}
2445
Lloyd Pique347200f2017-12-14 17:00:15 -08002446void SurfaceFlinger::processDisplayChangesLocked() {
2447 // here we take advantage of Vector's copy-on-write semantics to
2448 // improve performance by skipping the transaction entirely when
2449 // know that the lists are identical
2450 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2451 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2452 if (!curr.isIdenticalTo(draw)) {
2453 mVisibleRegionsDirty = true;
2454 const size_t cc = curr.size();
2455 size_t dc = draw.size();
2456
2457 // find the displays that were removed
2458 // (ie: in drawing state but not in current state)
2459 // also handle displays that changed
2460 // (ie: displays that are in both lists)
2461 for (size_t i = 0; i < dc;) {
2462 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2463 if (j < 0) {
2464 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002466 // Save display ID before disconnecting.
2467 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002468 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002469
2470 if (!display->isVirtual()) {
2471 LOG_ALWAYS_FATAL_IF(!displayId);
2472 dispatchDisplayHotplugEvent(displayId->value, false);
2473 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002474 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002475
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002476 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 } else {
2478 // this display is in both lists. see if something changed.
2479 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002480 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002481 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2482 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2483 if (state_binder != draw_binder) {
2484 // changing the surface is like destroying and
2485 // recreating the DisplayDevice, so we just remove it
2486 // from the drawing state, so that it get re-added
2487 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002489 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002491 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492 mDrawingState.displays.removeItemsAt(i);
2493 dc--;
2494 // at this point we must loop to the next item
2495 continue;
2496 }
2497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002499 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002500 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 }
2502 if ((state.orientation != draw[i].orientation) ||
2503 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002505 }
2506 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002507 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002508 if (display->isPrimary()) {
2509 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2510 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 }
2512 }
2513 }
2514 ++i;
2515 }
2516
2517 // find displays that were added
2518 // (ie: in current state but not in drawing state)
2519 for (size_t i = 0; i < cc; i++) {
2520 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2521 const DisplayDeviceState& state(curr[i]);
2522
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002523 int width = 0;
2524 int height = 0;
2525 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2526 if (state.physical) {
2527 const auto& activeConfig =
2528 getCompositionEngine().getHwComposer().getActiveConfig(
2529 state.physical->id);
2530 width = activeConfig->getWidth();
2531 height = activeConfig->getHeight();
2532 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2533 } else if (state.surface != nullptr) {
2534 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2535 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2536 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2537 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2538 int intPixelFormat;
2539 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2540 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2541 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2542 } else {
2543 // Virtual displays without a surface are dormant:
2544 // they have external state (layer stack, projection,
2545 // etc.) but no internal state (i.e. a DisplayDevice).
2546 continue;
2547 }
2548
2549 compositionengine::DisplayCreationArgsBuilder builder;
2550 if (const auto& physical = state.physical) {
2551 builder.setPhysical({physical->id, physical->type});
2552 }
2553 builder.setPixels(ui::Size(width, height));
2554 builder.setPixelFormat(pixelFormat);
2555 builder.setIsSecure(state.isSecure);
2556 builder.setLayerStackId(state.layerStack);
2557 builder.setPowerAdvisor(&mPowerAdvisor);
2558 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2559 getHwComposer().isUsingVrComposer());
2560 builder.setName(state.displayName);
2561 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2562
Lloyd Pique542307f2018-10-19 13:24:08 -07002563 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 sp<IGraphicBufferProducer> producer;
2565 sp<IGraphicBufferProducer> bqProducer;
2566 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002567 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002568
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002569 std::optional<DisplayId> displayId = compositionDisplay->getId();
2570
Dominik Laskowski663bd282018-04-19 15:26:54 -07002571 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002572 sp<VirtualDisplaySurface> vds =
2573 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2574 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002575
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002576 dispSurface = vds;
2577 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002578 } else {
2579 ALOGE_IF(state.surface != nullptr,
2580 "adding a supported display, but rendering "
2581 "surface is provided (%p), ignoring it",
2582 state.surface.get());
2583
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002584 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 producer = bqProducer;
2587 }
2588
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002589 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002590 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002591 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002592 setupNewDisplayDeviceInternal(displayToken,
2593 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002594 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002595 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002597 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002598 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002599
2600 const auto displayDevice = mDisplays[displayToken];
2601 if (displayDevice->isPrimary()) {
2602 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2603 displayDevice->getHeight());
2604 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 }
2606 }
2607 }
2608 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002609
2610 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002611}
2612
Mathias Agopian87baae12012-07-31 12:38:26 -07002613void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002614{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002615 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2616
Dan Stoza7dde5992015-05-22 09:51:44 -07002617 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002618 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002619 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002620 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002621
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 /*
2623 * Traversal of the children
2624 * (perform the transaction for each of them if needed)
2625 */
2626
Marissa Wall06255332019-03-27 13:48:27 -07002627 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002628 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002630 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631
2632 const uint32_t flags = layer->doTransaction(0);
2633 if (flags & Layer::eVisibleRegion)
2634 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002635
2636 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002637 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002638 }
Robert Carr2047fae2016-11-28 14:09:09 -08002639 });
Marissa Wall06255332019-03-27 13:48:27 -07002640 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641 }
2642
2643 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002644 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 */
2646
Mathias Agopiane57f2922012-08-09 16:29:12 -07002647 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002648 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002649 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002652 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002653 // The transform hint might have changed for some layers
2654 // (either because a display has changed, or because a layer
2655 // as changed).
2656 //
2657 // Walk through all the layers in currentLayers,
2658 // and update their transform hint.
2659 //
2660 // If a layer is visible only on a single display, then that
2661 // display is used to calculate the hint, otherwise we use the
2662 // default display.
2663 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002664 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002665 // the hint is set before we acquire a buffer from the surface texture.
2666 //
2667 // NOTE: layer transactions have taken place already, so we use their
2668 // drawing state. However, SurfaceFlinger's own transaction has not
2669 // happened yet, so we must use the current state layer list
2670 // (soon to become the drawing state list).
2671 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002672 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002673 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002674 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002675 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002676 // NOTE: we rely on the fact that layers are sorted by
2677 // layerStack first (so we don't have to traverse the list
2678 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002679 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002680 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002681 currentlayerStack = layerStack;
2682 // figure out if this layerstack is mirrored
2683 // (more than one display) if so, pick the default display,
2684 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002685 hintDisplay = nullptr;
2686 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002687 if (display->getCompositionDisplay()
2688 ->belongsInOutput(layer->getLayerStack(),
2689 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 if (hintDisplay) {
2691 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002692 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002694 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002695 }
2696 }
2697 }
2698 }
Chet Haase91d25932013-04-11 15:24:55 -07002699
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002701 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2702 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002703
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002704 // could be null when this layer is using a layerStack
2705 // that is not visible on any display. Also can occur at
2706 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002708 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002709
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002711 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002712 if (hintDisplay) {
2713 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002714 }
Robert Carr2047fae2016-11-28 14:09:09 -08002715
2716 first = false;
2717 });
Mathias Agopian84300952012-11-21 16:02:13 -08002718 }
2719
2720
Mathias Agopian3559b072012-08-15 13:46:03 -07002721 /*
2722 * Perform our own transaction if needed
2723 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724
2725 if (mLayersAdded) {
2726 mLayersAdded = false;
2727 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002728 mVisibleRegionsDirty = true;
2729 }
2730
2731 // some layers might have been removed, so
2732 // we need to update the regions they're exposing.
2733 if (mLayersRemoved) {
2734 mLayersRemoved = false;
2735 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002736 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002738 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002740 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002741 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002742 }
Robert Carr2047fae2016-11-28 14:09:09 -08002743 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 }
2745
Vishnu Nairec0ab382019-02-13 15:32:56 -08002746 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002748}
2749
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002750void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002751 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002752 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002753 return;
2754 }
2755
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002756 if (mVisibleRegionsDirty || mInputInfoChanged) {
2757 mInputInfoChanged = false;
2758 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002759 } else if (mInputWindowCommands.syncInputWindows) {
2760 // If the caller requested to sync input windows, but there are no
2761 // changes to input windows, notify immediately.
2762 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002763 }
2764
Arthur Hung6cbb9752019-09-05 16:38:18 +08002765 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002766}
2767
2768void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002769 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002770
2771 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2772 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002773 // When calculating the screen bounds we ignore the transparent region since it may
2774 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002775 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002776 }
2777 });
chaviw291d88a2019-02-14 10:33:58 -08002778
2779 mInputFlinger->setInputWindows(inputHandles,
2780 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2781 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002782}
2783
Vishnu Nairec0ab382019-02-13 15:32:56 -08002784void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002785 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002786 mPendingInputWindowCommands.clear();
2787}
2788
Riley Andrews03414a12014-07-01 14:22:59 -07002789void SurfaceFlinger::updateCursorAsync()
2790{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002791 compositionengine::CompositionRefreshArgs refreshArgs;
2792 for (const auto& [_, display] : mDisplays) {
2793 if (display->getId()) {
2794 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002795 }
2796 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002797
2798 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002799}
2800
Ady Abraham2139f732019-11-13 18:56:40 -08002801void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002802 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2803 // If this is called from the main thread mStateLock must be locked before
2804 // Currently the only way to call this function from the main thread is from
2805 // Sheduler::chooseRefreshRateForContent
2806
2807 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002808 changeRefreshRateLocked(refreshRate, event);
2809}
2810
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002811void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2812 if (mScheduler) {
2813 // In practice it's not allowed to hotplug in/out the primary display once it's been
2814 // connected during startup, but some tests do it, so just warn and return.
2815 ALOGW("Can't re-init scheduler");
2816 return;
2817 }
2818
Ady Abraham2139f732019-11-13 18:56:40 -08002819 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002820 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002821 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002822 primaryDisplayId),
2823 currentConfig);
2824 mRefreshRateStats =
2825 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2826 currentConfig, HWC_POWER_MODE_OFF);
2827 mRefreshRateStats->setConfigMode(currentConfig);
2828
Ady Abraham9e16a482019-12-03 17:19:41 -08002829 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2830
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002831 // start the EventThread
2832 mScheduler =
2833 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002834 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002835 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002836 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002837 impl::EventThread::InterceptVSyncsCallback());
2838 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002839 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002840 [this](nsecs_t timestamp) {
2841 mInterceptor->saveVSyncEvent(timestamp);
2842 });
2843
2844 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2845 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002846 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002847
2848 mRegionSamplingThread =
2849 new RegionSamplingThread(*this, *mScheduler,
2850 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002851 // Dispatch a config change request for the primary display on scheduler
2852 // initialization, so that the EventThreads always contain a reference to a
2853 // prior configuration.
2854 //
2855 // This is a bit hacky, but this avoids a back-pointer into the main SF
2856 // classes from EventThread, and there should be no run-time binder cost
2857 // anyway since there are no connected apps at this point.
2858 const nsecs_t vsyncPeriod =
2859 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2860 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2861 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002862}
2863
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864void SurfaceFlinger::commitTransaction()
2865{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002866 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002867
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002868 mTransactionPending = false;
2869 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002870 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871}
2872
Lloyd Pique58e24a32019-08-01 15:50:14 -07002873void SurfaceFlinger::commitTransactionLocked() {
2874 if (!mLayersPendingRemoval.isEmpty()) {
2875 // Notify removed layers now that they can't be drawn from
2876 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002877 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002878
2879 // Ensure any buffers set to display on any children are released.
2880 if (l->isRemovedFromCurrentState()) {
2881 l->latchAndReleaseBuffer();
2882 }
2883
2884 // If the layer has been removed and has no parent, then it will not be reachable
2885 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2886 // ensure we can copy its current to drawing state.
2887 if (!l->getParent()) {
2888 mOffscreenLayers.emplace(l.get());
2889 }
2890 }
2891 mLayersPendingRemoval.clear();
2892 }
2893
2894 // If this transaction is part of a window animation then the next frame
2895 // we composite should be considered an animation as well.
2896 mAnimCompositionPending = mAnimTransactionPending;
2897
2898 mDrawingState = mCurrentState;
2899 // clear the "changed" flags in current state
2900 mCurrentState.colorMatrixChanged = false;
2901
Edgar Arriaga844fa672020-01-16 14:21:42 -08002902 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002903 layer->commitChildList();
2904
2905 // If the layer can be reached when traversing mDrawingState, then the layer is no
2906 // longer offscreen. Remove the layer from the offscreenLayer set.
2907 if (mOffscreenLayers.count(layer)) {
2908 mOffscreenLayers.erase(layer);
2909 }
2910 });
2911
2912 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002913 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002914}
2915
Nataniel Borges2b796da2019-02-15 13:32:18 -08002916void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2917 if (mTracingEnabledChanged) {
2918 mTracingEnabled = mTracing.isEnabled();
2919 mTracingEnabledChanged = false;
2920 }
2921
2922 // Synchronize with Tracing thread
2923 std::unique_lock<std::mutex> lock;
2924 if (mTracingEnabled) {
2925 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2926 }
2927
2928 lockedOperation();
2929
2930 // Synchronize with Tracing thread
2931 if (mTracingEnabled) {
2932 lock.unlock();
2933 }
2934}
2935
chaviw74d90ad2019-04-26 14:45:26 -07002936void SurfaceFlinger::commitOffscreenLayers() {
2937 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002938 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002939 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2940 if (!trFlags) return;
2941
2942 layer->doTransaction(0);
2943 layer->commitChildList();
2944 });
2945 }
2946}
2947
Chia-I Wuab0c3192017-08-01 11:29:00 -07002948void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002949 for (const auto& [token, displayDevice] : mDisplays) {
2950 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002951 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002952 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002953 }
2954 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002955}
2956
Dan Stoza6b9454d2014-11-07 16:00:59 -08002957bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958{
Ady Abraham09bd3922019-04-08 10:44:56 -07002959 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002960 ALOGV("handlePageFlip");
2961
Brian Andersond6927fb2016-07-23 23:37:30 -07002962 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963
Mathias Agopian4fec8732012-06-29 14:12:52 -07002964 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002965 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002966 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002967
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002968 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2969
Eric Penner51c59cd2014-07-28 19:51:58 -07002970 // Store the set of layers that need updates. This set must not change as
2971 // buffers are being latched, as this could result in a deadlock.
2972 // Example: Two producers share the same command stream and:
2973 // 1.) Layer 0 is latched
2974 // 2.) Layer 0 gets a new frame
2975 // 2.) Layer 1 gets a new frame
2976 // 3.) Layer 1 is latched.
2977 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2978 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002979 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002980 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002981 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002982 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002983 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002984 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002985 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002986 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002987 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002988 } else {
2989 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002990 }
Robert Carr2047fae2016-11-28 14:09:09 -08002991 });
2992
chaviw49a108c2019-08-12 11:23:06 -07002993 // The client can continue submitting buffers for offscreen layers, but they will not
2994 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2995 // layers to ensure dequeueBuffer doesn't block indefinitely.
2996 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002997 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002998 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2999 }
3000
Lloyd Piquef2c79392018-12-20 16:23:33 -08003001 if (!mLayersWithQueuedFrames.empty()) {
3002 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3003 // writes to Layer current state. See also b/119481871
3004 Mutex::Autolock lock(mStateLock);
3005
3006 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003007 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003008 mLayersPendingRefresh.push_back(layer);
3009 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003010 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003011 if (layer->isBufferLatched()) {
3012 newDataLatched = true;
3013 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003014 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003016
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003017 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003018
3019 // If we will need to wake up at some time in the future to deal with a
3020 // queued frame that shouldn't be displayed during this vsync period, wake
3021 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003022 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003023 signalLayerUpdate();
3024 }
3025
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003026 // enter boot animation on first buffer latch
3027 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3028 ALOGI("Enter boot animation");
3029 mBootStage = BootStage::BOOTANIMATION;
3030 }
3031
Edgar Arriaga844fa672020-01-16 14:21:42 -08003032 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003033
Dan Stoza6b9454d2014-11-07 16:00:59 -08003034 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003035 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036}
3037
Mathias Agopianad456f92011-01-13 17:53:01 -08003038void SurfaceFlinger::invalidateHwcGeometry()
3039{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003041}
3042
Robert Carrc0df3122019-04-11 13:18:21 -07003043status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3044 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3045 const sp<IBinder>& parentHandle,
3046 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003047 // add this layer to the current state list
3048 {
3049 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003050 sp<Layer> parent;
3051 if (parentHandle != nullptr) {
3052 parent = fromHandle(parentHandle);
3053 if (parent == nullptr) {
3054 return NAME_NOT_FOUND;
3055 }
3056 } else {
3057 parent = parentLayer;
3058 }
3059
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003061 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003062 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003063 return NO_MEMORY;
3064 }
Robert Carrc0df3122019-04-11 13:18:21 -07003065
3066 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3067
Robert Carrb89ea9d2018-12-10 13:01:14 -08003068 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003070 } else if (parent == nullptr) {
3071 lbc->onRemovedFromCurrentState();
3072 } else if (parent->isRemovedFromCurrentState()) {
3073 parent->addChild(lbc);
3074 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003075 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003076 parent->addChild(lbc);
3077 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003078
Yiwei Zhang243b3782018-05-15 17:40:04 -07003079 if (gbc != nullptr) {
3080 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3081 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3082 mMaxGraphicBufferProducerListSize,
3083 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3084 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003085 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003086 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003087 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003088 }
3089
Mathias Agopian96f08192010-06-02 23:28:45 -07003090 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003091 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003092
Dan Stoza7d89d062015-04-30 13:29:25 -07003093 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003094}
3095
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003096uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003097 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003098}
3099
Mathias Agopian3f844832013-08-07 21:24:32 -07003100uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003101 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102}
3103
Mathias Agopian3f844832013-08-07 21:24:32 -07003104uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003105 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003106}
3107
3108uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003109 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003110 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003111 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003113 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 }
3115 return old;
3116}
3117
Marissa Wall713b63f2018-10-17 15:42:43 -07003118bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003119 // to prevent onHandleDestroyed from being called while the lock is held,
3120 // we must keep a copy of the transactions (specifically the composer
3121 // states) around outside the scope of the lock
3122 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003123 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003124 {
3125 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003126
Valerie Haufce31b82019-04-30 16:41:14 -07003127 auto it = mTransactionQueues.begin();
3128 while (it != mTransactionQueues.end()) {
3129 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003130
Valerie Haufce31b82019-04-30 16:41:14 -07003131 while (!transactionQueue.empty()) {
3132 const auto& transaction = transactionQueue.front();
3133 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003134 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003135 transaction.states)) {
3136 setTransactionFlags(eTransactionFlushNeeded);
3137 break;
3138 }
3139 transactions.push_back(transaction);
3140 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3141 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003142 transaction.buffer, transaction.postTime,
3143 transaction.privileged, transaction.hasListenerCallbacks,
3144 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003145 transactionQueue.pop();
3146 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003147 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003148
Valerie Haufce31b82019-04-30 16:41:14 -07003149 if (transactionQueue.empty()) {
3150 it = mTransactionQueues.erase(it);
3151 mTransactionCV.broadcast();
3152 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003153 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003154 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003155 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003156 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003157 return flushedATransaction;
3158}
3159
3160bool SurfaceFlinger::transactionFlushNeeded() {
3161 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003162}
3163
chaviwca27f252018-02-06 16:46:39 -08003164
Marissa Wall17b4e452018-12-26 16:32:34 -08003165bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003166 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003167 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003168 if (!useCachedExpectedPresentTime)
3169 populateExpectedPresentTime();
3170
3171 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003172 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3173 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3174 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3175 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3176 return false;
3177 }
3178
Marissa Wall713b63f2018-10-17 15:42:43 -07003179 for (const ComposerState& state : states) {
3180 const layer_state_t& s = state.state;
3181 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3182 continue;
3183 }
3184 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003185 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003186 }
3187 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003188 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003189}
3190
Valerie Hau9dab9732019-08-20 09:29:25 -07003191void SurfaceFlinger::setTransactionState(
3192 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3193 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3194 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3195 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003196 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003197
Valerie Haubc6ddb12019-03-08 11:10:15 -08003198 const int64_t postTime = systemTime();
3199
Robert Carr14167e02019-02-13 13:50:55 -08003200 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3201
Mathias Agopian698c0872011-06-28 19:09:31 -07003202 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003203
Marissa Wall713b63f2018-10-17 15:42:43 -07003204 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003205 auto itr = mTransactionQueues.find(applyToken);
3206 // if this is an animation frame, wait until prior animation frame has
3207 // been applied by SF
3208 if (flags & eAnimation) {
3209 while (itr != mTransactionQueues.end()) {
3210 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3211 if (CC_UNLIKELY(err != NO_ERROR)) {
3212 ALOGW_IF(err == TIMED_OUT,
3213 "setTransactionState timed out "
3214 "waiting for animation frame to apply");
3215 break;
3216 }
3217 itr = mTransactionQueues.find(applyToken);
3218 }
3219 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003220
3221 // Expected present time is computed and cached on invalidate, so it may be stale.
3222 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3223 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003224 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003225 uncacheBuffer, postTime, privileged,
3226 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003227 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003228 return;
3229 }
3230
Valerie Haubc6ddb12019-03-08 11:10:15 -08003231 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003232 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3233 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003234}
3235
Valerie Hau9dab9732019-08-20 09:29:25 -07003236void SurfaceFlinger::applyTransactionState(
3237 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3238 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3239 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3240 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3241 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003242 uint32_t transactionFlags = 0;
3243
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 if (flags & eAnimation) {
3245 // For window updates that are part of an animation we must wait for
3246 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003247 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003248 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003249 if (CC_UNLIKELY(err != NO_ERROR)) {
3250 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003251 // caller after a few seconds.
3252 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3253 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003254 mAnimTransactionPending = false;
3255 break;
3256 }
3257 }
3258 }
3259
chaviwca27f252018-02-06 16:46:39 -08003260 for (const DisplayState& display : displays) {
3261 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003262 }
3263
Valerie Hau9dab9732019-08-20 09:29:25 -07003264 // start and end registration for listeners w/ no surface so they can get their callback. Note
3265 // that listeners with SurfaceControls will start registration during setClientStateLocked
3266 // below.
3267 for (const auto& listener : listenerCallbacks) {
3268 mTransactionCompletedThread.startRegistration(listener);
3269 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003270 }
3271
Valerie Hau9dab9732019-08-20 09:29:25 -07003272 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003273 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003274 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003275 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3276 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003277 }
3278
Valerie Hau9dab9732019-08-20 09:29:25 -07003279 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003280 mTransactionCompletedThread.endRegistration(listenerCallback);
3281 }
3282
Marissa Walle2ffb422018-10-12 11:33:52 -07003283 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003284 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003285 mTransactionCompletedThread.sendCallbacks();
3286 }
3287 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003288
chaviw273171b2018-12-26 11:46:30 -08003289 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3290
Marissa Wall947d34e2019-03-29 14:03:53 -07003291 if (uncacheBuffer.isValid()) {
3292 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003293 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003294 }
3295
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003296 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3297 // anyway. This can be used as a flush mechanism for previous async transactions.
3298 // Empty animation transaction can be used to simulate back-pressure, so also force a
3299 // transaction for empty animation transactions.
3300 if (transactionFlags == 0 &&
3301 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003302 transactionFlags = eTransactionNeeded;
3303 }
3304
Marissa Wall06255332019-03-27 13:48:27 -07003305 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3306 // so we don't have to wake up again next frame to preform an uneeded traversal.
3307 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3308 transactionFlags = transactionFlags & (~eTraversalNeeded);
3309 mTraversalNeededMainThread = true;
3310 }
3311
Mathias Agopian386aa982011-11-07 21:58:03 -08003312 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003313 if (mInterceptor->isEnabled()) {
3314 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003315 }
Irvel468051e2016-06-13 16:44:44 -07003316
Mathias Agopian386aa982011-11-07 21:58:03 -08003317 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003318 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3319 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003320 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003321
3322 // if this is a synchronous transaction, wait for it to take effect
3323 // before returning.
3324 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003325 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003326 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003327 if (flags & eAnimation) {
3328 mAnimTransactionPending = true;
3329 }
chaviw4fe36852019-04-15 16:25:49 -07003330 if (mPendingInputWindowCommands.syncInputWindows) {
3331 mPendingSyncInputWindows = true;
3332 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003333
3334 // applyTransactionState can be called by either the main SF thread or by
3335 // another process through setTransactionState. While a given process may wish
3336 // to wait on synchronous transactions, the main SF thread should never
3337 // be blocked. Therefore, we only wait if isMainThread is false.
3338 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003339 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3340 if (CC_UNLIKELY(err != NO_ERROR)) {
3341 // just in case something goes wrong in SF, return to the
3342 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003343 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3344 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003345 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003346 break;
3347 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349 }
3350}
3351
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003352uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3353 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3354 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003355
Mathias Agopiane57f2922012-08-09 16:29:12 -07003356 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003357 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3358
3359 const uint32_t what = s.what;
3360 if (what & DisplayState::eSurfaceChanged) {
3361 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3362 state.surface = s.surface;
3363 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003364 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003365 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003366 if (what & DisplayState::eLayerStackChanged) {
3367 if (state.layerStack != s.layerStack) {
3368 state.layerStack = s.layerStack;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 }
3372 if (what & DisplayState::eDisplayProjectionChanged) {
3373 if (state.orientation != s.orientation) {
3374 state.orientation = s.orientation;
3375 flags |= eDisplayTransactionNeeded;
3376 }
3377 if (state.frame != s.frame) {
3378 state.frame = s.frame;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 if (state.viewport != s.viewport) {
3382 state.viewport = s.viewport;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 }
3386 if (what & DisplayState::eDisplaySizeChanged) {
3387 if (state.width != s.width) {
3388 state.width = s.width;
3389 flags |= eDisplayTransactionNeeded;
3390 }
3391 if (state.height != s.height) {
3392 state.height = s.height;
3393 flags |= eDisplayTransactionNeeded;
3394 }
3395 }
3396
Mathias Agopiane57f2922012-08-09 16:29:12 -07003397 return flags;
3398}
3399
Robert Carr14167e02019-02-13 13:50:55 -08003400bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003401 IPCThreadState* ipc = IPCThreadState::self();
3402 const int pid = ipc->getCallingPid();
3403 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003404 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003405 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003406 return false;
3407 }
3408 return true;
3409}
3410
Marissa Wall3dad52d2019-03-22 14:03:19 -07003411uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003412 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3413 bool privileged,
3414 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003415 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003416
Valerie Hau9dab9732019-08-20 09:29:25 -07003417 for (auto& listener : s.listeners) {
3418 // note that startRegistration will not re-register if the listener has
3419 // already be registered for a prior surface control
3420 mTransactionCompletedThread.startRegistration(listener);
3421 listenerCallbacks.insert(listener);
3422 }
3423
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003424 sp<Layer> layer = nullptr;
3425 if (s.surface) {
3426 layer = fromHandle(s.surface);
3427 } else {
3428 // The client may provide us a null handle. Treat it as if the layer was removed.
3429 ALOGW("Attempt to set client state with a null layer handle");
3430 }
chaviw8b3871a2017-11-01 17:41:01 -07003431 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003432 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003433 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003434 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003435 }
chaviw8b3871a2017-11-01 17:41:01 -07003436 return 0;
3437 }
3438
chaviw8b3871a2017-11-01 17:41:01 -07003439 uint32_t flags = 0;
3440
Garfield Tan8a3083e2018-12-03 13:21:07 -08003441 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003442
3443 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3444 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003445 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003446 layer->pushPendingState();
3447 }
3448
Valerie Hau871d6352020-01-29 08:44:02 -08003449 // Only set by BLAST adapter layers
3450 if (what & layer_state_t::eProducerDisconnect) {
3451 layer->onDisconnect();
3452 }
3453
chaviw8b3871a2017-11-01 17:41:01 -07003454 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003455 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003456 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003457 }
chaviw8b3871a2017-11-01 17:41:01 -07003458 }
3459 if (what & layer_state_t::eLayerChanged) {
3460 // NOTE: index needs to be calculated before we update the state
3461 const auto& p = layer->getParent();
3462 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003463 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003464 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003465 mCurrentState.layersSortedByZ.removeAt(idx);
3466 mCurrentState.layersSortedByZ.add(layer);
3467 // we need traversal (state changed)
3468 // AND transaction (list changed)
3469 flags |= eTransactionNeeded|eTraversalNeeded;
3470 }
chaviw8b3871a2017-11-01 17:41:01 -07003471 } else {
3472 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003473 flags |= eTransactionNeeded|eTraversalNeeded;
3474 }
3475 }
chaviw8b3871a2017-11-01 17:41:01 -07003476 }
3477 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003478 // NOTE: index needs to be calculated before we update the state
3479 const auto& p = layer->getParent();
3480 if (p == nullptr) {
3481 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3482 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3483 mCurrentState.layersSortedByZ.removeAt(idx);
3484 mCurrentState.layersSortedByZ.add(layer);
3485 // we need traversal (state changed)
3486 // AND transaction (list changed)
3487 flags |= eTransactionNeeded|eTraversalNeeded;
3488 }
3489 } else {
3490 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3491 flags |= eTransactionNeeded|eTraversalNeeded;
3492 }
chaviw8b3871a2017-11-01 17:41:01 -07003493 }
3494 }
3495 if (what & layer_state_t::eSizeChanged) {
3496 if (layer->setSize(s.w, s.h)) {
3497 flags |= eTraversalNeeded;
3498 }
3499 }
3500 if (what & layer_state_t::eAlphaChanged) {
3501 if (layer->setAlpha(s.alpha))
3502 flags |= eTraversalNeeded;
3503 }
3504 if (what & layer_state_t::eColorChanged) {
3505 if (layer->setColor(s.color))
3506 flags |= eTraversalNeeded;
3507 }
Peiyong Lind3788632018-09-18 16:01:31 -07003508 if (what & layer_state_t::eColorTransformChanged) {
3509 if (layer->setColorTransform(s.colorTransform)) {
3510 flags |= eTraversalNeeded;
3511 }
3512 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003513 if (what & layer_state_t::eBackgroundColorChanged) {
3514 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3515 flags |= eTraversalNeeded;
3516 }
3517 }
chaviw8b3871a2017-11-01 17:41:01 -07003518 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003519 // TODO: b/109894387
3520 //
3521 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3522 // rotation. To see the problem observe that if we have a square parent, and a child
3523 // of the same size, then we rotate the child 45 degrees around it's center, the child
3524 // must now be cropped to a non rectangular 8 sided region.
3525 //
3526 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3527 // private API, and the WindowManager only uses rotation in one case, which is on a top
3528 // level layer in which cropping is not an issue.
3529 //
3530 // However given that abuse of rotation matrices could lead to surfaces extending outside
3531 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3532 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3533 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003534 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003535 flags |= eTraversalNeeded;
3536 }
3537 if (what & layer_state_t::eTransparentRegionChanged) {
3538 if (layer->setTransparentRegionHint(s.transparentRegion))
3539 flags |= eTraversalNeeded;
3540 }
3541 if (what & layer_state_t::eFlagsChanged) {
3542 if (layer->setFlags(s.flags, s.mask))
3543 flags |= eTraversalNeeded;
3544 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003545 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003546 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003547 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003548 if (what & layer_state_t::eCornerRadiusChanged) {
3549 if (layer->setCornerRadius(s.cornerRadius))
3550 flags |= eTraversalNeeded;
3551 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003552 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3553 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3554 }
chaviw8b3871a2017-11-01 17:41:01 -07003555 if (what & layer_state_t::eLayerStackChanged) {
3556 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3557 // We only allow setting layer stacks for top level layers,
3558 // everything else inherits layer stack from its parent.
3559 if (layer->hasParent()) {
3560 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003561 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003562 } else if (idx < 0) {
3563 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003564 "that also does not appear in the top level layer list. Something"
3565 " has gone wrong.",
3566 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003567 } else if (layer->setLayerStack(s.layerStack)) {
3568 mCurrentState.layersSortedByZ.removeAt(idx);
3569 mCurrentState.layersSortedByZ.add(layer);
3570 // we need traversal (state changed)
3571 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003572 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003573 }
3574 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003575 if (what & layer_state_t::eDeferTransaction_legacy) {
3576 if (s.barrierHandle_legacy != nullptr) {
3577 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3578 } else if (s.barrierGbp_legacy != nullptr) {
3579 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003580 if (authenticateSurfaceTextureLocked(gbp)) {
3581 const auto& otherLayer =
3582 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003583 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003584 } else {
3585 ALOGE("Attempt to defer transaction to to an"
3586 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003587 }
3588 }
chaviw8b3871a2017-11-01 17:41:01 -07003589 // We don't trigger a traversal here because if no other state is
3590 // changed, we don't want this to cause any more work
3591 }
chaviw8b3871a2017-11-01 17:41:01 -07003592 if (what & layer_state_t::eReparentChildren) {
3593 if (layer->reparentChildren(s.reparentHandle)) {
3594 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003595 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003596 }
chaviw8b3871a2017-11-01 17:41:01 -07003597 if (what & layer_state_t::eDetachChildren) {
3598 layer->detachChildren();
3599 }
3600 if (what & layer_state_t::eOverrideScalingModeChanged) {
3601 layer->setOverrideScalingMode(s.overrideScalingMode);
3602 // We don't trigger a traversal here because if no other state is
3603 // changed, we don't want this to cause any more work
3604 }
Marissa Wall61c58622018-07-18 10:12:20 -07003605 if (what & layer_state_t::eTransformChanged) {
3606 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3607 }
3608 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3609 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3610 flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eCropChanged) {
3613 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3614 }
Marissa Wall861616d2018-10-22 12:52:23 -07003615 if (what & layer_state_t::eFrameChanged) {
3616 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3617 }
Marissa Wall61c58622018-07-18 10:12:20 -07003618 if (what & layer_state_t::eAcquireFenceChanged) {
3619 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3620 }
3621 if (what & layer_state_t::eDataspaceChanged) {
3622 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3623 }
3624 if (what & layer_state_t::eHdrMetadataChanged) {
3625 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3626 }
3627 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3628 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3629 }
3630 if (what & layer_state_t::eApiChanged) {
3631 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3632 }
3633 if (what & layer_state_t::eSidebandStreamChanged) {
3634 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3635 }
Robert Carr720e5062018-07-30 17:45:14 -07003636 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003637 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003638 layer->setInputInfo(s.inputInfo);
3639 flags |= eTraversalNeeded;
3640 } else {
3641 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3642 }
Robert Carr720e5062018-07-30 17:45:14 -07003643 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003644 if (what & layer_state_t::eMetadataChanged) {
3645 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3646 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003647 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3648 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3649 flags |= eTraversalNeeded;
3650 }
3651 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003652 if (what & layer_state_t::eShadowRadiusChanged) {
3653 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3654 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003655 if (what & layer_state_t::eFrameRateSelectionPriority) {
3656 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3657 flags |= eTraversalNeeded;
3658 }
3659 }
Steven Thomas3172e202020-01-06 19:25:30 -08003660 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003661 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3662 "SurfaceFlinger::setClientStateLocked") &&
3663 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3664 Layer::FrameRate::convertCompatibility(
3665 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003666 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003667 }
Steven Thomas3172e202020-01-06 19:25:30 -08003668 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003669 // This has to happen after we reparent children because when we reparent to null we remove
3670 // child layers from current state and remove its relative z. If the children are reparented in
3671 // the same transaction, then we have to make sure we reparent the children first so we do not
3672 // lose its relative z order.
3673 if (what & layer_state_t::eReparent) {
3674 bool hadParent = layer->hasParent();
3675 if (layer->reparent(s.parentHandleForChild)) {
3676 if (!hadParent) {
3677 mCurrentState.layersSortedByZ.remove(layer);
3678 }
3679 flags |= eTransactionNeeded | eTraversalNeeded;
3680 }
3681 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003682 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003683 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3684 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003685 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3686 }
3687 }
Marissa Wall78b72202019-03-15 14:58:34 -07003688 bool bufferChanged = what & layer_state_t::eBufferChanged;
3689 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3690 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003691 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003692 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003693 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3694 if (success) {
3695 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3696 success = ClientCache::getInstance()
3697 .registerErasedRecipient(s.cachedBuffer,
3698 wp<ClientCache::ErasedRecipient>(this));
3699 if (!success) {
3700 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3701 }
3702 }
Marissa Wall78b72202019-03-15 14:58:34 -07003703 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003704 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003705 } else if (bufferChanged) {
3706 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003707 }
Marissa Wall78b72202019-03-15 14:58:34 -07003708 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003709 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3710 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003711 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003712 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003713 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003714 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3715 // Do not put anything that updates layer state or modifies flags after
3716 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003717 return flags;
3718}
3719
chaviw273171b2018-12-26 11:46:30 -08003720uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3721 uint32_t flags = 0;
3722 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3723 flags |= eTraversalNeeded;
3724 }
3725
chaviwa911b102019-02-14 10:18:33 -08003726 if (inputWindowCommands.syncInputWindows) {
3727 flags |= eTraversalNeeded;
3728 }
3729
Vishnu Nairec0ab382019-02-13 15:32:56 -08003730 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003731 return flags;
3732}
3733
chaviwfe94a222019-08-21 13:52:59 -07003734status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3735 sp<IBinder>* outHandle) {
3736 if (!mirrorFromHandle) {
3737 return NAME_NOT_FOUND;
3738 }
3739
3740 sp<Layer> mirrorLayer;
3741 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003742 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003743
3744 {
3745 Mutex::Autolock _l(mStateLock);
3746 mirrorFrom = fromHandle(mirrorFromHandle);
3747 if (!mirrorFrom) {
3748 return NAME_NOT_FOUND;
3749 }
3750
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003751 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3752 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003753 if (result != NO_ERROR) {
3754 return result;
3755 }
3756
3757 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3758 }
3759
3760 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3761}
3762
Marissa Wall2d814fb2019-04-09 18:52:57 +00003763status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3764 uint32_t h, PixelFormat format, uint32_t flags,
3765 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003766 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003767 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3768 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003769 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003770 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003771 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003772 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003773 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003774
Robert Carrc0df3122019-04-11 13:18:21 -07003775 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3776 "Expected only one of parentLayer or parentHandle to be non-null. "
3777 "Programmer error?");
3778
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003779 status_t result = NO_ERROR;
3780
3781 sp<Layer> layer;
3782
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003783 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003784
Evan Roskya1f1e152019-01-24 16:17:46 -08003785 bool primaryDisplayOnly = false;
3786
3787 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3788 // TODO b/64227542
3789 if (metadata.has(METADATA_WINDOW_TYPE)) {
3790 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3791 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003792 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003793 primaryDisplayOnly = true;
3794 }
3795 }
3796
Mathias Agopian3165cc22012-08-08 19:42:09 -07003797 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003798 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003799 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3800 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003803 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003804 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003805 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003806 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003807 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003808 // check if buffer size is set for color layer.
3809 if (w > 0 || h > 0) {
3810 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3811 int(w), int(h));
3812 return BAD_VALUE;
3813 }
3814
Vishnu Nairfa247b12020-02-11 08:58:26 -08003815 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3816 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003817 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003818 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003819 // check if buffer size is set for container layer.
3820 if (w > 0 || h > 0) {
3821 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3822 int(w), int(h));
3823 return BAD_VALUE;
3824 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003825 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3826 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003827 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003828 default:
3829 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 break;
3831 }
3832
Dan Stoza7d89d062015-04-30 13:29:25 -07003833 if (result != NO_ERROR) {
3834 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003835 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003836
Evan Roskya1f1e152019-01-24 16:17:46 -08003837 if (primaryDisplayOnly) {
3838 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003839 }
3840
Robert Carrb89ea9d2018-12-10 13:01:14 -08003841 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003842 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3843 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003844 if (result != NO_ERROR) {
3845 return result;
3846 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003847 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003848
3849 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003850 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851}
3852
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003853std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3854 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003855
3856 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003857 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003858
Dan Stoza436ccf32018-06-21 12:10:12 -07003859 // Grab the state lock since we're accessing mCurrentState
3860 Mutex::Autolock lock(mStateLock);
3861
Cody Northropbc755282017-03-31 12:00:08 -06003862 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003863 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003864 while (matchFound) {
3865 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003866 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003867 if (layer->getName() == uniqueName) {
3868 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003869 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003870 }
3871 });
3872 }
3873
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003874 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003875 return uniqueName;
3876}
3877
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003878status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003879 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003880 LayerMetadata metadata, PixelFormat& format,
3881 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003882 sp<IGraphicBufferProducer>* gbp,
3883 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003884 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003885 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886 case PIXEL_FORMAT_TRANSPARENT:
3887 case PIXEL_FORMAT_TRANSLUCENT:
3888 format = PIXEL_FORMAT_RGBA_8888;
3889 break;
3890 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003891 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 break;
3893 }
3894
chaviwb4c6e582019-08-16 14:35:07 -07003895 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003896 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003897 args.textureName = getNewTexture();
3898 {
3899 // Grab the SF state lock during this since it's the only safe way to access
3900 // RenderEngine when creating a BufferLayerConsumer
3901 // TODO: Check if this lock is still needed here
3902 Mutex::Autolock lock(mStateLock);
3903 layer = getFactory().createBufferQueueLayer(args);
3904 }
3905
Marissa Wallfd668622018-05-10 10:21:13 -07003906 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003907 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003908 *handle = layer->getHandle();
3909 *gbp = layer->getProducer();
3910 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003912
Marissa Wallfd668622018-05-10 10:21:13 -07003913 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003914 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915}
3916
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003917status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003918 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003919 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003920 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003921 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003922 args.displayDevice = getDefaultDisplayDevice();
3923 args.textureName = getNewTexture();
3924 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003925 if (outTransformHint) {
3926 *outTransformHint = layer->getTransformHint();
3927 }
Marissa Wall61c58622018-07-18 10:12:20 -07003928 *handle = layer->getHandle();
3929 *outLayer = layer;
3930
3931 return NO_ERROR;
3932}
3933
Vishnu Nairfa247b12020-02-11 08:58:26 -08003934status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3935 uint32_t h, uint32_t flags, LayerMetadata metadata,
3936 sp<IBinder>* handle, sp<Layer>* outLayer) {
3937 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003938 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003939 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003940 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003941}
3942
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003943status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003944 uint32_t w, uint32_t h, uint32_t flags,
3945 LayerMetadata metadata, sp<IBinder>* handle,
3946 sp<Layer>* outLayer) {
3947 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003948 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003949 *handle = (*outLayer)->getHandle();
3950 return NO_ERROR;
3951}
3952
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003953void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003954 mLayersPendingRemoval.add(layer);
3955 mLayersRemoved = true;
3956 setTransactionFlags(eTransactionNeeded);
3957}
3958
Robert Carr695d5282018-12-18 15:27:58 -08003959void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003960{
Robert Carr2e102c92018-10-23 12:11:15 -07003961 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003962 // If a layer has a parent, we allow it to out-live it's handle
3963 // with the idea that the parent holds a reference and will eventually
3964 // be cleaned up. However no one cleans up the top-level so we do so
3965 // here.
3966 if (layer->getParent() == nullptr) {
3967 mCurrentState.layersSortedByZ.remove(layer);
3968 }
3969 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003970
3971 auto it = mLayersByLocalBinderToken.begin();
3972 while (it != mLayersByLocalBinderToken.end()) {
3973 if (it->second == layer) {
3974 it = mLayersByLocalBinderToken.erase(it);
3975 } else {
3976 it++;
3977 }
3978 }
3979
Robert Carr695d5282018-12-18 15:27:58 -08003980 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003981}
3982
Mathias Agopianb60314a2012-04-10 22:09:54 -07003983// ---------------------------------------------------------------------------
3984
Andy McFadden13a082e2012-08-24 10:16:42 -07003985void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003986 const auto display = getDefaultDisplayDeviceLocked();
3987 if (!display) return;
3988
3989 const sp<IBinder> token = display->getDisplayToken().promote();
3990 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003991
Jesse Hall01e29052013-02-19 16:13:35 -08003992 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003993 Vector<ComposerState> state;
3994 Vector<DisplayState> displays;
3995 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003996 d.what = DisplayState::eDisplayProjectionChanged |
3997 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003998 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003999 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004000 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004001 d.frame.makeInvalid();
4002 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004003 d.width = 0;
4004 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004005 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004006 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4007 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004008
Dominik Laskowskie9774092018-12-11 10:04:24 -08004009 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004010
Dominik Laskowski83b88212018-12-11 13:34:06 -08004011 const nsecs_t vsyncPeriod = getVsyncPeriod();
4012 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004013
Brian Andersond0010582017-03-07 13:20:31 -08004014 // Use phase of 0 since phase is not known.
4015 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004016 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004017 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004018}
4019
4020void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004021 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004022 postMessageAsync(
4023 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004024}
4025
Ady Abraham27c70212019-06-11 10:52:26 -07004026void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4027 if (mHWCVsyncState != enabled) {
4028 getHwComposer().setVsyncEnabled(displayId, enabled);
4029 mHWCVsyncState = enabled;
4030 }
4031}
4032
Dominik Laskowskie9774092018-12-11 10:04:24 -08004033void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004034 if (display->isVirtual()) {
4035 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004036 return;
4037 }
4038
Dominik Laskowski075d3172018-05-24 15:50:06 -07004039 const auto displayId = display->getId();
4040 LOG_ALWAYS_FATAL_IF(!displayId);
4041
Dominik Laskowski34157762018-10-31 13:07:19 -07004042 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004043
4044 int currentMode = display->getPowerMode();
4045 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004046 return;
4047 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004049 display->setPowerMode(mode);
4050
Lloyd Pique4dccc412018-01-22 17:21:36 -08004051 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004052 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004053 }
4054
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004055 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004056 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004057 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004058 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004059 mScheduler->onScreenAcquired(mAppConnectionHandle);
4060 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004061 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004063 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004064 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004065 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004066
4067 struct sched_param param = {0};
4068 param.sched_priority = 1;
4069 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4070 ALOGW("Couldn't set SCHED_FIFO on display on");
4071 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004072 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004073 // Turn off the display
4074 struct sched_param param = {0};
4075 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4076 ALOGW("Couldn't set SCHED_OTHER on display off");
4077 }
4078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004079 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004080 mScheduler->disableHardwareVsync(true);
4081 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004082 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004083
Ady Abraham27c70212019-06-11 10:52:26 -07004084 // Make sure HWVsync is disabled before turning off the display
4085 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4086
Dominik Laskowski075d3172018-05-24 15:50:06 -07004087 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004088 mVisibleRegionsDirty = true;
4089 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004090 } else if (mode == HWC_POWER_MODE_DOZE ||
4091 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004092 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004093 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004094 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004095 mScheduler->onScreenAcquired(mAppConnectionHandle);
4096 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004097 }
4098 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4099 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004100 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004101 mScheduler->disableHardwareVsync(true);
4102 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004103 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004105 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004106 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004107 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004108 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004109
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004110 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004111 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004112 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004113 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004114 }
4115
Dominik Laskowski34157762018-10-31 13:07:19 -07004116 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004117}
4118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004119void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004120 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004121 const auto display = getDisplayDevice(displayToken);
4122 if (!display) {
4123 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4124 displayToken.get());
4125 } else if (display->isVirtual()) {
4126 ALOGW("Attempt to set power mode %d for virtual display", mode);
4127 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004128 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004129 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004130 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004131}
4132
4133// ---------------------------------------------------------------------------
4134
Dominik Laskowskic2867142019-01-21 11:33:38 -08004135status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4136 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004137 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004138
Mathias Agopianbd115332013-04-18 16:41:04 -07004139 IPCThreadState* ipc = IPCThreadState::self();
4140 const int pid = ipc->getCallingPid();
4141 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004142
Mathias Agopianbd115332013-04-18 16:41:04 -07004143 if ((uid != AID_SHELL) &&
4144 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004145 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4146 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004148 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004149 // (this would indicate SF is stuck, but we want to be able to
4150 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004151 status_t err = mStateLock.timedLock(s2ns(1));
4152 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004153 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004154 StringAppendF(&result,
4155 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4156 "(no locks held)\n",
4157 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004158 }
4159
Dominik Laskowskic2867142019-01-21 11:33:38 -08004160 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004161 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004162 {"--dispsync"s,
4163 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004164 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004165 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4166 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4167 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4168 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4169 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4170 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004171 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004172 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4173 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004174
Dominik Laskowskic2867142019-01-21 11:33:38 -08004175 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004176
Dominik Laskowski46470112019-08-02 13:13:11 -07004177 const auto it = dumpers.find(flag);
4178 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004179 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004180 } else if (!asProto) {
4181 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004182 }
4183
Mathias Agopian9795c422009-08-26 16:36:26 -07004184 if (locked) {
4185 mStateLock.unlock();
4186 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004187
Dominik Laskowski46470112019-08-02 13:13:11 -07004188 if (it == dumpers.end()) {
4189 const LayersProto layersProto = dumpProtoFromMainThread();
4190 if (asProto) {
4191 result.append(layersProto.SerializeAsString());
4192 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004193 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004194 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4195 result.append(LayerProtoParser::layerTreeToString(layerTree));
4196 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004197 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004198 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004199 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004200 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004201 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 return NO_ERROR;
4203}
4204
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004205status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4206 if (asProto && mTracing.isEnabled()) {
4207 mTracing.writeToFileAsync();
4208 }
4209
4210 return doDump(fd, DumpArgs(), asProto);
4211}
4212
Dominik Laskowskic2867142019-01-21 11:33:38 -08004213void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004214 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004215 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004216}
4217
Dominik Laskowskic2867142019-01-21 11:33:38 -08004218void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004220
Dominik Laskowskic2867142019-01-21 11:33:38 -08004221 if (args.size() > 1) {
4222 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004223 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004224 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004225 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004226 }
Robert Carr2047fae2016-11-28 14:09:09 -08004227 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004228 } else {
4229 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004230 }
4231}
4232
Dominik Laskowskic2867142019-01-21 11:33:38 -08004233void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004234 const bool clearAll = args.size() < 2;
4235 const auto name = clearAll ? String8() : String8(args[1]);
4236
Edgar Arriaga844fa672020-01-16 14:21:42 -08004237 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004238 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004239 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004240 }
Robert Carr2047fae2016-11-28 14:09:09 -08004241 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004242
Svetoslavd85084b2014-03-20 10:28:31 -07004243 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004244}
4245
Dominik Laskowskic2867142019-01-21 11:33:38 -08004246void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4247 mTimeStats->parseArgs(asProto, args, result);
4248}
4249
Jamie Gennis6547ff42013-07-16 20:12:42 -07004250// This should only be called from the main thread. Otherwise it would need
4251// the lock and should use mCurrentState rather than mDrawingState.
4252void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004253 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004254 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004255 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004256
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004257 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004258}
4259
Yiwei Zhang5434a782018-12-05 18:06:32 -08004260void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004261 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004262
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004263 if (isLayerTripleBufferingDisabled())
4264 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004265
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4267 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4268 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4269 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4270 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4271 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004272 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004273}
4274
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004275void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004276 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004277
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004278 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004279 result.append("\n");
4280
Ady Abraham9e16a482019-12-03 17:19:41 -08004281 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004282 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004283 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004284 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004285
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004286 HwcConfigIndexType defaultConfig;
4287 float minFps, maxFps;
4288 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004289 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004290 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004291 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004292 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004293 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4294 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004295
Ana Krulecc2870422019-01-29 19:00:58 -08004296 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004297}
4298
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4300 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004301 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4302 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004303 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004304 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004305 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004306 }
David Sodman4a36e932017-11-07 14:29:47 -08004307 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004308 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004309 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004310 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4311 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004312}
4313
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004314void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4315 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004316 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4317 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004318 for (const auto& segment : history) {
4319 if (!segment.usedThirdBuffer) {
4320 stats.twoBufferTime += segment.totalTime;
4321 }
4322 if (segment.occupancyAverage < 1.0f) {
4323 stats.doubleBufferedTime += segment.totalTime;
4324 } else if (segment.occupancyAverage < 2.0f) {
4325 stats.tripleBufferedTime += segment.totalTime;
4326 }
4327 ++stats.numSegments;
4328 stats.totalTime += segment.totalTime;
4329 }
4330}
4331
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4333 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004334
4335 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4336 const size_t count = currentLayers.size();
4337 for (size_t i=0 ; i<count ; i++) {
4338 currentLayers[i]->dumpFrameEvents(result);
4339 }
4340}
4341
Yiwei Zhang5434a782018-12-05 18:06:32 -08004342void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004343 result.append("Buffering stats:\n");
4344 result.append(" [Layer name] <Active time> <Two buffer> "
4345 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004346 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004347 typedef std::tuple<std::string, float, float, float> BufferTuple;
4348 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004349 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004350 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004351 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004352 if (stats.numSegments == 0) {
4353 continue;
4354 }
4355 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4356 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4357 stats.totalTime;
4358 float doubleBufferRatio = static_cast<float>(
4359 stats.doubleBufferedTime) / stats.totalTime;
4360 float tripleBufferRatio = static_cast<float>(
4361 stats.tripleBufferedTime) / stats.totalTime;
4362 sorted.insert({activeTime, {name, twoBufferRatio,
4363 doubleBufferRatio, tripleBufferRatio}});
4364 }
4365 for (const auto& sortedPair : sorted) {
4366 float activeTime = sortedPair.first;
4367 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004368 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4369 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004370 }
4371 result.append("\n");
4372}
4373
Yiwei Zhang5434a782018-12-05 18:06:32 -08004374void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004375 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004376 const auto displayId = display->getId();
4377 if (!displayId) {
4378 continue;
4379 }
4380 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004381 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004382 continue;
4383 }
4384
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result,
4386 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4387 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004388 uint8_t port;
4389 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004390 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004391 result.append("no identification data\n");
4392 continue;
4393 }
4394
4395 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004396 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004397 continue;
4398 }
4399
4400 const auto edid = parseEdid(data);
4401 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004402 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004403 continue;
4404 }
4405
Yiwei Zhang5434a782018-12-05 18:06:32 -08004406 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004407 result.append(edid->displayName.data(), edid->displayName.length());
4408 result.append("\"\n");
4409 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004410}
4411
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004412void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4413 std::string& result) const {
4414 hwc2_display_t hwcDisplayId;
4415 uint8_t port;
4416 DisplayIdentificationData data;
4417
4418 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4419 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4420 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4421 }
4422}
4423
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004425 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4427 StringAppendF(&result, "DisplayColorSetting: %s\n",
4428 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004429
4430 // TODO: print out if wide-color mode is active or not
4431
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004432 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004433 const auto displayId = display->getId();
4434 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004435 continue;
4436 }
4437
Yiwei Zhang5434a782018-12-05 18:06:32 -08004438 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004439 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004440 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004442 }
4443
Lloyd Pique32cbe282018-10-19 13:09:22 -07004444 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, " Current color mode: %s (%d)\n",
4446 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004447 }
4448 result.append("\n");
4449}
4450
Vishnu Nair8406fd72019-07-30 11:29:31 -07004451LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004452 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004453 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4454 layer->writeToProto(layersProto, traceFlags);
4455 }
chaviw1d044282017-09-27 12:19:28 -07004456 return layersProto;
4457}
4458
Vishnu Nair0f085c62019-08-30 08:49:12 -07004459void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4460 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4461 // it.
4462 LayerProto* rootProto = layersProto.add_layers();
4463 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4464 rootProto->set_id(offscreenRootLayerId);
4465 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004466 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004467
4468 for (Layer* offscreenLayer : mOffscreenLayers) {
4469 // Add layer as child of the fake root
4470 rootProto->add_children(offscreenLayer->sequence);
4471
4472 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004473 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004474 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004475 }
4476}
4477
Vishnu Nair8406fd72019-07-30 11:29:31 -07004478LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4479 LayersProto layersProto;
4480 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4481 return layersProto;
4482}
4483
Vishnu Nair0f085c62019-08-30 08:49:12 -07004484void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4485 result.append("Offscreen Layers:\n");
4486 postMessageSync(new LambdaMessage([&]() {
4487 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004488 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004489 layer->dumpCallingUidPid(result);
4490 });
4491 }
4492 }));
4493}
4494
Dominik Laskowskic2867142019-01-21 11:33:38 -08004495void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4496 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004497 Colorizer colorizer(colorize);
4498
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004499 // figure out if we're stuck somewhere
4500 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004501 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004502 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4503
4504 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004505 * Dump library configuration.
4506 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004507
4508 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004509 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004510 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004511 appendSfConfigString(result);
4512 appendUiConfigString(result);
4513 appendGuiConfigString(result);
4514 result.append("\n");
4515
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004516 result.append("\nDisplay identification data:\n");
4517 dumpDisplayIdentificationData(result);
4518
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004519 result.append("\nWide-Color information:\n");
4520 dumpWideColorInfo(result);
4521
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004522 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004523 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004524 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004525 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004526 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004527
Andy McFadden41d67d72014-04-25 16:58:34 -07004528 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004529 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004530 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004531 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004532 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004533
Dan Stozab90cf072015-03-05 11:05:59 -08004534 dumpStaticScreenStats(result);
4535 result.append("\n");
4536
Alec Mouri40189b02019-03-05 15:07:54 -08004537 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4538 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4539 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004540
Dan Stozae77c7662016-05-13 11:37:28 -07004541 dumpBufferingStats(result);
4542
Andy McFadden4803b742012-09-24 19:07:20 -07004543 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544 * Dump the visible layer list
4545 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004546 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004547 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004548 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4549 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004550 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004551
Chia-I Wu2f884132018-09-13 15:17:58 -07004552 {
Lloyd Pique207def92019-02-28 16:09:52 -08004553 StringAppendF(&result, "Composition layers\n");
4554 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004555 auto* compositionState = layer->getCompositionState();
4556 if (!compositionState) return;
4557
4558 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4559 layer->getDebugName() ? layer->getDebugName()
4560 : "<unknown>");
4561 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004562 });
4563 }
4564
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004566 * Dump Display state
4567 */
4568
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004570 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004572 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004573 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004574 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004575 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004576
4577 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004578 * Dump CompositionEngine state
4579 */
4580
4581 mCompositionEngine->dump(result);
4582
4583 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004584 * Dump SurfaceFlinger global state
4585 */
4586
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004587 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004588 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004589 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004590
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004591 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004592
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004593 DebugEGLImageTracker::getInstance()->dump(result);
4594
Dominik Laskowski075d3172018-05-24 15:50:06 -07004595 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004596 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4597 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004598 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4599 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004600 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result,
4602 " transaction-flags : %08x\n"
4603 " gpu_to_cpu_unsupported : %d\n",
4604 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004605
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004606 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004607 displayId && getHwComposer().isConnected(*displayId)) {
4608 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result,
4610 " refresh-rate : %f fps\n"
4611 " x-dpi : %f\n"
4612 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004613 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4614 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004615 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004618
Dan Stozae22aec72016-08-01 13:20:59 -07004619 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004620 * Tracing state
4621 */
4622 mTracing.dump(result);
4623 result.append("\n");
4624
4625 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004626 * HWC layer minidump
4627 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004628 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 const auto displayId = display->getId();
4630 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004631 continue;
4632 }
4633
Yiwei Zhang5434a782018-12-05 18:06:32 -08004634 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004635 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004636 const sp<DisplayDevice> displayDevice = display;
4637 mCurrentState.traverseInZOrder(
4638 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004639 result.append("\n");
4640 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641
4642 /*
4643 * Dump HWComposer state
4644 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004645 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004646 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004647 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004648 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004650 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004651
4652 /*
4653 * Dump gralloc state
4654 */
4655 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4656 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004657
4658 /*
4659 * Dump VrFlinger state if in use.
4660 */
4661 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4662 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004664 result.append("\n");
4665 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004666
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004667 result.append(mTimeStats->miniDump());
4668 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004669}
4670
Chia-I Wu28f320b2018-05-03 11:02:56 -07004671void SurfaceFlinger::updateColorMatrixLocked() {
4672 mat4 colorMatrix;
4673 if (mGlobalSaturationFactor != 1.0f) {
4674 // Rec.709 luma coefficients
4675 float3 luminance{0.213f, 0.715f, 0.072f};
4676 luminance *= 1.0f - mGlobalSaturationFactor;
4677 mat4 saturationMatrix = mat4(
4678 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4679 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4680 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4681 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4682 );
4683 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4684 } else {
4685 colorMatrix = mClientColorMatrix * mDaltonizer();
4686 }
4687
4688 if (mCurrentState.colorMatrix != colorMatrix) {
4689 mCurrentState.colorMatrix = colorMatrix;
4690 mCurrentState.colorMatrixChanged = true;
4691 setTransactionFlags(eTransactionNeeded);
4692 }
4693}
4694
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004695status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696#pragma clang diagnostic push
4697#pragma clang diagnostic error "-Wswitch-enum"
4698 switch (static_cast<ISurfaceComposerTag>(code)) {
4699 // These methods should at minimum make sure that the client requested
4700 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004701 case BOOT_FINISHED:
4702 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004703 case CREATE_DISPLAY:
4704 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004705 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004706 case GET_ANIMATION_FRAME_STATS:
4707 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004708 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004709 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004710 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004711 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4712 case SET_AUTO_LOW_LATENCY_MODE:
4713 case GET_GAME_CONTENT_TYPE_SUPPORT:
4714 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004715 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004716 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004717 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004718 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004719 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004720 case NOTIFY_POWER_HINT:
4721 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004722 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4723 IPCThreadState* ipc = IPCThreadState::self();
4724 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4725 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004726 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004727 }
Robert Carr1db73f62016-12-21 12:58:51 -08004728 return OK;
4729 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004730 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004731 IPCThreadState* ipc = IPCThreadState::self();
4732 const int pid = ipc->getCallingPid();
4733 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004734 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4735 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004736 return PERMISSION_DENIED;
4737 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004739 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004740 // Used by apps to hook Choreographer to SurfaceFlinger.
4741 case CREATE_DISPLAY_EVENT_CONNECTION:
4742 // The following calls are currently used by clients that do not
4743 // request necessary permissions. However, they do not expose any secret
4744 // information, so it is OK to pass them.
4745 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004746 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004747 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004748 case GET_PHYSICAL_DISPLAY_IDS:
4749 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004750 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004751 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004752 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004753 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004754 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 case GET_DISPLAY_STATS:
4756 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4757 // Calling setTransactionState is safe, because you need to have been
4758 // granted a reference to Client* and Handle* to do anything with it.
4759 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004760 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004761 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004762 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004763 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004764 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004765 // setFrameRate() is deliberately available for apps to call without any
4766 // special permissions.
4767 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004768 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4769 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004770 return OK;
4771 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004772 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004773 case CAPTURE_SCREEN:
4774 case ADD_REGION_SAMPLING_LISTENER:
4775 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004776 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004777 IPCThreadState* ipc = IPCThreadState::self();
4778 const int pid = ipc->getCallingPid();
4779 const int uid = ipc->getCallingUid();
4780 if ((uid != AID_GRAPHICS) &&
4781 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4782 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4783 return PERMISSION_DENIED;
4784 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004785 return OK;
4786 }
chaviw93df2ea2019-04-30 16:45:12 -07004787 case CAPTURE_SCREEN_BY_ID: {
4788 IPCThreadState* ipc = IPCThreadState::self();
4789 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004790 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004791 return OK;
4792 }
4793 return PERMISSION_DENIED;
4794 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004795 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796
4797 // These codes are used for the IBinder protocol to either interrogate the recipient
4798 // side of the transaction for its canonical interface descriptor or to dump its state.
4799 // We let them pass by default.
4800 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4801 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4802 code == IBinder::SYSPROPS_TRANSACTION) {
4803 return OK;
4804 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004805 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004806 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004807 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004808 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4809 return OK;
4810 }
4811 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4812 return PERMISSION_DENIED;
4813#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004814}
4815
Ana Krulec13be8ad2018-08-21 02:43:56 +00004816status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4817 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004818 status_t credentialCheck = CheckTransactCodeCredentials(code);
4819 if (credentialCheck != OK) {
4820 return credentialCheck;
4821 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004822
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004823 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4824 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004825 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004826 IPCThreadState* ipc = IPCThreadState::self();
4827 const int uid = ipc->getCallingUid();
4828 if (CC_UNLIKELY(uid != AID_SYSTEM
4829 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004830 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004831 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004832 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 return PERMISSION_DENIED;
4834 }
4835 int n;
4836 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004837 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004838 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004839 return NO_ERROR;
4840 case 1002: // SHOW_UPDATES
4841 n = data.readInt32();
4842 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004843 invalidateHwcGeometry();
4844 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004845 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004846 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004847 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004848 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004849 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004850 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004851 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004852 setTransactionFlags(
4853 eTransactionNeeded|
4854 eDisplayTransactionNeeded|
4855 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004856 return NO_ERROR;
4857 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004858 case 1006:{ // send empty update
4859 signalRefresh();
4860 return NO_ERROR;
4861 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004862 case 1008: // toggle use of hw composer
4863 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004864 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004865 invalidateHwcGeometry();
4866 repaintEverything();
4867 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004868 case 1009: // toggle use of transform hint
4869 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004870 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004871 invalidateHwcGeometry();
4872 repaintEverything();
4873 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004874 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004875 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004876 reply->writeInt32(0);
4877 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004878 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004879 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880 return NO_ERROR;
4881 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004882 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004883 if (!display) {
4884 return NAME_NOT_FOUND;
4885 }
4886
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004887 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004888 return NO_ERROR;
4889 }
4890 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004891 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004892 // daltonize
4893 n = data.readInt32();
4894 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004895 case 1:
4896 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4897 break;
4898 case 2:
4899 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4900 break;
4901 case 3:
4902 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4903 break;
4904 default:
4905 mDaltonizer.setType(ColorBlindnessType::None);
4906 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004907 }
4908 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004909 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004910 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004911 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004912 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004913
4914 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004915 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004917 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004918 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004919 // apply a color matrix
4920 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004921 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004922 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004923 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004924 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004925 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004926 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004927 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004928 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004929 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004930 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004931
4932 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4933 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004934 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004935 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4936 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4937 }
4938
Chia-I Wu28f320b2018-05-03 11:02:56 -07004939 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004940 return NO_ERROR;
4941 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004942 case 1016: { // Unused.
4943 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004944 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004945 case 1017: {
4946 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004947 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004948 return NO_ERROR;
4949 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004950 case 1018: { // Modify Choreographer's phase offset
4951 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004952 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004953 return NO_ERROR;
4954 }
4955 case 1019: { // Modify SurfaceFlinger's phase offset
4956 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004957 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004958 return NO_ERROR;
4959 }
Irvel468051e2016-06-13 16:44:44 -07004960 case 1020: { // Layer updates interceptor
4961 n = data.readInt32();
4962 if (n) {
4963 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004964 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004965 }
4966 else{
4967 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004968 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004969 }
4970 return NO_ERROR;
4971 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004972 case 1021: { // Disable HWC virtual displays
4973 n = data.readInt32();
4974 mUseHwcVirtualDisplays = !n;
4975 return NO_ERROR;
4976 }
Romain Guy0147a172017-06-01 13:53:56 -07004977 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004978 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004979 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004980
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004982 return NO_ERROR;
4983 }
Romain Guy54f154a2017-10-24 21:40:32 +01004984 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004985 int32_t colorMode;
4986
Chia-I Wu0d711262018-05-21 15:19:35 -07004987 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004988 if (data.readInt32(&colorMode) == NO_ERROR) {
4989 mForceColorMode = static_cast<ColorMode>(colorMode);
4990 }
Romain Guy54f154a2017-10-24 21:40:32 +01004991 invalidateHwcGeometry();
4992 repaintEverything();
4993 return NO_ERROR;
4994 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004995 // Deprecate, use 1030 to check whether the device is color managed.
4996 case 1024: {
4997 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004998 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004999 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005000 n = data.readInt32();
5001 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005002 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005003 Mutex::Autolock lock(mStateLock);
5004 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005005 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005006 reply->writeInt32(NO_ERROR);
5007 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005008 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005009 bool writeFile = false;
5010 {
5011 Mutex::Autolock lock(mStateLock);
5012 mTracingEnabledChanged = true;
5013 writeFile = mTracing.disable();
5014 }
5015
5016 if (writeFile) {
5017 reply->writeInt32(mTracing.writeToFile());
5018 } else {
5019 reply->writeInt32(NO_ERROR);
5020 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005021 }
5022 return NO_ERROR;
5023 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005024 case 1026: { // Get layer tracing status
5025 reply->writeBool(mTracing.isEnabled());
5026 return NO_ERROR;
5027 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005028 // Is a DisplayColorSetting supported?
5029 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005030 const auto display = getDefaultDisplayDevice();
5031 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005032 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005033 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005034
5035 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5036 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005037 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005038 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005039 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005040 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005041 reply->writeBool(true);
5042 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005043 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005044 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005045 break;
5046 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005047 reply->writeBool(
5048 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005049 break;
5050 }
5051 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005052 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005053 // Is VrFlinger active?
5054 case 1028: {
5055 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005056 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005057 return NO_ERROR;
5058 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005059 // Set buffer size for SF tracing (value in KB)
5060 case 1029: {
5061 n = data.readInt32();
5062 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5063 ALOGW("Invalid buffer size: %d KB", n);
5064 reply->writeInt32(BAD_VALUE);
5065 return BAD_VALUE;
5066 }
5067
5068 ALOGD("Updating trace buffer to %d KB", n);
5069 mTracing.setBufferSize(n * 1024);
5070 reply->writeInt32(NO_ERROR);
5071 return NO_ERROR;
5072 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005073 // Is device color managed?
5074 case 1030: {
5075 reply->writeBool(useColorManagement);
5076 return NO_ERROR;
5077 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005078 // Override default composition data space
5079 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5080 // && adb shell stop zygote && adb shell start zygote
5081 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5082 // adb shell stop zygote && adb shell start zygote
5083 case 1031: {
5084 Mutex::Autolock _l(mStateLock);
5085 n = data.readInt32();
5086 if (n) {
5087 n = data.readInt32();
5088 if (n) {
5089 Dataspace dataspace = static_cast<Dataspace>(n);
5090 if (!validateCompositionDataspace(dataspace)) {
5091 return BAD_VALUE;
5092 }
5093 mDefaultCompositionDataspace = dataspace;
5094 }
5095 n = data.readInt32();
5096 if (n) {
5097 Dataspace dataspace = static_cast<Dataspace>(n);
5098 if (!validateCompositionDataspace(dataspace)) {
5099 return BAD_VALUE;
5100 }
5101 mWideColorGamutCompositionDataspace = dataspace;
5102 }
5103 } else {
5104 // restore composition data space.
5105 mDefaultCompositionDataspace = defaultCompositionDataspace;
5106 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5107 }
5108 return NO_ERROR;
5109 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005110 // Set trace flags
5111 case 1033: {
5112 n = data.readUint32();
5113 ALOGD("Updating trace flags to 0x%x", n);
5114 mTracing.setTraceFlags(n);
5115 reply->writeInt32(NO_ERROR);
5116 return NO_ERROR;
5117 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005118 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005119 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005120 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005121 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005122 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5123 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005124 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005125 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005126 } else {
5127 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005128 }
5129 return NO_ERROR;
5130 }
Ady Abraham34392f72019-04-10 11:29:27 -07005131 case 1035: {
5132 n = data.readInt32();
5133 mDebugDisplayConfigSetByBackdoor = false;
5134 if (n >= 0) {
5135 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005136 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005137 if (result != NO_ERROR) {
5138 return result;
5139 }
5140 mDebugDisplayConfigSetByBackdoor = true;
5141 }
5142 return NO_ERROR;
5143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005144 }
5145 }
5146 return err;
5147}
5148
Steven Thomas6d8110b2017-08-31 18:24:21 -07005149void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005150 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005151 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005152}
5153
Ana Krulec7d1d6832018-12-27 11:10:09 -08005154void SurfaceFlinger::repaintEverythingForHWC() {
5155 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005156 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005157 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005158}
5159
Ady Abrahama09852a2020-02-20 14:23:42 -08005160void SurfaceFlinger::kernelTimerChanged(bool expired) {
5161 static bool updateOverlay =
5162 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5163 if (!updateOverlay || !mRefreshRateOverlay) return;
5164
5165 // Update the overlay on the main thread to avoid race conditions with
5166 // mRefreshRateConfigs->getCurrentRefreshRate()
5167 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5168 if (mRefreshRateOverlay) {
5169 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5170 const bool timerExpired = kernelTimerEnabled && expired;
5171 const auto& current = [this]() {
5172 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5173 if (mDesiredActiveConfigChanged) {
5174 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5175 mDesiredActiveConfig.configId);
5176 }
5177
5178 return mRefreshRateConfigs->getCurrentRefreshRate();
5179 }();
5180 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5181
5182 if (current != min) {
5183 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5184 mEventQueue->invalidate();
5185 }
5186 }
5187 }));
5188}
5189
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005190// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5191class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005192public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5194 ~WindowDisconnector() {
5195 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005196 }
5197
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005198private:
5199 ANativeWindow* mWindow;
5200 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005201};
5202
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005203status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005204 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005205 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5206 const Rect& sourceCrop, uint32_t reqWidth,
5207 uint32_t reqHeight, bool useIdentityTransform,
5208 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005209 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005210
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005211 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005212
Dominik Laskowski718f9602019-11-09 20:01:35 -08005213 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5214 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5215 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5216 renderAreaRotation = ui::Transform::ROT_0;
5217 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005218
Chia-I Wu20261cb2018-08-23 12:55:44 -07005219 sp<DisplayDevice> display;
5220 {
5221 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005222
Chia-I Wu20261cb2018-08-23 12:55:44 -07005223 display = getDisplayDeviceLocked(displayToken);
5224 if (!display) return BAD_VALUE;
5225
Chia-I Wucb023152018-08-28 12:57:23 -07005226 // set the requested width/height to the logical display viewport size
5227 // by default
5228 if (reqWidth == 0 || reqHeight == 0) {
5229 reqWidth = uint32_t(display->getViewport().width());
5230 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005231 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005232 }
5233
Peiyong Lin0e003c92018-09-17 11:09:51 -07005234 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005235 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005236
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005237 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5238 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005239 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005240 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005241}
5242
chaviw93df2ea2019-04-30 16:45:12 -07005243static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5244 switch (colorMode) {
5245 case ColorMode::DISPLAY_P3:
5246 case ColorMode::BT2100_PQ:
5247 case ColorMode::BT2100_HLG:
5248 case ColorMode::DISPLAY_BT2020:
5249 return Dataspace::DISPLAY_P3;
5250 default:
5251 return Dataspace::V0_SRGB;
5252 }
5253}
5254
5255const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5256 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5257 if (displayToken) {
5258 return getDisplayDeviceLocked(displayToken);
5259 }
5260 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5261 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005262 return getDisplayByLayerStack(displayOrLayerStack);
5263}
5264
5265const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005266 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005267 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005268 return display;
5269 }
5270 }
5271 return nullptr;
5272}
5273
5274status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5275 sp<GraphicBuffer>* outBuffer) {
5276 sp<DisplayDevice> display;
5277 uint32_t width;
5278 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005279 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005280 {
5281 Mutex::Autolock _l(mStateLock);
5282 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5283 if (!display) {
5284 return BAD_VALUE;
5285 }
5286
5287 width = uint32_t(display->getViewport().width());
5288 height = uint32_t(display->getViewport().height());
5289
Dominik Laskowski718f9602019-11-09 20:01:35 -08005290 const auto orientation = display->getOrientation();
5291 captureOrientation = ui::Transform::toRotationFlags(orientation);
5292
5293 switch (captureOrientation) {
5294 case ui::Transform::ROT_90:
5295 captureOrientation = ui::Transform::ROT_270;
5296 break;
5297
5298 case ui::Transform::ROT_270:
5299 captureOrientation = ui::Transform::ROT_90;
5300 break;
5301
5302 case ui::Transform::ROT_INVALID:
5303 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5304 captureOrientation = ui::Transform::ROT_0;
5305 break;
5306
5307 default:
5308 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005309 }
chaviw93df2ea2019-04-30 16:45:12 -07005310 *outDataspace =
5311 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5312 }
5313
5314 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5315 false /* captureSecureLayers */);
5316
5317 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5318 std::placeholders::_1);
5319 bool ignored = false;
5320 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5321 false /* useIdentityTransform */,
5322 ignored /* outCapturedSecureLayers */);
5323}
5324
Robert Carr866455f2019-04-02 16:28:26 -07005325status_t SurfaceFlinger::captureLayers(
5326 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5327 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5328 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5329 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005330 ATRACE_CALL();
5331
5332 class LayerRenderArea : public RenderArea {
5333 public:
Robert Carr578038f2018-03-09 12:25:24 -08005334 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005335 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005336 bool childrenOnly, const Rect& displayViewport)
5337 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005338 mLayer(layer),
5339 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005340 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005341 mFlinger(flinger),
5342 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005343 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005344 Rect getBounds() const override {
5345 const Layer::State& layerState(mLayer->getDrawingState());
5346 return mLayer->getBufferSize(layerState);
5347 }
Marissa Wall61c58622018-07-18 10:12:20 -07005348 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005349 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005350 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005351 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005352 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005353 }
chaviwa76b2712017-09-20 12:02:26 -07005354 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005355 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005356 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005357 Rect getSourceCrop() const override {
5358 if (mCrop.isEmpty()) {
5359 return getBounds();
5360 } else {
5361 return mCrop;
5362 }
5363 }
Robert Carr578038f2018-03-09 12:25:24 -08005364 class ReparentForDrawing {
5365 public:
5366 const sp<Layer>& oldParent;
5367 const sp<Layer>& newParent;
5368
Vishnu Nair4351ad52019-02-11 14:13:02 -08005369 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5370 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005371 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005372 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005373 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5374 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005375 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005376 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005377 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005378 };
5379
5380 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005381 const Rect sourceCrop = getSourceCrop();
5382 // no need to check rotation because there is none
5383 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5384 sourceCrop.height() != getReqHeight();
5385
Robert Carr578038f2018-03-09 12:25:24 -08005386 if (!mChildrenOnly) {
5387 mTransform = mLayer->getTransform().inverse();
5388 drawLayers();
5389 } else {
5390 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005391 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5392 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005393 // In the "childrenOnly" case we reparent the children to a screenshot
5394 // layer which has no properties set and which does not draw.
5395 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005396 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5397 "Screenshot Parent"s, w, h, 0,
5398 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005399
Vishnu Nair4351ad52019-02-11 14:13:02 -08005400 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005401 drawLayers();
5402 }
5403 }
chaviwa76b2712017-09-20 12:02:26 -07005404
chaviwa76b2712017-09-20 12:02:26 -07005405 private:
chaviw7206d492017-11-10 16:16:12 -08005406 const sp<Layer> mLayer;
5407 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005408
Peiyong Linefefaac2018-08-17 12:27:51 -07005409 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005410 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005411
5412 SurfaceFlinger* mFlinger;
5413 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005414 };
5415
Robert Carrc0df3122019-04-11 13:18:21 -07005416 int reqWidth = 0;
5417 int reqHeight = 0;
5418 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005419 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005420 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005421 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005422 {
5423 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005424
Robert Carrc0df3122019-04-11 13:18:21 -07005425 parent = fromHandle(layerHandleBinder);
5426 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5427 ALOGE("captureLayers called with an invalid or removed parent");
5428 return NAME_NOT_FOUND;
5429 }
5430
5431 const int uid = IPCThreadState::self()->getCallingUid();
5432 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5433 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5434 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5435 return PERMISSION_DENIED;
5436 }
5437
Vishnu Nairefc42e22019-12-03 17:36:12 -08005438 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005439 if (sourceCrop.width() <= 0) {
5440 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005441 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005442 }
5443
5444 if (sourceCrop.height() <= 0) {
5445 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005446 crop.bottom = parentSourceBounds.getHeight();
5447 }
5448
5449 if (crop.isEmpty() || frameScale <= 0.0f) {
5450 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5451 // crop was not specified, or an invalid frame scale was provided.
5452 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005453 }
5454 reqWidth = crop.width() * frameScale;
5455 reqHeight = crop.height() * frameScale;
5456
5457 for (const auto& handle : excludeHandles) {
5458 sp<Layer> excludeLayer = fromHandle(handle);
5459 if (excludeLayer != nullptr) {
5460 excludeLayers.emplace(excludeLayer);
5461 } else {
5462 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5463 return NAME_NOT_FOUND;
5464 }
5465 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005466
5467 auto display = getDisplayByLayerStack(parent->getLayerStack());
5468 if (!display) {
5469 return BAD_VALUE;
5470 }
5471
5472 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005473 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005474
Chia-I Wu20261cb2018-08-23 12:55:44 -07005475 // really small crop or frameScale
5476 if (reqWidth <= 0) {
5477 reqWidth = 1;
5478 }
5479 if (reqHeight <= 0) {
5480 reqHeight = 1;
5481 }
5482
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005483 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5484 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005485 auto traverseLayers = [parent, childrenOnly,
5486 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005487 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5488 if (!layer->isVisible()) {
5489 return;
Robert Carr578038f2018-03-09 12:25:24 -08005490 } else if (childrenOnly && layer == parent.get()) {
5491 return;
chaviwa76b2712017-09-20 12:02:26 -07005492 }
Robert Carr866455f2019-04-02 16:28:26 -07005493
5494 sp<Layer> p = layer;
5495 while (p != nullptr) {
5496 if (excludeLayers.count(p) != 0) {
5497 return;
5498 }
5499 p = p->getParent();
5500 }
5501
chaviwa76b2712017-09-20 12:02:26 -07005502 visitor(layer);
5503 });
5504 };
Robert Carr108b2c72019-04-02 16:32:58 -07005505
5506 bool outCapturedSecureLayers = false;
5507 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5508 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005509}
5510
5511status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5512 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005513 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005514 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005515 bool useIdentityTransform,
5516 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005517 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005518
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005520 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5521 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005522 *outBuffer =
5523 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5524 static_cast<android_pixel_format>(reqPixelFormat), 1,
5525 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526
Robert Carr108b2c72019-04-02 16:32:58 -07005527 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5528 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005529}
5530
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005531status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5532 TraverseLayersFunction traverseLayers,
5533 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005534 bool useIdentityTransform,
5535 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005536 // This mutex protects syncFd and captureResult for communication of the return values from the
5537 // main thread back to this Binder thread
5538 std::mutex captureMutex;
5539 std::condition_variable captureCondition;
5540 std::unique_lock<std::mutex> captureLock(captureMutex);
5541 int syncFd = -1;
5542 std::optional<status_t> captureResult;
5543
Robert Carr03480e22018-01-04 16:02:06 -08005544 const int uid = IPCThreadState::self()->getCallingUid();
5545 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5546
Dominik Laskowski8c001672018-05-30 16:52:06 -07005547 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005548 // If there is a refresh pending, bug out early and tell the binder thread to try again
5549 // after the refresh.
5550 if (mRefreshPending) {
5551 ATRACE_NAME("Skipping screenshot for now");
5552 std::unique_lock<std::mutex> captureLock(captureMutex);
5553 captureResult = std::make_optional<status_t>(EAGAIN);
5554 captureCondition.notify_one();
5555 return;
5556 }
5557
5558 status_t result = NO_ERROR;
5559 int fd = -1;
5560 {
5561 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005562 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005563 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005564 useIdentityTransform, forSystem, &fd,
5565 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005566 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567 }
5568
5569 {
5570 std::unique_lock<std::mutex> captureLock(captureMutex);
5571 syncFd = fd;
5572 captureResult = std::make_optional<status_t>(result);
5573 captureCondition.notify_one();
5574 }
5575 });
5576
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005577 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005578 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005579 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005580 while (*captureResult == EAGAIN) {
5581 captureResult.reset();
5582 result = postMessageAsync(message);
5583 if (result != NO_ERROR) {
5584 return result;
5585 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005586 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005587 }
5588 result = *captureResult;
5589 }
5590
5591 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592 sync_wait(syncFd, -1);
5593 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005594 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005595
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005597}
5598
chaviwa76b2712017-09-20 12:02:26 -07005599void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005600 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005601 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5602 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005603 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005604
chaviwa76b2712017-09-20 12:02:26 -07005605 const auto reqWidth = renderArea.getReqWidth();
5606 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005607 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005608 const auto transform = renderArea.getTransform();
5609 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005610 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005611
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005612 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005613 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005614
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005615 // assume that bounds are never offset, and that they are the same as the
5616 // buffer bounds.
5617 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005618 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005619 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005620
5621 // Now take into account the rotation flag. We append a transform that
5622 // rotates the layer stack about the origin, then translate by buffer
5623 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005624 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005625 int displacementX = 0;
5626 int displacementY = 0;
5627 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5628 switch (rotation) {
5629 case ui::Transform::ROT_90:
5630 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005631 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005632 break;
5633 case ui::Transform::ROT_180:
5634 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005635 displacementY = renderArea.getBounds().getWidth();
5636 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 break;
5638 case ui::Transform::ROT_270:
5639 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005640 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005641 break;
5642 default:
5643 break;
5644 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005645
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005646 // We need to transform the clipping window into the right spot.
5647 // First, rotate the clipping rectangle by the rotation hint to get the
5648 // right orientation
5649 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5650 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5651 const vec4 rotClipTL = rotMatrix * clipTL;
5652 const vec4 rotClipBR = rotMatrix * clipBR;
5653 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5654 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5655 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5656 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5657
5658 // Now reposition the clipping rectangle with the displacement vector
5659 // computed above.
5660 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661 clientCompositionDisplay.clip =
5662 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5663 newClipRight + displacementX, newClipBottom + displacementY);
5664
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005665 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005666 clientCompositionDisplay.globalTransform =
5667 clipTransform * clientCompositionDisplay.globalTransform;
5668
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005669 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5670 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005671
chaviw50da5042018-04-09 13:49:37 -07005672 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005673
Vishnu Nair9b079a22020-01-21 14:36:08 -08005674 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005675 fillLayer.source.buffer.buffer = nullptr;
5676 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5677 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5678 fillLayer.alpha = half(alpha);
5679 clientCompositionLayers.push_back(fillLayer);
5680
5681 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005682 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005683 const bool supportProtectedContent = false;
5684 Region clip(renderArea.getBounds());
5685 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5686 clip,
5687 useIdentityTransform,
5688 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5689 renderArea.isSecure(),
5690 supportProtectedContent,
5691 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005692 displayViewport,
5693 clientCompositionDisplay.outputDataspace,
5694 true, /* realContentIsVisible */
5695 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005696 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005697 std::vector<compositionengine::LayerFE::LayerSettings> results =
5698 layer->prepareClientCompositionList(targetSettings);
5699 clientCompositionLayers.insert(clientCompositionLayers.end(),
5700 std::make_move_iterator(results.begin()),
5701 std::make_move_iterator(results.end()));
5702 results.clear();
5703
chaviwa76b2712017-09-20 12:02:26 -07005704 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005705
Vishnu Nair9b079a22020-01-21 14:36:08 -08005706 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5707 clientCompositionLayers.reserve(clientCompositionLayers.size());
5708 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5709 std::back_inserter(clientCompositionLayerPointers),
5710 [](compositionengine::LayerFE::LayerSettings& settings)
5711 -> renderengine::LayerSettings* { return &settings; });
5712
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005714 // Use an empty fence for the buffer fence, since we just created the buffer so
5715 // there is no need for synchronization with the GPU.
5716 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005717 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005718 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005719 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005720 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005721
5722 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005723}
5724
chaviwa76b2712017-09-20 12:02:26 -07005725status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5726 TraverseLayersFunction traverseLayers,
5727 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005728 bool useIdentityTransform, bool forSystem,
5729 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005730 ATRACE_CALL();
5731
chaviwa76b2712017-09-20 12:02:26 -07005732 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005733 outCapturedSecureLayers =
5734 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005735 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005736
Robert Carr03480e22018-01-04 16:02:06 -08005737 // We allow the system server to take screenshots of secure layers for
5738 // use in situations like the Screen-rotation animation and place
5739 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005740 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005741 ALOGW("FB is protected: PERMISSION_DENIED");
5742 return PERMISSION_DENIED;
5743 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005744 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005745 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005746}
5747
chaviw95ef3c42019-02-14 10:55:09 -08005748void SurfaceFlinger::setInputWindowsFinished() {
5749 Mutex::Autolock _l(mStateLock);
5750
5751 mPendingSyncInputWindows = false;
5752 mTransactionCV.broadcast();
5753}
chaviw5f21a5e2019-02-14 10:00:34 -08005754
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005755// ---------------------------------------------------------------------------
5756
Edgar Arriaga844fa672020-01-16 14:21:42 -08005757void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5758 layersSortedByZ.traverse(visitor);
5759}
5760
Dan Stoza412903f2017-04-27 13:42:17 -07005761void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5762 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005763}
5764
Dan Stoza412903f2017-04-27 13:42:17 -07005765void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5766 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005767}
5768
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005769void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005770 const LayerVector::Visitor& visitor) {
5771 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005772 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005773 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005774 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005775 continue;
5776 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005777 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005778 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005779 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005780 return;
5781 }
chaviwa76b2712017-09-20 12:02:26 -07005782 if (!layer->isVisible()) {
5783 return;
5784 }
5785 visitor(layer);
5786 });
5787 }
5788}
5789
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005790status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5791 HwcConfigIndexType defaultConfig,
5792 float minRefreshRate,
5793 float maxRefreshRate) {
5794 Mutex::Autolock lock(mStateLock);
5795
Dominik Laskowski22488f62019-03-28 09:53:04 -07005796 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005797 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5798 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5799 // it should go thru setDesiredActiveConfig, similar to primary display.
5800 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5801 const auto displayId = display->getId();
5802 LOG_ALWAYS_FATAL_IF(!displayId);
5803
5804 HWC2::VsyncPeriodChangeConstraints constraints;
5805 constraints.desiredTimeNanos = systemTime();
5806 constraints.seamlessRequired = false;
5807
5808 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005809 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5810 constraints, &timeline) < 0) {
5811 return BAD_VALUE;
5812 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005813 if (timeline.refreshRequired) {
5814 repaintEverythingForHWC();
5815 }
5816
Ady Abrahamdfa37362020-01-21 18:02:39 -08005817 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005818 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005819 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5820 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005821 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005822 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005823 }
5824
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005825 if (mDebugDisplayConfigSetByBackdoor) {
5826 // ignore this request as config is overridden by backdoor
5827 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005828 }
5829
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005830 bool policyChanged;
5831 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5832 &policyChanged) < 0) {
5833 return BAD_VALUE;
5834 }
5835 if (!policyChanged) {
5836 return NO_ERROR;
5837 }
5838
5839 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5840 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005841
5842 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5843 // that listeners that care about a change in allowed configs can get the notification.
5844 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005845 const nsecs_t vsyncPeriod =
5846 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005847 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005848 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005849
Ana Krulec3f6a2062020-01-23 15:48:01 -08005850 auto configId = mScheduler->getPreferredConfigId();
5851 auto preferredRefreshRate = configId
5852 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5853 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5854 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5855 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5856 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5857
5858 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5859 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5860 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005861 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005862 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005863 }
5864
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005865 return NO_ERROR;
5866}
5867
Ana Krulec0782b882019-10-15 17:34:54 -07005868status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005869 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005870 float maxRefreshRate) {
5871 ATRACE_CALL();
5872
5873 if (!displayToken) {
5874 return BAD_VALUE;
5875 }
5876
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005877 status_t result = NO_ERROR;
5878
Ana Krulec234bb162019-11-10 22:55:55 +01005879 postMessageSync(new LambdaMessage([&]() {
5880 const auto display = getDisplayDeviceLocked(displayToken);
5881 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005882 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005883 ALOGE("Attempt to set desired display configs for invalid display token %p",
5884 displayToken.get());
5885 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005886 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005887 ALOGW("Attempt to set desired display configs for virtual display");
5888 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005889 result =
5890 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5891 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005892 }
5893 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005894
5895 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005896}
5897
5898status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005899 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005900 float* outMinRefreshRate,
5901 float* outMaxRefreshRate) {
5902 ATRACE_CALL();
5903
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005904 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005905 return BAD_VALUE;
5906 }
5907
5908 Mutex::Autolock lock(mStateLock);
5909 const auto display = getDisplayDeviceLocked(displayToken);
5910 if (!display) {
5911 return NAME_NOT_FOUND;
5912 }
5913
5914 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005915 HwcConfigIndexType defaultConfig;
5916 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5917 *outDefaultConfig = defaultConfig.value();
5918 return NO_ERROR;
5919 } else if (display->isVirtual()) {
5920 return BAD_VALUE;
5921 } else {
5922 const auto displayId = display->getId();
5923 if (!displayId) {
5924 return BAD_VALUE;
5925 }
5926 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5927 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5928 *outMinRefreshRate = 1e9f / vsyncPeriod;
5929 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5930 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005931 }
Ana Krulec0782b882019-10-15 17:34:54 -07005932}
5933
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005934void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005935 mFlinger->setInputWindowsFinished();
5936}
5937
Robert Carrc0df3122019-04-11 13:18:21 -07005938sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005939 BBinder* b = nullptr;
5940 if (handle) {
5941 b = handle->localBinder();
5942 }
Robert Carrc0df3122019-04-11 13:18:21 -07005943 if (b == nullptr) {
5944 return nullptr;
5945 }
5946 auto it = mLayersByLocalBinderToken.find(b);
5947 if (it != mLayersByLocalBinderToken.end()) {
5948 return it->second.promote();
5949 }
5950 return nullptr;
5951}
5952
Dominik Laskowski75848362019-11-11 17:57:20 -08005953void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005954 mNumLayers++;
5955 mScheduler->registerLayer(layer);
5956}
5957
5958void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5959 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005960 removeFromOffscreenLayers(layer);
5961}
5962
5963// WARNING: ONLY CALL THIS FROM LAYER DTOR
5964// Here we add children in the current state to offscreen layers and remove the
5965// layer itself from the offscreen layer list. Since
5966// this is the dtor, it is safe to access the current state. This keeps us
5967// from dangling children layers such that they are not reachable from the
5968// Drawing state nor the offscreen layer list
5969// See b/141111965
5970void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5971 for (auto& child : layer->getCurrentChildren()) {
5972 mOffscreenLayers.emplace(child.get());
5973 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005974 mOffscreenLayers.erase(layer);
5975}
5976
Alec Mouri4545a8a2019-08-08 20:05:32 -07005977void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5978 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5979}
5980
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005981status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5982 float lightPosY, float lightPosZ,
5983 float lightRadius) {
5984 Mutex::Autolock _l(mStateLock);
5985 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5986 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5987 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5988 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5989 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5990
5991 // these values are overridden when calculating the shadow settings for a layer.
5992 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5993 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005994 return NO_ERROR;
5995}
5996
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005997const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5998 const {
5999 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6000 // on the work to remove the table in that bug rather than adding more to
6001 // it.
6002 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6003 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6004 // supported, and exposed via the
6005 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6006 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6007 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6008 };
6009 return genericLayerMetadataKeyMap;
6010}
6011
Steven Thomas62a4cf82020-01-31 12:04:03 -08006012status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6013 int8_t compatibility) {
6014 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6015 return BAD_VALUE;
6016 }
6017
6018 Mutex::Autolock lock(mStateLock);
6019 if (authenticateSurfaceTextureLocked(surface)) {
6020 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6021 if (layer->setFrameRate(
6022 Layer::FrameRate(frameRate,
6023 Layer::FrameRate::convertCompatibility(compatibility)))) {
6024 setTransactionFlags(eTraversalNeeded);
6025 }
6026 } else {
6027 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6028 return BAD_VALUE;
6029 }
6030 return NO_ERROR;
6031}
6032
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006033} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006034
Mathias Agopian3f844832013-08-07 21:24:32 -07006035#if defined(__gl_h_)
6036#error "don't include gl/gl.h in this file"
6037#endif
6038
6039#if defined(__gl2_h_)
6040#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006041#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006042
6043// TODO(b/129481165): remove the #pragma below and fix conversion issues
6044#pragma clang diagnostic pop // ignored "-Wconversion"