blob: 8587fb2c43d6d8ddcce46e3ebb10a372dd9faab8 [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;
Ady Abrahamff731d82020-02-18 17:22:46 -0800856 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857
Andy McFadden91b2ca82014-06-13 14:04:23 -0700858 // This is how far in advance a buffer must be queued for
859 // presentation at a given time. If you want a buffer to appear
860 // on the screen at time N, you must submit the buffer before
861 // (N - presentationDeadline).
862 //
863 // Normally it's one full refresh period (to give SF a chance to
864 // latch the buffer), but this can be reduced by configuring a
865 // DispSync offset. Any additional delays introduced by the hardware
866 // composer or panel must be accounted for here.
867 //
868 // We add an additional 1ms to allow for processing time and
869 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700871
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700873 }
874
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 return NO_ERROR;
876}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700877
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700878status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
879 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700880 return BAD_VALUE;
881 }
882
Ana Krulecc2870422019-01-29 19:00:58 -0800883 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700884 return NO_ERROR;
885}
886
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
888 const auto display = getDisplayDevice(displayToken);
889 if (!display) {
890 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800891 return BAD_VALUE;
892 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700893
Steven Thomasc9098452019-09-30 17:15:05 -0700894 if (display->isPrimary()) {
895 std::lock_guard<std::mutex> lock(mActiveConfigLock);
896 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800897 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700898 }
Steven Thomasc9098452019-09-30 17:15:05 -0700899 }
Ady Abraham2139f732019-11-13 18:56:40 -0800900
901 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Ady Abraham03b02dd2019-03-21 15:40:11 -0700904void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800905 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800906 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800907 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800908
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800909 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800910 // config twice. However event generation config might have changed so we need to update it
911 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800912 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700913 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
914 mDesiredActiveConfig = info;
915 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800916
917 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800918 // This will trigger HWC refresh without resetting the idle timer.
919 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700920 // Start receiving vsync samples now, so that we can detect a period
921 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800922 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700923 // As we called to set period, we will call to onRefreshRateChangeCompleted once
924 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700925 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800926
Ady Abraham9e16a482019-12-03 17:19:41 -0800927 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
928 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800930 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700931
932 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800933 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700934 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800935}
936
937status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
938 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800939
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100940 if (!displayToken) {
941 return BAD_VALUE;
942 }
Ady Abraham838de062019-02-04 10:24:03 -0800943
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100944 status_t result = NO_ERROR;
945
946 postMessageSync(new LambdaMessage([&]() {
947 const auto display = getDisplayDeviceLocked(displayToken);
948 if (!display) {
949 ALOGE("Attempt to set allowed display configs for invalid display token %p",
950 displayToken.get());
951 result = BAD_VALUE;
952 } else if (display->isVirtual()) {
953 ALOGW("Attempt to set allowed display configs for virtual display");
954 result = BAD_VALUE;
955 } else {
956 HwcConfigIndexType config(mode);
957 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
958 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
959 refreshRate.fps);
960 }
961 }));
962
963 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964}
965
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966void SurfaceFlinger::setActiveConfigInternal() {
967 ATRACE_CALL();
968
Dominik Laskowski22488f62019-03-28 09:53:04 -0700969 const auto display = getDefaultDisplayDeviceLocked();
970 if (!display) {
971 return;
972 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800975 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700976 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 display->setActiveConfig(mUpcomingActiveConfig.configId);
978
Ady Abraham2e1dd892020-03-05 13:48:36 -0800979 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800980 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800981 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
982 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800983 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700984
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800985 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700986 const nsecs_t vsyncPeriod =
987 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
988 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800989 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700990 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800991 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992}
993
Ady Abraham53852a52019-05-28 18:07:44 -0700994void SurfaceFlinger::desiredActiveConfigChangeDone() {
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
996 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
997 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700998
Ady Abraham2e1dd892020-03-05 13:48:36 -0800999 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001000 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001001 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001002 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1003 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001004}
1005
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001007 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001008 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001010 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001012 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 return true;
1014 }
1015
1016 // We received the present fence from the HWC, so we assume it successfully updated
1017 // the config, hence we update SF.
1018 mCheckPendingFence = false;
1019 setActiveConfigInternal();
1020 }
1021
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022 // Store the local variable to release the lock.
1023 ActiveConfigInfo desiredActiveConfig;
1024 {
1025 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 if (!mDesiredActiveConfigChanged) {
1027 return false;
1028 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 desiredActiveConfig = mDesiredActiveConfig;
1030 }
1031
Ady Abraham2e1dd892020-03-05 13:48:36 -08001032 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001033 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1034 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1035 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001036 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1038 // display is not valid or we are already in the requested mode
1039 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001040 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001042 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043
Ady Abraham838de062019-02-04 10:24:03 -08001044 // Desired active config was set, it is different than the config currently in use, however
1045 // allowed configs might have change by the time we process the refresh.
1046 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001047 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001048 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001049 return false;
1050 }
Alec Mouri7f015182019-07-11 13:56:22 -07001051
Ady Abrahamb838aed2019-02-12 15:30:16 -08001052 mUpcomingActiveConfig = desiredActiveConfig;
1053 const auto displayId = display->getId();
1054 LOG_ALWAYS_FATAL_IF(!displayId);
1055
Ady Abraham2139f732019-11-13 18:56:40 -08001056 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001057
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001058 // TODO(b/142753666) use constrains
1059 HWC2::VsyncPeriodChangeConstraints constraints;
1060 constraints.desiredTimeNanos = systemTime();
1061 constraints.seamlessRequired = false;
1062
1063 HWC2::VsyncPeriodChangeTimeline outTimeline;
1064 auto status =
1065 getHwComposer().setActiveConfigWithConstraints(*displayId,
1066 mUpcomingActiveConfig.configId.value(),
1067 constraints, &outTimeline);
1068 if (status != NO_ERROR) {
1069 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1070 return false;
1071 }
1072
1073 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1074 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001075 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001076 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001077}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1080 Vector<ColorMode>* outColorModes) {
1081 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001082 return BAD_VALUE;
1083 }
1084
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001086 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001087 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001088 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1089
1090 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1091 if (!displayId) {
1092 return NAME_NOT_FOUND;
1093 }
1094
Dominik Laskowski075d3172018-05-24 15:50:06 -07001095 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001096 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001097 }
Michael Wright28f24d02016-07-12 13:30:53 -07001098 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001099
1100 // If it's built-in display and the configuration claims it's not wide color capable,
1101 // filter out all wide color modes. The typical reason why this happens is that the
1102 // hardware is not good enough to support GPU composition of wide color, and thus the
1103 // OEMs choose to disable this capability.
1104 if (isInternalDisplay && !hasWideColorDisplay) {
1105 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1106 isWideColorMode);
1107 } else {
1108 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1109 }
Michael Wright28f24d02016-07-12 13:30:53 -07001110
1111 return NO_ERROR;
1112}
1113
Daniel Solomon42d04562019-01-20 21:03:19 -08001114status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1115 ui::DisplayPrimaries &primaries) {
1116 if (!displayToken) {
1117 return BAD_VALUE;
1118 }
1119
1120 // Currently we only support this API for a single internal display.
1121 if (getInternalDisplayToken() != displayToken) {
1122 return BAD_VALUE;
1123 }
1124
1125 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1126 return NO_ERROR;
1127}
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1130 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001131 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001132 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001133 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001134}
1135
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001136status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001137 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001138 Vector<ColorMode> modes;
1139 getDisplayColorModes(displayToken, &modes);
1140 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1141 if (mode < ColorMode::NATIVE || !exists) {
1142 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1143 decodeColorMode(mode).c_str(), mode, displayToken.get());
1144 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001145 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 const auto display = getDisplayDevice(displayToken);
1147 if (!display) {
1148 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1149 decodeColorMode(mode).c_str(), mode, displayToken.get());
1150 } else if (display->isVirtual()) {
1151 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1152 decodeColorMode(mode).c_str(), mode);
1153 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001154 display->getCompositionDisplay()->setColorProfile(
1155 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1156 RenderIntent::COLORIMETRIC,
1157 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001158 }
1159 }));
1160
Michael Wright28f24d02016-07-12 13:30:53 -07001161 return NO_ERROR;
1162}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001163
Galia Peycheva5492cb52019-10-30 14:13:16 +01001164status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1165 bool* outSupport) const {
1166 Mutex::Autolock _l(mStateLock);
1167
1168 if (!displayToken) {
1169 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1170 return BAD_VALUE;
1171 }
1172 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1173 if (!displayId) {
1174 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1175 displayToken.get());
1176 return NAME_NOT_FOUND;
1177 }
1178 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1179 HWC2::DisplayCapability::AutoLowLatencyMode);
1180 return NO_ERROR;
1181}
1182
1183void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1184 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1185}
1186
1187void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1188 if (!displayToken) {
1189 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1190 return;
1191 }
1192 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1193 if (!displayId) {
1194 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1195 displayToken.get());
1196 return;
1197 }
1198
1199 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1200}
1201
1202status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1203 bool* outSupport) const {
1204 Mutex::Autolock _l(mStateLock);
1205
1206 if (!displayToken) {
1207 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1208 return BAD_VALUE;
1209 }
1210 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1211 if (!displayId) {
1212 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1213 displayToken.get());
1214 return NAME_NOT_FOUND;
1215 }
1216
1217 std::vector<HWC2::ContentType> outSupportedContentTypes;
1218 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1219 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1220 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1221 return NO_ERROR;
1222}
1223
1224void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1225 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1226}
1227
1228void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1229 if (!displayToken) {
1230 ALOGE("setGameContentType() failed. Missing display token.");
1231 return;
1232 }
1233 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1234 if (!displayId) {
1235 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1236 displayToken.get());
1237 return;
1238 }
1239
1240 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1241 getHwComposer().setContentType(*displayId, type);
1242}
1243
Svetoslavd85084b2014-03-20 10:28:31 -07001244status_t SurfaceFlinger::clearAnimationFrameStats() {
1245 Mutex::Autolock _l(mStateLock);
1246 mAnimFrameTracker.clearStats();
1247 return NO_ERROR;
1248}
1249
1250status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1251 Mutex::Autolock _l(mStateLock);
1252 mAnimFrameTracker.getStats(outStats);
1253 return NO_ERROR;
1254}
1255
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001256status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1257 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001258 Mutex::Autolock _l(mStateLock);
1259
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001260 const auto display = getDisplayDeviceLocked(displayToken);
1261 if (!display) {
1262 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001263 return BAD_VALUE;
1264 }
1265
Peiyong Linfb069302018-04-25 14:34:31 -07001266 // At this point the DisplayDeivce should already be set up,
1267 // meaning the luminance information is already queried from
1268 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001269 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001270 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1271 capabilities.getDesiredMaxLuminance(),
1272 capabilities.getDesiredMaxAverageLuminance(),
1273 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001274
1275 return NO_ERROR;
1276}
1277
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001278std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1279 const DisplayDevice& display) const {
1280 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1281 // avoid repetitive HAL IPC and EDID parsing.
1282 const auto displayId = display.getId();
1283 LOG_FATAL_IF(!displayId);
1284
1285 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1286 LOG_FATAL_IF(!hwcDisplayId);
1287
1288 uint8_t port;
1289 DisplayIdentificationData data;
1290 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1291 ALOGV("%s: No identification data.", __FUNCTION__);
1292 return {};
1293 }
1294
1295 const auto info = parseDisplayIdentificationData(port, data);
1296 if (!info) {
1297 return {};
1298 }
1299 return info->deviceProductInfo;
1300}
1301
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001302status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1303 ui::PixelFormat* outFormat,
1304 ui::Dataspace* outDataspace,
1305 uint8_t* outComponentMask) const {
1306 if (!outFormat || !outDataspace || !outComponentMask) {
1307 return BAD_VALUE;
1308 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001309 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001310 if (!display || !display->getId()) {
1311 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1312 return BAD_VALUE;
1313 }
1314 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1315 outDataspace, outComponentMask);
1316}
1317
Kevin DuBois74e53772018-11-19 10:52:38 -08001318status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1319 bool enable, uint8_t componentMask,
1320 uint64_t maxFrames) const {
1321 const auto display = getDisplayDevice(displayToken);
1322 if (!display || !display->getId()) {
1323 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1324 return BAD_VALUE;
1325 }
1326
1327 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1328 componentMask, maxFrames);
1329}
1330
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001331status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1332 uint64_t maxFrames, uint64_t timestamp,
1333 DisplayedFrameStats* outStats) const {
1334 const auto display = getDisplayDevice(displayToken);
1335 if (!display || !display->getId()) {
1336 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1337 return BAD_VALUE;
1338 }
1339
1340 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1341 outStats);
1342}
1343
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001344status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1345 if (!outSupported) {
1346 return BAD_VALUE;
1347 }
1348 *outSupported = getRenderEngine().supportsProtectedContent();
1349 return NO_ERROR;
1350}
1351
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001352status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1353 bool* outIsWideColorDisplay) const {
1354 if (!displayToken || !outIsWideColorDisplay) {
1355 return BAD_VALUE;
1356 }
1357 Mutex::Autolock _l(mStateLock);
1358 const auto display = getDisplayDeviceLocked(displayToken);
1359 if (!display) {
1360 return BAD_VALUE;
1361 }
Peiyong Linff84a152019-05-17 18:36:19 -07001362
1363 // Use hasWideColorDisplay to override built-in display.
1364 const auto displayId = display->getId();
1365 if (displayId && displayId == getInternalDisplayIdLocked()) {
1366 *outIsWideColorDisplay = hasWideColorDisplay;
1367 return NO_ERROR;
1368 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001369 *outIsWideColorDisplay = display->hasWideColorGamut();
1370 return NO_ERROR;
1371}
1372
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001373status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001374 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001375 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001376
Dominik Laskowski6505f792019-09-18 11:10:05 -07001377 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1378 mEventQueue->setEventConnection(
1379 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001380 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001381 }));
1382
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001383 return NO_ERROR;
1384}
1385
1386status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001387 Mutex::Autolock lock(mStateLock);
1388 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001389}
1390
Lloyd Pique755e3192018-01-31 16:46:15 -08001391status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1392 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001393 // Try to acquire a lock for 1s, fail gracefully
1394 const status_t err = mStateLock.timedLock(s2ns(1));
1395 const bool locked = (err == NO_ERROR);
1396 if (!locked) {
1397 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1398 return TIMED_OUT;
1399 }
1400
1401 outLayers->clear();
1402 mCurrentState.traverseInZOrder([&](Layer* layer) {
1403 outLayers->push_back(layer->getLayerDebugInfo());
1404 });
1405
1406 mStateLock.unlock();
1407 return NO_ERROR;
1408}
1409
Peiyong Linc6780972018-10-28 15:24:08 -07001410status_t SurfaceFlinger::getCompositionPreference(
1411 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1412 Dataspace* outWideColorGamutDataspace,
1413 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001414 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001415 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001416 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001417 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001418 return NO_ERROR;
1419}
1420
Dan Stozaec460082018-12-17 15:35:09 -08001421status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1422 const sp<IBinder>& stopLayerHandle,
1423 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001424 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001425 return BAD_VALUE;
1426 }
1427 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001428 return NO_ERROR;
1429}
1430
Dan Stozaec460082018-12-17 15:35:09 -08001431status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001432 if (!listener) {
1433 return BAD_VALUE;
1434 }
Dan Stozaec460082018-12-17 15:35:09 -08001435 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001436 return NO_ERROR;
1437}
Dan Gittik57e63c52019-01-18 16:37:54 +00001438
1439status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1440 bool* outSupport) const {
1441 if (!displayToken || !outSupport) {
1442 return BAD_VALUE;
1443 }
1444 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1445 if (!displayId) {
1446 return NAME_NOT_FOUND;
1447 }
1448 *outSupport =
1449 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1450 return NO_ERROR;
1451}
1452
1453status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1454 float brightness) const {
1455 if (!displayToken) {
1456 return BAD_VALUE;
1457 }
1458 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1459 if (!displayId) {
1460 return NAME_NOT_FOUND;
1461 }
1462 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1463}
1464
Ady Abraham8532d012019-05-08 14:50:56 -07001465status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1466 PowerHint powerHint = static_cast<PowerHint>(hintId);
1467
1468 if (powerHint == PowerHint::INTERACTION) {
1469 mScheduler->notifyTouchEvent();
1470 }
1471
1472 return NO_ERROR;
1473}
1474
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001475// ----------------------------------------------------------------------------
1476
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001477sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001478 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001479 const auto& handle =
1480 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001481
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001482 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001483}
1484
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001485// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001486
1487void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001488 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001489}
1490
1491void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001492 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001493 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001494 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001495}
1496
1497void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001498 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001499 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001500 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001501}
1502
1503void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001504 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001505 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001506}
1507
1508status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001509 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001510 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511}
1512
1513status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001514 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516 if (res == NO_ERROR) {
1517 msg->wait();
1518 }
1519 return res;
1520}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001522void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001523 do {
1524 waitForEvent();
1525 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001526}
1527
Dominik Laskowski83b88212018-12-11 13:34:06 -08001528nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001529 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001530 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1531 return 0;
1532 }
1533
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001534 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001535}
1536
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001537void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001538 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001539 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001540 ATRACE_NAME("SF onVsync");
1541
Steven Thomas3cfac282017-02-06 12:29:30 -08001542 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001544 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 return;
1546 }
1547
Dominik Laskowski075d3172018-05-24 15:50:06 -07001548 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001549 return;
1550 }
1551
Dominik Laskowski075d3172018-05-24 15:50:06 -07001552 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001553 // For now, we don't do anything with external display vsyncs.
1554 return;
1555 }
1556
Alec Mourif8e689c2019-05-20 18:32:22 -07001557 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001558 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001559 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001560 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001561 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001562}
1563
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001565 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1566 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001567}
1568
Ady Abraham2139f732019-11-13 18:56:40 -08001569bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001570 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001571}
1572
Ady Abraham2139f732019-11-13 18:56:40 -08001573void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1574 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001575 const auto display = getDefaultDisplayDeviceLocked();
1576 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001577 return;
1578 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001579 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001580
Ana Krulec7d1d6832018-12-27 11:10:09 -08001581 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001582 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1583 ALOGV("Skipping config %d as it is not part of allowed configs",
1584 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001585 return;
1586 }
1587
Ady Abraham2139f732019-11-13 18:56:40 -08001588 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001589}
1590
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001591void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001592 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001593 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001594 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595
Lloyd Piqueba04e622017-12-14 17:11:26 -08001596 // Ignore events that do not have the right sequenceId.
1597 if (sequenceId != getBE().mComposerSequenceId) {
1598 return;
1599 }
1600
Steven Thomasb02664d2017-07-26 18:48:28 -07001601 // Only lock if we're not on the main thread. This function is normally
1602 // called on a hwbinder thread, but for the primary display it's called on
1603 // the main thread with the state lock already held, so don't attempt to
1604 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001605 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001606
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001607 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001608
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001609 if (std::this_thread::get_id() == mMainThreadId) {
1610 // Process all pending hot plug events immediately if we are on the main thread.
1611 processDisplayHotplugEventsLocked();
1612 }
1613
Lloyd Piqueba04e622017-12-14 17:11:26 -08001614 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001615}
1616
Ady Abraham7159f572019-10-11 11:10:18 -07001617void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001618 int32_t sequenceId, hwc2_display_t /*display*/,
1619 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1620 Mutex::Autolock lock(mStateLock);
1621 if (sequenceId != getBE().mComposerSequenceId) {
1622 return;
1623 }
1624 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001625}
1626
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001627void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1628 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1629 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1630}
1631
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001632void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001633 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001634 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001635 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001636 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001637 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001638}
1639
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001640void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001641 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001642
1643 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1644 // display power state.
1645 postMessageAsync(new LambdaMessage(
1646 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1647}
1648
1649void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1650 ATRACE_CALL();
1651
Ady Abraham27c70212019-06-11 10:52:26 -07001652 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1653
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001654 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001655 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1656 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001657 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001658 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001659 }
Mathias Agopian86303202012-07-24 22:46:10 -07001660}
1661
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001662// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001663void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001664 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001665 // Clear the drawing state so that the logic inside of
1666 // handleTransactionLocked will fire. It will determine the delta between
1667 // mCurrentState and mDrawingState and re-apply all changes when we make the
1668 // transition.
1669 mDrawingState.displays.clear();
1670 mDisplays.clear();
1671}
1672
Steven Thomas050b2c82017-03-06 11:45:16 -08001673void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001674 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001675 if (!mVrFlinger)
1676 return;
1677 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001678 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001679 return;
1680 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001681
Lloyd Pique441d5042018-10-18 16:49:51 -07001682 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001683 ALOGE("Vr flinger is only supported for remote hardware composer"
1684 " service connections. Ignoring request to transition to vr"
1685 " flinger.");
1686 mVrFlingerRequestsDisplay = false;
1687 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001688 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001689
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001690 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001691
Steven Thomas0123ac62018-07-12 11:32:34 -07001692 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001693 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001694
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001695 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001696
1697 // Clear out all the output layers from the composition engine for all
1698 // displays before destroying the hardware composer interface. This ensures
1699 // any HWC layers are destroyed through that interface before it becomes
1700 // invalid.
1701 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001702 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001703 }
1704
Steven Thomas0123ac62018-07-12 11:32:34 -07001705 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1706 // called below. Clear the reference now so we don't accidentally use it
1707 // later.
1708 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001709
Steven Thomasb02664d2017-07-26 18:48:28 -07001710 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001711 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001712 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001713
Steven Thomasb02664d2017-07-26 18:48:28 -07001714 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001715 // Delete the current instance before creating the new one
1716 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1717 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1718 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001719 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720
Lloyd Pique441d5042018-10-18 16:49:51 -07001721 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001722 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001723
1724 if (vrFlingerRequestsDisplay) {
1725 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001726 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001727
1728 mVisibleRegionsDirty = true;
1729 invalidateHwcGeometry();
1730
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001731 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001732 display = getDefaultDisplayDeviceLocked();
1733 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001734 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001735
Steven Thomasb02664d2017-07-26 18:48:28 -07001736 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001737 const nsecs_t vsyncPeriod = getVsyncPeriod();
1738 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001739
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001740 // The present fences returned from vr_hwc are not an accurate
1741 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001742 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001743
Steven Thomasb02664d2017-07-26 18:48:28 -07001744 // Use phase of 0 since phase is not known.
1745 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001746 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001747 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001748
Ana Krulecc2870422019-01-29 19:00:58 -08001749 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001750
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001751 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001752 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001753}
1754
Ady Abraham11579302019-09-19 12:35:58 -07001755bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1756 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001757 // We are storing the last 2 present fences. If sf's phase offset is to be
1758 // woken up before the actual vsync but targeting the next vsync, we need to check
1759 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001760 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1761 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001762
Ady Abraham11579302019-09-19 12:35:58 -07001763 if (fence == Fence::NO_FENCE) {
1764 return false;
1765 }
1766
1767 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1768 fence->wait(graceTimeMs);
1769 }
1770
1771 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001772}
1773
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001774void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001775 DisplayStatInfo stats;
1776 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001777 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001778 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001779 mExpectedPresentTime.store(
1780 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001781}
1782
Dominik Laskowski22488f62019-03-28 09:53:04 -07001783void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001784 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001785 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001786 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001787 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001788 // calculate the expected present time once and use the cached
1789 // value throughout this frame to make sure all layers are
1790 // seeing this same value.
1791 populateExpectedPresentTime();
1792
Ady Abraham11579302019-09-19 12:35:58 -07001793 // When Backpressure propagation is enabled we want to give a small grace period
1794 // for the present fence to fire instead of just giving up on this frame to handle cases
1795 // where present fence is just about to get signaled.
1796 const int graceTimeForPresentFenceMs =
1797 (mPropagateBackpressure &&
1798 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1799 ? 1
1800 : 0;
1801 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1802 previousFrameMissed(
1803 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001804 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1805 mHadDeviceComposition && frameMissed};
1806 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1807 mHadClientComposition && frameMissed};
1808
Alec Mouricc0fc602019-02-26 21:45:19 -08001809 if (frameMissed) {
1810 mFrameMissedCount++;
1811 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001812 if (mMissedFrameJankCount == 0) {
1813 mMissedFrameJankStart = systemTime();
1814 }
1815 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001816 }
1817
Alec Mouri40189b02019-03-05 15:07:54 -08001818 if (hwcFrameMissed) {
1819 mHwcFrameMissedCount++;
1820 }
1821
1822 if (gpuFrameMissed) {
1823 mGpuFrameMissedCount++;
1824 }
1825
Ady Abrahamadb9a992019-09-19 21:21:55 +00001826 if (frameMissed && mPropagateBackpressure) {
1827 if ((hwcFrameMissed && !gpuFrameMissed) ||
1828 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001829 signalLayerUpdate();
1830 break;
1831 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001832 }
Dan Stoza50182882016-07-08 12:02:20 -07001833
Alec Mouri989ddbe2020-02-06 09:26:19 -08001834 // Our jank window is always at least 100ms since we missed a
1835 // frame...
1836 static constexpr nsecs_t kMinJankyDuration =
1837 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1838 // ...but if it's larger than 1s then we missed the trace cutoff.
1839 static constexpr nsecs_t kMaxJankyDuration =
1840 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1841 // If we're in a user build then don't push any atoms
1842 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1843 const auto displayDevice = getDefaultDisplayDeviceLocked();
1844 // Only report jank when the display is on, as displays in DOZE
1845 // power mode may operate at a different frame rate than is
1846 // reported in their config, which causes noticeable (but less
1847 // severe) jank.
1848 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1849 const nsecs_t currentTime = systemTime();
1850 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1851 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1852 ATRACE_NAME("Jank detected");
1853 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1854 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1855 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1856 jankyDurationMillis, mMissedFrameJankCount);
1857 }
1858
1859 // We either reported a jank event or we missed the trace
1860 // window, so clear counters here.
1861 if (jankDuration > kMinJankyDuration) {
1862 mMissedFrameJankCount = 0;
1863 mMissedFrameJankStart = 0;
1864 }
1865 }
1866 }
1867
Steven Thomas050b2c82017-03-06 11:45:16 -08001868 // Now that we're going to make it to the handleMessageTransaction()
1869 // call below it's safe to call updateVrFlinger(), which will
1870 // potentially trigger a display handoff.
1871 updateVrFlinger();
1872
Dan Stoza6b9454d2014-11-07 16:00:59 -08001873 bool refreshNeeded = handleMessageTransaction();
1874 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001875
Ana Krulecc84d09b2019-11-02 23:10:29 +01001876 // Layers need to get updated (in the previous line) before we can use them for
1877 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001878 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1879 // and may eventually call to ~Layer() if it holds the last reference
1880 {
1881 Mutex::Autolock _l(mStateLock);
1882 mScheduler->chooseRefreshRateForContent();
1883 }
1884
Ana Krulecc84d09b2019-11-02 23:10:29 +01001885 if (performSetActiveConfig()) {
1886 break;
1887 }
1888
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001889 updateCursorAsync();
1890 updateInputFlinger();
1891
Dan Stoza58784442014-12-02 16:58:17 -08001892 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001893 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001894 // Signal a refresh if a transaction modified the window state,
1895 // a new buffer was latched, or if HWC has requested a full
1896 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001897 if (mFrameStartTime <= 0) {
1898 // We should only use the time of the first invalidate
1899 // message that signals a refresh as the beginning of the
1900 // frame. Otherwise the real frame time will be
1901 // underestimated.
1902 mFrameStartTime = frameStart;
1903 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001904 signalRefresh();
1905 }
1906 break;
1907 }
1908 case MessageQueue::REFRESH: {
1909 handleMessageRefresh();
1910 break;
1911 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001912 }
1913}
1914
Dan Stoza6b9454d2014-11-07 16:00:59 -08001915bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001916 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001917 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001918
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001919 bool flushedATransaction = flushTransactionQueues();
1920
1921 bool runHandleTransaction = transactionFlags &&
1922 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1923
1924 if (runHandleTransaction) {
1925 handleTransaction(eTransactionMask);
1926 } else {
1927 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001928 }
1929
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001930 if (transactionFlushNeeded()) {
1931 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001932 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001933
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001934 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001935}
1936
Mathias Agopian4fec8732012-06-29 14:12:52 -07001937void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001939
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001940 mRefreshPending = false;
1941
Lloyd Piqueab039b52019-02-13 14:22:42 -08001942 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001943 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001944 for (const auto& [_, display] : mDisplays) {
1945 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1946 }
1947 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001948 if (auto layerFE = layer->getCompositionEngineLayerFE())
1949 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001950 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001951 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1952 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001953 if (auto layerFE = layer->getCompositionEngineLayerFE())
1954 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001955 }
1956
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001957 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001958 refreshArgs.outputColorSetting = useColorManagement
1959 ? mDisplayColorSetting
1960 : compositionengine::OutputColorSetting::kUnmanaged;
1961 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1962 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001963
1964 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1965 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001966 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001967
1968 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1969 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1970 mDrawingState.colorMatrixChanged = false;
1971 }
1972
1973 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1974
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001975 if (mDebugRegion != 0) {
1976 refreshArgs.devOptFlashDirtyRegionsDelay =
1977 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1978 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001979
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001980 mGeometryInvalid = false;
1981
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001982 // Store the present time just before calling to the composition engine so we could notify
1983 // the scheduler.
1984 const auto presentTime = systemTime();
1985
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001986 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001987 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1988 // Reset the frame start time now that we've recorded this frame.
1989 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001990
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001991 mScheduler->onDisplayRefreshed(presentTime);
1992
David Sodmanfa9b2af2017-12-24 13:28:59 -08001993 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001994 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001995
Lloyd Pique66d68602019-02-13 14:23:31 -08001996 mHadClientComposition =
1997 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1998 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001999 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2000 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002001 });
2002 mHadDeviceComposition =
2003 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2004 auto& displayDevice = tokenDisplayPair.second;
2005 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2006 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002007 mReusedClientComposition =
2008 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2009 auto& displayDevice = tokenDisplayPair.second;
2010 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2011 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002012
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002013 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002014
David Sodman7e4ae112018-02-09 15:02:28 -08002015 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002016 if (mVisibleRegionsDirty) {
2017 mVisibleRegionsDirty = false;
2018 if (mTracingEnabled) {
2019 mTracing.notify("visibleRegionsDirty");
2020 }
2021 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002022
2023 if (mCompositionEngine->needsAnotherUpdate()) {
2024 signalLayerUpdate();
2025 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002027
David Sodmanfa9b2af2017-12-24 13:28:59 -08002028
2029bool SurfaceFlinger::handleMessageInvalidate() {
2030 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002031 bool refreshNeeded = handlePageFlip();
2032
Vishnu Nair4351ad52019-02-11 14:13:02 -08002033 if (mVisibleRegionsDirty) {
2034 computeLayerBounds();
2035 }
2036
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002037 for (auto& layer : mLayersPendingRefresh) {
2038 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002039 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002040 invalidateLayerStack(layer, visibleReg);
2041 }
2042 mLayersPendingRefresh.clear();
2043 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002044}
2045
Ana Krulece588e312018-09-18 12:32:24 -07002046void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2047 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 // Update queue of past composite+present times and determine the
2049 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002050 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002052 while (!getBE().mCompositePresentTimes.empty()) {
2053 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 // Cached values should have been updated before calling this method,
2055 // which helps avoid duplicate syscalls.
2056 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2057 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2058 break;
2059 }
2060 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002061 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 }
2063
2064 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002065 while (getBE().mCompositePresentTimes.size() > 16) {
2066 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002067 }
2068
Ana Krulece588e312018-09-18 12:32:24 -07002069 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002070}
2071
Ana Krulece588e312018-09-18 12:32:24 -07002072void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2073 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002074 // Integer division and modulo round toward 0 not -inf, so we need to
2075 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002076 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2077 ? (stats.vsyncPeriod -
2078 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2079 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002080
Ady Abraham9e16a482019-12-03 17:19:41 -08002081 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002082 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002083 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002084 }
2085
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002086 // Snap the latency to a value that removes scheduling jitter from the
2087 // composition and present times, which often have >1ms of jitter.
2088 // Reducing jitter is important if an app attempts to extrapolate
2089 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002090 // Snapping also allows an app to precisely calculate
2091 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002092 nsecs_t bias = stats.vsyncPeriod / 2;
2093 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2094 nsecs_t snappedCompositeToPresentLatency =
2095 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002096
David Sodman99974d22017-11-28 12:04:33 -08002097 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002098 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2099 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002100 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101}
2102
David Sodman2b406362017-12-15 13:33:47 -08002103void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002104{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 ATRACE_CALL();
2106 ALOGV("postComposition");
2107
Brian Andersonf6386862016-10-31 16:34:13 -07002108 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002109 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002110 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002111 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002112 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002113 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002114
David Sodman73beded2017-11-15 11:56:06 -08002115 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002116 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002117 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002119 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2120 ->getRenderSurface()
2121 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002122 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002123 } else {
2124 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2125 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002126
David Sodman73beded2017-11-15 11:56:06 -08002127 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002128 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2129 mPreviousPresentFences[0] = displayDevice
2130 ? getHwComposer().getPresentFence(*displayDevice->getId())
2131 : Fence::NO_FENCE;
2132 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002133 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002134
Ana Krulece588e312018-09-18 12:32:24 -07002135 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002136 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002137
Lloyd Piqueab039b52019-02-13 14:22:42 -08002138 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2139 // be sampled a little later than when we started doing work for this frame,
2140 // but that should be okay since updateCompositorTiming has snapping logic.
2141 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2142 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002143 CompositorTiming compositorTiming;
2144 {
David Sodman99974d22017-11-28 12:04:33 -08002145 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2146 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002147 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002148
Edgar Arriaga844fa672020-01-16 14:21:42 -08002149 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002150 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2151 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002152 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002153 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002154 }
Robert Carr2047fae2016-11-28 14:09:09 -08002155 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002156
Ady Abraham92fa2f42020-02-11 15:33:56 -08002157 if (displayDevice && displayDevice->isPrimary() &&
2158 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002159 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002160 }
2161
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002162 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2164 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002165 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002166 }
2167 }
2168
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002169 if (mAnimCompositionPending) {
2170 mAnimCompositionPending = false;
2171
Brian Anderson4e606e32017-03-16 15:34:57 -07002172 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002173 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002174 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002175 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002176 // The HWC doesn't support present fences, so use the refresh
2177 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002178 const nsecs_t presentTime =
2179 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002180 mAnimFrameTracker.setActualPresentTime(presentTime);
2181 }
2182 mAnimFrameTracker.advanceFrame();
2183 }
Dan Stozab90cf072015-03-05 11:05:59 -08002184
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002185 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002186 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002187 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002188 }
2189
Vishnu Nair9b079a22020-01-21 14:36:08 -08002190 if (mReusedClientComposition) {
2191 mTimeStats->incrementClientCompositionReusedFrames();
2192 }
2193
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002194 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002195
Alec Mouri717bcb62020-02-10 17:07:19 -08002196 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2197 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2198 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2199
Lloyd Pique32cbe282018-10-19 13:09:22 -07002200 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2201 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002202 return;
2203 }
2204
2205 nsecs_t currentTime = systemTime();
2206 if (mHasPoweredOff) {
2207 mHasPoweredOff = false;
2208 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002209 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002210 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002211 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2212 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002213 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002214 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002215 }
David Sodman4a36e932017-11-07 14:29:47 -08002216 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002217 }
David Sodman4a36e932017-11-07 14:29:47 -08002218 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002219
2220 {
2221 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002222 if (mTexturePool.size() < mTexturePoolSize) {
2223 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002224 const size_t offset = mTexturePool.size();
2225 mTexturePool.resize(mTexturePoolSize);
2226 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2227 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002228 } else if (mTexturePool.size() > mTexturePoolSize) {
2229 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2230 const size_t offset = mTexturePoolSize;
2231 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2232 mTexturePool.resize(mTexturePoolSize);
2233 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002234 }
2235 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002236
Ady Abrahambe0f9482019-04-24 15:41:53 -07002237 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002238 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002239
Kevin DuBois413287f2019-02-25 08:46:47 -08002240 if (mLumaSampling && mRegionSamplingThread) {
2241 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002242 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002243
2244 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2245 // side-effect of getTotalSize(), so we check that again here
2246 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002247 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002248 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2249 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002250}
2251
Vishnu Nair4351ad52019-02-11 14:13:02 -08002252void SurfaceFlinger::computeLayerBounds() {
2253 for (const auto& pair : mDisplays) {
2254 const auto& displayDevice = pair.second;
2255 const auto display = displayDevice->getCompositionDisplay();
2256 for (const auto& layer : mDrawingState.layersSortedByZ) {
2257 // only consider the layers on the given layer stack
2258 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002259 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002260 }
2261
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002262 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2263 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002264 }
2265 }
2266}
2267
David Sodmanfa9b2af2017-12-24 13:28:59 -08002268void SurfaceFlinger::postFrame()
2269{
2270 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002271 const auto display = getDefaultDisplayDeviceLocked();
2272 if (display && getHwComposer().isConnected(*display->getId())) {
2273 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002274 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2275 logFrameStats();
2276 }
2277 }
2278}
2279
Mathias Agopian87baae12012-07-31 12:38:26 -07002280void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281{
Mathias Agopian841cde52012-03-01 15:44:37 -08002282 ATRACE_CALL();
2283
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002284 // here we keep a copy of the drawing state (that is the state that's
2285 // going to be overwritten by handleTransactionLocked()) outside of
2286 // mStateLock so that the side-effects of the State assignment
2287 // don't happen with mStateLock held (which can cause deadlocks).
2288 State drawingState(mDrawingState);
2289
Mathias Agopianca4d3602011-05-19 15:38:14 -07002290 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002291 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292
Mathias Agopianca4d3602011-05-19 15:38:14 -07002293 // Here we're guaranteed that some transaction flags are set
2294 // so we can call handleTransactionLocked() unconditionally.
2295 // We call getTransactionFlags(), which will also clear the flags,
2296 // with mStateLock held to guarantee that mCurrentState won't change
2297 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002298
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002299 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002300 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002301 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002302
Mathias Agopianca4d3602011-05-19 15:38:14 -07002303 mDebugInTransaction = 0;
2304 invalidateHwcGeometry();
2305 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002306}
2307
Lloyd Piqueba04e622017-12-14 17:11:26 -08002308void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2309 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002310 const std::optional<DisplayIdentificationInfo> info =
2311 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312
Dominik Laskowski075d3172018-05-24 15:50:06 -07002313 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002314 continue;
2315 }
2316
Dominik Laskowski55c85402020-01-21 16:25:47 -08002317 const DisplayId displayId = info->id;
2318 const auto it = mPhysicalDisplayTokens.find(displayId);
2319
Lloyd Piqueba04e622017-12-14 17:11:26 -08002320 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002321 if (it == mPhysicalDisplayTokens.end()) {
2322 ALOGV("Creating display %s", to_string(displayId).c_str());
2323
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002324 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002325 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002326 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002327
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002329 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 state.isSecure = true; // All physical displays are currently considered secure.
2331 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002332
2333 sp<IBinder> token = new BBinder();
2334 mCurrentState.displays.add(token, state);
2335 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2336
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002338 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002340 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002341
Dominik Laskowski55c85402020-01-21 16:25:47 -08002342 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002343 if (index >= 0) {
2344 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2345 mInterceptor->saveDisplayDeletion(state.sequenceId);
2346 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002347 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002348 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002349 }
2350
2351 processDisplayChangesLocked();
2352 }
2353
2354 mPendingHotplugEvents.clear();
2355}
2356
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002357void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002358 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2359 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002360}
2361
Lloyd Pique99d3da52018-01-22 17:48:03 -08002362sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002363 const wp<IBinder>& displayToken,
2364 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002365 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002366 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002367 auto displayId = compositionDisplay->getDisplayId();
2368 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002369 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002370 creationArgs.isSecure = state.isSecure;
2371 creationArgs.displaySurface = dispSurface;
2372 creationArgs.hasWideColorGamut = false;
2373 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002374
Dominik Laskowski55c85402020-01-21 16:25:47 -08002375 if (const auto& physical = state.physical) {
2376 creationArgs.connectionType = physical->type;
2377 }
2378
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002379 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002380 creationArgs.isPrimary = isInternalDisplay;
2381
2382 if (useColorManagement && displayId) {
2383 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002385 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002386 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002388
Dominik Laskowski7e045462018-05-30 13:02:02 -07002389 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002391 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392 }
tangrobin6753a022018-08-10 10:58:54 +08002393 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 if (displayId) {
2396 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002397 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002399 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400
Lloyd Pique90c115d2018-09-18 21:39:42 -07002401 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002403 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405 // Make sure that composition can never be stalled by a virtual display
2406 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002407 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002408 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2410 }
2411
Dominik Laskowski718f9602019-11-09 20:01:35 -08002412 creationArgs.physicalOrientation =
2413 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002414
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002416 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002418 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419
2420 if (maxFrameBufferAcquiredBuffers >= 3) {
2421 nativeWindowSurface->preallocateBuffers();
2422 }
2423
2424 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002425 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002426 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002428 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002430 display->getCompositionDisplay()->setColorProfile(
2431 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2432 RenderIntent::COLORIMETRIC,
2433 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434 if (!state.isVirtual()) {
2435 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002436 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2437 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002438 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 display->setLayerStack(state.layerStack);
2441 display->setProjection(state.orientation, state.viewport, state.frame);
2442 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445}
2446
Lloyd Pique347200f2017-12-14 17:00:15 -08002447void SurfaceFlinger::processDisplayChangesLocked() {
2448 // here we take advantage of Vector's copy-on-write semantics to
2449 // improve performance by skipping the transaction entirely when
2450 // know that the lists are identical
2451 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2452 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2453 if (!curr.isIdenticalTo(draw)) {
2454 mVisibleRegionsDirty = true;
2455 const size_t cc = curr.size();
2456 size_t dc = draw.size();
2457
2458 // find the displays that were removed
2459 // (ie: in drawing state but not in current state)
2460 // also handle displays that changed
2461 // (ie: displays that are in both lists)
2462 for (size_t i = 0; i < dc;) {
2463 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2464 if (j < 0) {
2465 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002467 // Save display ID before disconnecting.
2468 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002469 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002470
2471 if (!display->isVirtual()) {
2472 LOG_ALWAYS_FATAL_IF(!displayId);
2473 dispatchDisplayHotplugEvent(displayId->value, false);
2474 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002476
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002477 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 } else {
2479 // this display is in both lists. see if something changed.
2480 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002481 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2483 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2484 if (state_binder != draw_binder) {
2485 // changing the surface is like destroying and
2486 // recreating the DisplayDevice, so we just remove it
2487 // from the drawing state, so that it get re-added
2488 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002489 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002490 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002491 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002492 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 mDrawingState.displays.removeItemsAt(i);
2494 dc--;
2495 // at this point we must loop to the next item
2496 continue;
2497 }
2498
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 }
2503 if ((state.orientation != draw[i].orientation) ||
2504 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002505 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 }
2507 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002509 if (display->isPrimary()) {
2510 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2511 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002512 }
2513 }
2514 }
2515 ++i;
2516 }
2517
2518 // find displays that were added
2519 // (ie: in current state but not in drawing state)
2520 for (size_t i = 0; i < cc; i++) {
2521 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2522 const DisplayDeviceState& state(curr[i]);
2523
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002524 int width = 0;
2525 int height = 0;
2526 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2527 if (state.physical) {
2528 const auto& activeConfig =
2529 getCompositionEngine().getHwComposer().getActiveConfig(
2530 state.physical->id);
2531 width = activeConfig->getWidth();
2532 height = activeConfig->getHeight();
2533 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2534 } else if (state.surface != nullptr) {
2535 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2536 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2537 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2538 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2539 int intPixelFormat;
2540 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2541 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2542 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2543 } else {
2544 // Virtual displays without a surface are dormant:
2545 // they have external state (layer stack, projection,
2546 // etc.) but no internal state (i.e. a DisplayDevice).
2547 continue;
2548 }
2549
2550 compositionengine::DisplayCreationArgsBuilder builder;
2551 if (const auto& physical = state.physical) {
2552 builder.setPhysical({physical->id, physical->type});
2553 }
2554 builder.setPixels(ui::Size(width, height));
2555 builder.setPixelFormat(pixelFormat);
2556 builder.setIsSecure(state.isSecure);
2557 builder.setLayerStackId(state.layerStack);
2558 builder.setPowerAdvisor(&mPowerAdvisor);
2559 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2560 getHwComposer().isUsingVrComposer());
2561 builder.setName(state.displayName);
2562 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2563
Lloyd Pique542307f2018-10-19 13:24:08 -07002564 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 sp<IGraphicBufferProducer> producer;
2566 sp<IGraphicBufferProducer> bqProducer;
2567 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002568 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002569
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002570 std::optional<DisplayId> displayId = compositionDisplay->getId();
2571
Dominik Laskowski663bd282018-04-19 15:26:54 -07002572 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002573 sp<VirtualDisplaySurface> vds =
2574 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2575 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002576
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002577 dispSurface = vds;
2578 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002579 } else {
2580 ALOGE_IF(state.surface != nullptr,
2581 "adding a supported display, but rendering "
2582 "surface is provided (%p), ignoring it",
2583 state.surface.get());
2584
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002585 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002587 producer = bqProducer;
2588 }
2589
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002592 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002593 setupNewDisplayDeviceInternal(displayToken,
2594 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002595 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002596 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002598 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002599 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002600
2601 const auto displayDevice = mDisplays[displayToken];
2602 if (displayDevice->isPrimary()) {
2603 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2604 displayDevice->getHeight());
2605 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 }
2607 }
2608 }
2609 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002610
2611 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002612}
2613
Mathias Agopian87baae12012-07-31 12:38:26 -07002614void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002615{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002616 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2617
Dan Stoza7dde5992015-05-22 09:51:44 -07002618 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002619 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002620 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002621 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002622
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 /*
2624 * Traversal of the children
2625 * (perform the transaction for each of them if needed)
2626 */
2627
Marissa Wall06255332019-03-27 13:48:27 -07002628 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002629 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002631 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632
2633 const uint32_t flags = layer->doTransaction(0);
2634 if (flags & Layer::eVisibleRegion)
2635 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002636
2637 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002638 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002639 }
Robert Carr2047fae2016-11-28 14:09:09 -08002640 });
Marissa Wall06255332019-03-27 13:48:27 -07002641 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 }
2643
2644 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002645 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 */
2647
Mathias Agopiane57f2922012-08-09 16:29:12 -07002648 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002649 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002650 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002651 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002653 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002654 // The transform hint might have changed for some layers
2655 // (either because a display has changed, or because a layer
2656 // as changed).
2657 //
2658 // Walk through all the layers in currentLayers,
2659 // and update their transform hint.
2660 //
2661 // If a layer is visible only on a single display, then that
2662 // display is used to calculate the hint, otherwise we use the
2663 // default display.
2664 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002665 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002666 // the hint is set before we acquire a buffer from the surface texture.
2667 //
2668 // NOTE: layer transactions have taken place already, so we use their
2669 // drawing state. However, SurfaceFlinger's own transaction has not
2670 // happened yet, so we must use the current state layer list
2671 // (soon to become the drawing state list).
2672 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002673 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002674 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002675 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002676 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002677 // NOTE: we rely on the fact that layers are sorted by
2678 // layerStack first (so we don't have to traverse the list
2679 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002681 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002682 currentlayerStack = layerStack;
2683 // figure out if this layerstack is mirrored
2684 // (more than one display) if so, pick the default display,
2685 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 hintDisplay = nullptr;
2687 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002688 if (display->getCompositionDisplay()
2689 ->belongsInOutput(layer->getLayerStack(),
2690 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 if (hintDisplay) {
2692 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002693 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002695 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002696 }
2697 }
2698 }
2699 }
Chet Haase91d25932013-04-11 15:24:55 -07002700
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002702 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2703 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002704
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002705 // could be null when this layer is using a layerStack
2706 // that is not visible on any display. Also can occur at
2707 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002708 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002709 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002710
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002711 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002712 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002713 if (hintDisplay) {
2714 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002715 }
Robert Carr2047fae2016-11-28 14:09:09 -08002716
2717 first = false;
2718 });
Mathias Agopian84300952012-11-21 16:02:13 -08002719 }
2720
2721
Mathias Agopian3559b072012-08-15 13:46:03 -07002722 /*
2723 * Perform our own transaction if needed
2724 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725
2726 if (mLayersAdded) {
2727 mLayersAdded = false;
2728 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002729 mVisibleRegionsDirty = true;
2730 }
2731
2732 // some layers might have been removed, so
2733 // we need to update the regions they're exposing.
2734 if (mLayersRemoved) {
2735 mLayersRemoved = false;
2736 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002737 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002739 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002741 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002742 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002743 }
Robert Carr2047fae2016-11-28 14:09:09 -08002744 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 }
2746
Vishnu Nairec0ab382019-02-13 15:32:56 -08002747 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002749}
2750
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002751void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002752 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002753 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002754 return;
2755 }
2756
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002757 if (mVisibleRegionsDirty || mInputInfoChanged) {
2758 mInputInfoChanged = false;
2759 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002760 } else if (mInputWindowCommands.syncInputWindows) {
2761 // If the caller requested to sync input windows, but there are no
2762 // changes to input windows, notify immediately.
2763 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002764 }
2765
Arthur Hung6cbb9752019-09-05 16:38:18 +08002766 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002767}
2768
2769void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002770 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002771
2772 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2773 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002774 // When calculating the screen bounds we ignore the transparent region since it may
2775 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002776 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002777 }
2778 });
chaviw291d88a2019-02-14 10:33:58 -08002779
2780 mInputFlinger->setInputWindows(inputHandles,
2781 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2782 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002783}
2784
Vishnu Nairec0ab382019-02-13 15:32:56 -08002785void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002786 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002787 mPendingInputWindowCommands.clear();
2788}
2789
Riley Andrews03414a12014-07-01 14:22:59 -07002790void SurfaceFlinger::updateCursorAsync()
2791{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002792 compositionengine::CompositionRefreshArgs refreshArgs;
2793 for (const auto& [_, display] : mDisplays) {
2794 if (display->getId()) {
2795 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002796 }
2797 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002798
2799 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002800}
2801
Ady Abraham2139f732019-11-13 18:56:40 -08002802void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002803 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2804 // If this is called from the main thread mStateLock must be locked before
2805 // Currently the only way to call this function from the main thread is from
2806 // Sheduler::chooseRefreshRateForContent
2807
2808 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002809 changeRefreshRateLocked(refreshRate, event);
2810}
2811
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002812void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2813 if (mScheduler) {
2814 // In practice it's not allowed to hotplug in/out the primary display once it's been
2815 // connected during startup, but some tests do it, so just warn and return.
2816 ALOGW("Can't re-init scheduler");
2817 return;
2818 }
2819
Ady Abraham2139f732019-11-13 18:56:40 -08002820 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002821 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002822 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002823 primaryDisplayId),
2824 currentConfig);
2825 mRefreshRateStats =
2826 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2827 currentConfig, HWC_POWER_MODE_OFF);
2828 mRefreshRateStats->setConfigMode(currentConfig);
2829
Ady Abraham9e16a482019-12-03 17:19:41 -08002830 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2831
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002832 // start the EventThread
2833 mScheduler =
2834 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002835 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002836 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002837 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002838 impl::EventThread::InterceptVSyncsCallback());
2839 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002840 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002841 [this](nsecs_t timestamp) {
2842 mInterceptor->saveVSyncEvent(timestamp);
2843 });
2844
2845 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2846 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002847 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002848
2849 mRegionSamplingThread =
2850 new RegionSamplingThread(*this, *mScheduler,
2851 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002852 // Dispatch a config change request for the primary display on scheduler
2853 // initialization, so that the EventThreads always contain a reference to a
2854 // prior configuration.
2855 //
2856 // This is a bit hacky, but this avoids a back-pointer into the main SF
2857 // classes from EventThread, and there should be no run-time binder cost
2858 // anyway since there are no connected apps at this point.
2859 const nsecs_t vsyncPeriod =
2860 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2861 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2862 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002863}
2864
Mathias Agopian4fec8732012-06-29 14:12:52 -07002865void SurfaceFlinger::commitTransaction()
2866{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002867 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002868
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002869 mTransactionPending = false;
2870 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002871 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Lloyd Pique58e24a32019-08-01 15:50:14 -07002874void SurfaceFlinger::commitTransactionLocked() {
2875 if (!mLayersPendingRemoval.isEmpty()) {
2876 // Notify removed layers now that they can't be drawn from
2877 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002878 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002879
2880 // Ensure any buffers set to display on any children are released.
2881 if (l->isRemovedFromCurrentState()) {
2882 l->latchAndReleaseBuffer();
2883 }
2884
2885 // If the layer has been removed and has no parent, then it will not be reachable
2886 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2887 // ensure we can copy its current to drawing state.
2888 if (!l->getParent()) {
2889 mOffscreenLayers.emplace(l.get());
2890 }
2891 }
2892 mLayersPendingRemoval.clear();
2893 }
2894
2895 // If this transaction is part of a window animation then the next frame
2896 // we composite should be considered an animation as well.
2897 mAnimCompositionPending = mAnimTransactionPending;
2898
2899 mDrawingState = mCurrentState;
2900 // clear the "changed" flags in current state
2901 mCurrentState.colorMatrixChanged = false;
2902
Edgar Arriaga844fa672020-01-16 14:21:42 -08002903 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002904 layer->commitChildList();
2905
2906 // If the layer can be reached when traversing mDrawingState, then the layer is no
2907 // longer offscreen. Remove the layer from the offscreenLayer set.
2908 if (mOffscreenLayers.count(layer)) {
2909 mOffscreenLayers.erase(layer);
2910 }
2911 });
2912
2913 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002914 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002915}
2916
Nataniel Borges2b796da2019-02-15 13:32:18 -08002917void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2918 if (mTracingEnabledChanged) {
2919 mTracingEnabled = mTracing.isEnabled();
2920 mTracingEnabledChanged = false;
2921 }
2922
2923 // Synchronize with Tracing thread
2924 std::unique_lock<std::mutex> lock;
2925 if (mTracingEnabled) {
2926 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2927 }
2928
2929 lockedOperation();
2930
2931 // Synchronize with Tracing thread
2932 if (mTracingEnabled) {
2933 lock.unlock();
2934 }
2935}
2936
chaviw74d90ad2019-04-26 14:45:26 -07002937void SurfaceFlinger::commitOffscreenLayers() {
2938 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002939 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002940 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2941 if (!trFlags) return;
2942
2943 layer->doTransaction(0);
2944 layer->commitChildList();
2945 });
2946 }
2947}
2948
Chia-I Wuab0c3192017-08-01 11:29:00 -07002949void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002950 for (const auto& [token, displayDevice] : mDisplays) {
2951 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002952 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002953 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002954 }
2955 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002956}
2957
Dan Stoza6b9454d2014-11-07 16:00:59 -08002958bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959{
Ady Abraham09bd3922019-04-08 10:44:56 -07002960 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002961 ALOGV("handlePageFlip");
2962
Brian Andersond6927fb2016-07-23 23:37:30 -07002963 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964
Mathias Agopian4fec8732012-06-29 14:12:52 -07002965 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002966 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002967 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002968
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002969 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2970
Eric Penner51c59cd2014-07-28 19:51:58 -07002971 // Store the set of layers that need updates. This set must not change as
2972 // buffers are being latched, as this could result in a deadlock.
2973 // Example: Two producers share the same command stream and:
2974 // 1.) Layer 0 is latched
2975 // 2.) Layer 0 gets a new frame
2976 // 2.) Layer 1 gets a new frame
2977 // 3.) Layer 1 is latched.
2978 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2979 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002980 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002981 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002983 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002984 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002985 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002986 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002987 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002988 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002989 } else {
2990 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002991 }
Robert Carr2047fae2016-11-28 14:09:09 -08002992 });
2993
chaviw49a108c2019-08-12 11:23:06 -07002994 // The client can continue submitting buffers for offscreen layers, but they will not
2995 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2996 // layers to ensure dequeueBuffer doesn't block indefinitely.
2997 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002998 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002999 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3000 }
3001
Lloyd Piquef2c79392018-12-20 16:23:33 -08003002 if (!mLayersWithQueuedFrames.empty()) {
3003 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3004 // writes to Layer current state. See also b/119481871
3005 Mutex::Autolock lock(mStateLock);
3006
3007 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003008 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003009 mLayersPendingRefresh.push_back(layer);
3010 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003011 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003012 if (layer->isBufferLatched()) {
3013 newDataLatched = true;
3014 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003015 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003016 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003017
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003018 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003019
3020 // If we will need to wake up at some time in the future to deal with a
3021 // queued frame that shouldn't be displayed during this vsync period, wake
3022 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003023 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003024 signalLayerUpdate();
3025 }
3026
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003027 // enter boot animation on first buffer latch
3028 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3029 ALOGI("Enter boot animation");
3030 mBootStage = BootStage::BOOTANIMATION;
3031 }
3032
Edgar Arriaga844fa672020-01-16 14:21:42 -08003033 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003034
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003036 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037}
3038
Mathias Agopianad456f92011-01-13 17:53:01 -08003039void SurfaceFlinger::invalidateHwcGeometry()
3040{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003042}
3043
Robert Carrc0df3122019-04-11 13:18:21 -07003044status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3045 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3046 const sp<IBinder>& parentHandle,
3047 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003048 // add this layer to the current state list
3049 {
3050 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003051 sp<Layer> parent;
3052 if (parentHandle != nullptr) {
3053 parent = fromHandle(parentHandle);
3054 if (parent == nullptr) {
3055 return NAME_NOT_FOUND;
3056 }
3057 } else {
3058 parent = parentLayer;
3059 }
3060
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003062 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003063 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003064 return NO_MEMORY;
3065 }
Robert Carrc0df3122019-04-11 13:18:21 -07003066
3067 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3068
Robert Carrb89ea9d2018-12-10 13:01:14 -08003069 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003070 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003071 } else if (parent == nullptr) {
3072 lbc->onRemovedFromCurrentState();
3073 } else if (parent->isRemovedFromCurrentState()) {
3074 parent->addChild(lbc);
3075 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003076 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 parent->addChild(lbc);
3078 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003079
Yiwei Zhang243b3782018-05-15 17:40:04 -07003080 if (gbc != nullptr) {
3081 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3082 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3083 mMaxGraphicBufferProducerListSize,
3084 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3085 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003086 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003087 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003089 }
3090
Mathias Agopian96f08192010-06-02 23:28:45 -07003091 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003092 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003093
Dan Stoza7d89d062015-04-30 13:29:25 -07003094 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003095}
3096
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003097uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003098 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003099}
3100
Mathias Agopian3f844832013-08-07 21:24:32 -07003101uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003102 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103}
3104
Mathias Agopian3f844832013-08-07 21:24:32 -07003105uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003106 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003107}
3108
3109uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003110 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003111 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003112 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003114 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 }
3116 return old;
3117}
3118
Marissa Wall713b63f2018-10-17 15:42:43 -07003119bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003120 // to prevent onHandleDestroyed from being called while the lock is held,
3121 // we must keep a copy of the transactions (specifically the composer
3122 // states) around outside the scope of the lock
3123 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003124 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003125 {
3126 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003127
Valerie Haufce31b82019-04-30 16:41:14 -07003128 auto it = mTransactionQueues.begin();
3129 while (it != mTransactionQueues.end()) {
3130 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003131
Valerie Haufce31b82019-04-30 16:41:14 -07003132 while (!transactionQueue.empty()) {
3133 const auto& transaction = transactionQueue.front();
3134 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003135 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003136 transaction.states)) {
3137 setTransactionFlags(eTransactionFlushNeeded);
3138 break;
3139 }
3140 transactions.push_back(transaction);
3141 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3142 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003143 transaction.buffer, transaction.postTime,
3144 transaction.privileged, transaction.hasListenerCallbacks,
3145 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003146 transactionQueue.pop();
3147 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003148 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003149
Valerie Haufce31b82019-04-30 16:41:14 -07003150 if (transactionQueue.empty()) {
3151 it = mTransactionQueues.erase(it);
3152 mTransactionCV.broadcast();
3153 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003154 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003155 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003156 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003157 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003158 return flushedATransaction;
3159}
3160
3161bool SurfaceFlinger::transactionFlushNeeded() {
3162 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003163}
3164
chaviwca27f252018-02-06 16:46:39 -08003165
Marissa Wall17b4e452018-12-26 16:32:34 -08003166bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003167 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003168 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003169 if (!useCachedExpectedPresentTime)
3170 populateExpectedPresentTime();
3171
3172 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003173 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3174 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3175 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3176 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3177 return false;
3178 }
3179
Marissa Wall713b63f2018-10-17 15:42:43 -07003180 for (const ComposerState& state : states) {
3181 const layer_state_t& s = state.state;
3182 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3183 continue;
3184 }
3185 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003186 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003187 }
3188 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003189 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003190}
3191
Valerie Hau9dab9732019-08-20 09:29:25 -07003192void SurfaceFlinger::setTransactionState(
3193 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3194 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3195 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3196 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003197 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003198
Valerie Haubc6ddb12019-03-08 11:10:15 -08003199 const int64_t postTime = systemTime();
3200
Robert Carr14167e02019-02-13 13:50:55 -08003201 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3202
Mathias Agopian698c0872011-06-28 19:09:31 -07003203 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003204
Marissa Wall713b63f2018-10-17 15:42:43 -07003205 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003206 auto itr = mTransactionQueues.find(applyToken);
3207 // if this is an animation frame, wait until prior animation frame has
3208 // been applied by SF
3209 if (flags & eAnimation) {
3210 while (itr != mTransactionQueues.end()) {
3211 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3212 if (CC_UNLIKELY(err != NO_ERROR)) {
3213 ALOGW_IF(err == TIMED_OUT,
3214 "setTransactionState timed out "
3215 "waiting for animation frame to apply");
3216 break;
3217 }
3218 itr = mTransactionQueues.find(applyToken);
3219 }
3220 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003221
3222 // Expected present time is computed and cached on invalidate, so it may be stale.
3223 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3224 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003225 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003226 uncacheBuffer, postTime, privileged,
3227 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003228 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003229 return;
3230 }
3231
Valerie Haubc6ddb12019-03-08 11:10:15 -08003232 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003233 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3234 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003235}
3236
Valerie Hau9dab9732019-08-20 09:29:25 -07003237void SurfaceFlinger::applyTransactionState(
3238 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3239 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3240 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3241 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3242 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003243 uint32_t transactionFlags = 0;
3244
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003245 if (flags & eAnimation) {
3246 // For window updates that are part of an animation we must wait for
3247 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003248 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003249 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003250 if (CC_UNLIKELY(err != NO_ERROR)) {
3251 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003252 // caller after a few seconds.
3253 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3254 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003255 mAnimTransactionPending = false;
3256 break;
3257 }
3258 }
3259 }
3260
chaviwca27f252018-02-06 16:46:39 -08003261 for (const DisplayState& display : displays) {
3262 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003263 }
3264
Valerie Hau9dab9732019-08-20 09:29:25 -07003265 // start and end registration for listeners w/ no surface so they can get their callback. Note
3266 // that listeners with SurfaceControls will start registration during setClientStateLocked
3267 // below.
3268 for (const auto& listener : listenerCallbacks) {
3269 mTransactionCompletedThread.startRegistration(listener);
3270 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003271 }
3272
Valerie Hau9dab9732019-08-20 09:29:25 -07003273 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003274 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003275 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003276 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3277 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003278 }
3279
Valerie Hau9dab9732019-08-20 09:29:25 -07003280 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003281 mTransactionCompletedThread.endRegistration(listenerCallback);
3282 }
3283
Marissa Walle2ffb422018-10-12 11:33:52 -07003284 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003285 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003286 mTransactionCompletedThread.sendCallbacks();
3287 }
3288 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003289
chaviw273171b2018-12-26 11:46:30 -08003290 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3291
Marissa Wall947d34e2019-03-29 14:03:53 -07003292 if (uncacheBuffer.isValid()) {
3293 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003294 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003295 }
3296
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003297 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3298 // anyway. This can be used as a flush mechanism for previous async transactions.
3299 // Empty animation transaction can be used to simulate back-pressure, so also force a
3300 // transaction for empty animation transactions.
3301 if (transactionFlags == 0 &&
3302 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003303 transactionFlags = eTransactionNeeded;
3304 }
3305
Marissa Wall06255332019-03-27 13:48:27 -07003306 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3307 // so we don't have to wake up again next frame to preform an uneeded traversal.
3308 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3309 transactionFlags = transactionFlags & (~eTraversalNeeded);
3310 mTraversalNeededMainThread = true;
3311 }
3312
Mathias Agopian386aa982011-11-07 21:58:03 -08003313 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003314 if (mInterceptor->isEnabled()) {
3315 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003316 }
Irvel468051e2016-06-13 16:44:44 -07003317
Mathias Agopian386aa982011-11-07 21:58:03 -08003318 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003319 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3320 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003321 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003322
3323 // if this is a synchronous transaction, wait for it to take effect
3324 // before returning.
3325 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003326 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003328 if (flags & eAnimation) {
3329 mAnimTransactionPending = true;
3330 }
chaviw4fe36852019-04-15 16:25:49 -07003331 if (mPendingInputWindowCommands.syncInputWindows) {
3332 mPendingSyncInputWindows = true;
3333 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003334
3335 // applyTransactionState can be called by either the main SF thread or by
3336 // another process through setTransactionState. While a given process may wish
3337 // to wait on synchronous transactions, the main SF thread should never
3338 // be blocked. Therefore, we only wait if isMainThread is false.
3339 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003340 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3341 if (CC_UNLIKELY(err != NO_ERROR)) {
3342 // just in case something goes wrong in SF, return to the
3343 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003344 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3345 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003346 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003347 break;
3348 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350 }
3351}
3352
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003353uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3354 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3355 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003356
Mathias Agopiane57f2922012-08-09 16:29:12 -07003357 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003358 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3359
3360 const uint32_t what = s.what;
3361 if (what & DisplayState::eSurfaceChanged) {
3362 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3363 state.surface = s.surface;
3364 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003365 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003366 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003367 if (what & DisplayState::eLayerStackChanged) {
3368 if (state.layerStack != s.layerStack) {
3369 state.layerStack = s.layerStack;
3370 flags |= eDisplayTransactionNeeded;
3371 }
3372 }
3373 if (what & DisplayState::eDisplayProjectionChanged) {
3374 if (state.orientation != s.orientation) {
3375 state.orientation = s.orientation;
3376 flags |= eDisplayTransactionNeeded;
3377 }
3378 if (state.frame != s.frame) {
3379 state.frame = s.frame;
3380 flags |= eDisplayTransactionNeeded;
3381 }
3382 if (state.viewport != s.viewport) {
3383 state.viewport = s.viewport;
3384 flags |= eDisplayTransactionNeeded;
3385 }
3386 }
3387 if (what & DisplayState::eDisplaySizeChanged) {
3388 if (state.width != s.width) {
3389 state.width = s.width;
3390 flags |= eDisplayTransactionNeeded;
3391 }
3392 if (state.height != s.height) {
3393 state.height = s.height;
3394 flags |= eDisplayTransactionNeeded;
3395 }
3396 }
3397
Mathias Agopiane57f2922012-08-09 16:29:12 -07003398 return flags;
3399}
3400
Robert Carr14167e02019-02-13 13:50:55 -08003401bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003402 IPCThreadState* ipc = IPCThreadState::self();
3403 const int pid = ipc->getCallingPid();
3404 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003405 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003406 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003407 return false;
3408 }
3409 return true;
3410}
3411
Marissa Wall3dad52d2019-03-22 14:03:19 -07003412uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003413 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3414 bool privileged,
3415 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003416 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003417
Valerie Hau9dab9732019-08-20 09:29:25 -07003418 for (auto& listener : s.listeners) {
3419 // note that startRegistration will not re-register if the listener has
3420 // already be registered for a prior surface control
3421 mTransactionCompletedThread.startRegistration(listener);
3422 listenerCallbacks.insert(listener);
3423 }
3424
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003425 sp<Layer> layer = nullptr;
3426 if (s.surface) {
3427 layer = fromHandle(s.surface);
3428 } else {
3429 // The client may provide us a null handle. Treat it as if the layer was removed.
3430 ALOGW("Attempt to set client state with a null layer handle");
3431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003433 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003434 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003435 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 return 0;
3438 }
3439
chaviw8b3871a2017-11-01 17:41:01 -07003440 uint32_t flags = 0;
3441
Garfield Tan8a3083e2018-12-03 13:21:07 -08003442 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003443
3444 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3445 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003446 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003447 layer->pushPendingState();
3448 }
3449
Valerie Hau871d6352020-01-29 08:44:02 -08003450 // Only set by BLAST adapter layers
3451 if (what & layer_state_t::eProducerDisconnect) {
3452 layer->onDisconnect();
3453 }
3454
chaviw8b3871a2017-11-01 17:41:01 -07003455 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003456 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003457 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003458 }
chaviw8b3871a2017-11-01 17:41:01 -07003459 }
3460 if (what & layer_state_t::eLayerChanged) {
3461 // NOTE: index needs to be calculated before we update the state
3462 const auto& p = layer->getParent();
3463 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003464 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003465 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003466 mCurrentState.layersSortedByZ.removeAt(idx);
3467 mCurrentState.layersSortedByZ.add(layer);
3468 // we need traversal (state changed)
3469 // AND transaction (list changed)
3470 flags |= eTransactionNeeded|eTraversalNeeded;
3471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 } else {
3473 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003474 flags |= eTransactionNeeded|eTraversalNeeded;
3475 }
3476 }
chaviw8b3871a2017-11-01 17:41:01 -07003477 }
3478 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003479 // NOTE: index needs to be calculated before we update the state
3480 const auto& p = layer->getParent();
3481 if (p == nullptr) {
3482 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3483 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3484 mCurrentState.layersSortedByZ.removeAt(idx);
3485 mCurrentState.layersSortedByZ.add(layer);
3486 // we need traversal (state changed)
3487 // AND transaction (list changed)
3488 flags |= eTransactionNeeded|eTraversalNeeded;
3489 }
3490 } else {
3491 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3492 flags |= eTransactionNeeded|eTraversalNeeded;
3493 }
chaviw8b3871a2017-11-01 17:41:01 -07003494 }
3495 }
3496 if (what & layer_state_t::eSizeChanged) {
3497 if (layer->setSize(s.w, s.h)) {
3498 flags |= eTraversalNeeded;
3499 }
3500 }
3501 if (what & layer_state_t::eAlphaChanged) {
3502 if (layer->setAlpha(s.alpha))
3503 flags |= eTraversalNeeded;
3504 }
3505 if (what & layer_state_t::eColorChanged) {
3506 if (layer->setColor(s.color))
3507 flags |= eTraversalNeeded;
3508 }
Peiyong Lind3788632018-09-18 16:01:31 -07003509 if (what & layer_state_t::eColorTransformChanged) {
3510 if (layer->setColorTransform(s.colorTransform)) {
3511 flags |= eTraversalNeeded;
3512 }
3513 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003514 if (what & layer_state_t::eBackgroundColorChanged) {
3515 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3516 flags |= eTraversalNeeded;
3517 }
3518 }
chaviw8b3871a2017-11-01 17:41:01 -07003519 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003520 // TODO: b/109894387
3521 //
3522 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3523 // rotation. To see the problem observe that if we have a square parent, and a child
3524 // of the same size, then we rotate the child 45 degrees around it's center, the child
3525 // must now be cropped to a non rectangular 8 sided region.
3526 //
3527 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3528 // private API, and the WindowManager only uses rotation in one case, which is on a top
3529 // level layer in which cropping is not an issue.
3530 //
3531 // However given that abuse of rotation matrices could lead to surfaces extending outside
3532 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3533 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3534 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003535 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003536 flags |= eTraversalNeeded;
3537 }
3538 if (what & layer_state_t::eTransparentRegionChanged) {
3539 if (layer->setTransparentRegionHint(s.transparentRegion))
3540 flags |= eTraversalNeeded;
3541 }
3542 if (what & layer_state_t::eFlagsChanged) {
3543 if (layer->setFlags(s.flags, s.mask))
3544 flags |= eTraversalNeeded;
3545 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003546 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003547 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003548 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003549 if (what & layer_state_t::eCornerRadiusChanged) {
3550 if (layer->setCornerRadius(s.cornerRadius))
3551 flags |= eTraversalNeeded;
3552 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003553 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3554 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3555 }
chaviw8b3871a2017-11-01 17:41:01 -07003556 if (what & layer_state_t::eLayerStackChanged) {
3557 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3558 // We only allow setting layer stacks for top level layers,
3559 // everything else inherits layer stack from its parent.
3560 if (layer->hasParent()) {
3561 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003562 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003563 } else if (idx < 0) {
3564 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003565 "that also does not appear in the top level layer list. Something"
3566 " has gone wrong.",
3567 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003568 } else if (layer->setLayerStack(s.layerStack)) {
3569 mCurrentState.layersSortedByZ.removeAt(idx);
3570 mCurrentState.layersSortedByZ.add(layer);
3571 // we need traversal (state changed)
3572 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003573 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003574 }
3575 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003576 if (what & layer_state_t::eDeferTransaction_legacy) {
3577 if (s.barrierHandle_legacy != nullptr) {
3578 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3579 } else if (s.barrierGbp_legacy != nullptr) {
3580 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003581 if (authenticateSurfaceTextureLocked(gbp)) {
3582 const auto& otherLayer =
3583 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003584 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003585 } else {
3586 ALOGE("Attempt to defer transaction to to an"
3587 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003588 }
3589 }
chaviw8b3871a2017-11-01 17:41:01 -07003590 // We don't trigger a traversal here because if no other state is
3591 // changed, we don't want this to cause any more work
3592 }
chaviw8b3871a2017-11-01 17:41:01 -07003593 if (what & layer_state_t::eReparentChildren) {
3594 if (layer->reparentChildren(s.reparentHandle)) {
3595 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003596 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 if (what & layer_state_t::eDetachChildren) {
3599 layer->detachChildren();
3600 }
3601 if (what & layer_state_t::eOverrideScalingModeChanged) {
3602 layer->setOverrideScalingMode(s.overrideScalingMode);
3603 // We don't trigger a traversal here because if no other state is
3604 // changed, we don't want this to cause any more work
3605 }
Marissa Wall61c58622018-07-18 10:12:20 -07003606 if (what & layer_state_t::eTransformChanged) {
3607 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3610 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3611 flags |= eTraversalNeeded;
3612 }
3613 if (what & layer_state_t::eCropChanged) {
3614 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3615 }
Marissa Wall861616d2018-10-22 12:52:23 -07003616 if (what & layer_state_t::eFrameChanged) {
3617 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3618 }
Marissa Wall61c58622018-07-18 10:12:20 -07003619 if (what & layer_state_t::eAcquireFenceChanged) {
3620 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3621 }
3622 if (what & layer_state_t::eDataspaceChanged) {
3623 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3624 }
3625 if (what & layer_state_t::eHdrMetadataChanged) {
3626 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3627 }
3628 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3629 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3630 }
3631 if (what & layer_state_t::eApiChanged) {
3632 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3633 }
3634 if (what & layer_state_t::eSidebandStreamChanged) {
3635 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3636 }
Robert Carr720e5062018-07-30 17:45:14 -07003637 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003638 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003639 layer->setInputInfo(s.inputInfo);
3640 flags |= eTraversalNeeded;
3641 } else {
3642 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3643 }
Robert Carr720e5062018-07-30 17:45:14 -07003644 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003645 if (what & layer_state_t::eMetadataChanged) {
3646 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3647 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003648 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3649 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3650 flags |= eTraversalNeeded;
3651 }
3652 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003653 if (what & layer_state_t::eShadowRadiusChanged) {
3654 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3655 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003656 if (what & layer_state_t::eFrameRateSelectionPriority) {
3657 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3658 flags |= eTraversalNeeded;
3659 }
3660 }
Steven Thomas3172e202020-01-06 19:25:30 -08003661 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003662 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3663 "SurfaceFlinger::setClientStateLocked") &&
3664 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3665 Layer::FrameRate::convertCompatibility(
3666 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003667 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003668 }
Steven Thomas3172e202020-01-06 19:25:30 -08003669 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003670 // This has to happen after we reparent children because when we reparent to null we remove
3671 // child layers from current state and remove its relative z. If the children are reparented in
3672 // the same transaction, then we have to make sure we reparent the children first so we do not
3673 // lose its relative z order.
3674 if (what & layer_state_t::eReparent) {
3675 bool hadParent = layer->hasParent();
3676 if (layer->reparent(s.parentHandleForChild)) {
3677 if (!hadParent) {
3678 mCurrentState.layersSortedByZ.remove(layer);
3679 }
3680 flags |= eTransactionNeeded | eTraversalNeeded;
3681 }
3682 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003683 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003684 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3685 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003686 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3687 }
3688 }
Marissa Wall78b72202019-03-15 14:58:34 -07003689 bool bufferChanged = what & layer_state_t::eBufferChanged;
3690 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3691 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003692 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003693 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003694 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3695 if (success) {
3696 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3697 success = ClientCache::getInstance()
3698 .registerErasedRecipient(s.cachedBuffer,
3699 wp<ClientCache::ErasedRecipient>(this));
3700 if (!success) {
3701 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3702 }
3703 }
Marissa Wall78b72202019-03-15 14:58:34 -07003704 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003705 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003706 } else if (bufferChanged) {
3707 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003708 }
Marissa Wall78b72202019-03-15 14:58:34 -07003709 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003710 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3711 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003712 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003713 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003714 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003715 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3716 // Do not put anything that updates layer state or modifies flags after
3717 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003718 return flags;
3719}
3720
chaviw273171b2018-12-26 11:46:30 -08003721uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3722 uint32_t flags = 0;
3723 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3724 flags |= eTraversalNeeded;
3725 }
3726
chaviwa911b102019-02-14 10:18:33 -08003727 if (inputWindowCommands.syncInputWindows) {
3728 flags |= eTraversalNeeded;
3729 }
3730
Vishnu Nairec0ab382019-02-13 15:32:56 -08003731 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003732 return flags;
3733}
3734
chaviwfe94a222019-08-21 13:52:59 -07003735status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3736 sp<IBinder>* outHandle) {
3737 if (!mirrorFromHandle) {
3738 return NAME_NOT_FOUND;
3739 }
3740
3741 sp<Layer> mirrorLayer;
3742 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003743 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003744
3745 {
3746 Mutex::Autolock _l(mStateLock);
3747 mirrorFrom = fromHandle(mirrorFromHandle);
3748 if (!mirrorFrom) {
3749 return NAME_NOT_FOUND;
3750 }
3751
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003752 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3753 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003754 if (result != NO_ERROR) {
3755 return result;
3756 }
3757
3758 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3759 }
3760
3761 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3762}
3763
Marissa Wall2d814fb2019-04-09 18:52:57 +00003764status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3765 uint32_t h, PixelFormat format, uint32_t flags,
3766 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003767 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003768 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3769 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003770 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003771 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003772 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003773 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003774 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003775
Robert Carrc0df3122019-04-11 13:18:21 -07003776 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3777 "Expected only one of parentLayer or parentHandle to be non-null. "
3778 "Programmer error?");
3779
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003780 status_t result = NO_ERROR;
3781
3782 sp<Layer> layer;
3783
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003784 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003785
Evan Roskya1f1e152019-01-24 16:17:46 -08003786 bool primaryDisplayOnly = false;
3787
3788 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3789 // TODO b/64227542
3790 if (metadata.has(METADATA_WINDOW_TYPE)) {
3791 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3792 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003793 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003794 primaryDisplayOnly = true;
3795 }
3796 }
3797
Mathias Agopian3165cc22012-08-08 19:42:09 -07003798 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003799 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003800 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3801 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003803 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003804 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003805 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003806 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003807 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003808 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003809 // check if buffer size is set for color layer.
3810 if (w > 0 || h > 0) {
3811 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3812 int(w), int(h));
3813 return BAD_VALUE;
3814 }
3815
Vishnu Nairfa247b12020-02-11 08:58:26 -08003816 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3817 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003818 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003819 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003820 // check if buffer size is set for container layer.
3821 if (w > 0 || h > 0) {
3822 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3823 int(w), int(h));
3824 return BAD_VALUE;
3825 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003826 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3827 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003828 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003829 default:
3830 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003831 break;
3832 }
3833
Dan Stoza7d89d062015-04-30 13:29:25 -07003834 if (result != NO_ERROR) {
3835 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003837
Evan Roskya1f1e152019-01-24 16:17:46 -08003838 if (primaryDisplayOnly) {
3839 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003840 }
3841
Robert Carrb89ea9d2018-12-10 13:01:14 -08003842 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003843 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3844 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003845 if (result != NO_ERROR) {
3846 return result;
3847 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003848 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003849
3850 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003851 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852}
3853
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003854std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3855 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003856
3857 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003858 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003859
Dan Stoza436ccf32018-06-21 12:10:12 -07003860 // Grab the state lock since we're accessing mCurrentState
3861 Mutex::Autolock lock(mStateLock);
3862
Cody Northropbc755282017-03-31 12:00:08 -06003863 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003864 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003865 while (matchFound) {
3866 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003867 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003868 if (layer->getName() == uniqueName) {
3869 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003870 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003871 }
3872 });
3873 }
3874
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003875 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003876 return uniqueName;
3877}
3878
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003879status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003880 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003881 LayerMetadata metadata, PixelFormat& format,
3882 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003883 sp<IGraphicBufferProducer>* gbp,
3884 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003886 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887 case PIXEL_FORMAT_TRANSPARENT:
3888 case PIXEL_FORMAT_TRANSLUCENT:
3889 format = PIXEL_FORMAT_RGBA_8888;
3890 break;
3891 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003892 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003893 break;
3894 }
3895
chaviwb4c6e582019-08-16 14:35:07 -07003896 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003897 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003898 args.textureName = getNewTexture();
3899 {
3900 // Grab the SF state lock during this since it's the only safe way to access
3901 // RenderEngine when creating a BufferLayerConsumer
3902 // TODO: Check if this lock is still needed here
3903 Mutex::Autolock lock(mStateLock);
3904 layer = getFactory().createBufferQueueLayer(args);
3905 }
3906
Marissa Wallfd668622018-05-10 10:21:13 -07003907 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003908 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003909 *handle = layer->getHandle();
3910 *gbp = layer->getProducer();
3911 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003913
Marissa Wallfd668622018-05-10 10:21:13 -07003914 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003915 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916}
3917
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003918status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003919 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003920 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003921 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003923 args.displayDevice = getDefaultDisplayDevice();
3924 args.textureName = getNewTexture();
3925 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003926 if (outTransformHint) {
3927 *outTransformHint = layer->getTransformHint();
3928 }
Marissa Wall61c58622018-07-18 10:12:20 -07003929 *handle = layer->getHandle();
3930 *outLayer = layer;
3931
3932 return NO_ERROR;
3933}
3934
Vishnu Nairfa247b12020-02-11 08:58:26 -08003935status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3936 uint32_t h, uint32_t flags, LayerMetadata metadata,
3937 sp<IBinder>* handle, sp<Layer>* outLayer) {
3938 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003939 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003940 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003941 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003942}
3943
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003944status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003945 uint32_t w, uint32_t h, uint32_t flags,
3946 LayerMetadata metadata, sp<IBinder>* handle,
3947 sp<Layer>* outLayer) {
3948 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003949 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003950 *handle = (*outLayer)->getHandle();
3951 return NO_ERROR;
3952}
3953
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003954void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003955 mLayersPendingRemoval.add(layer);
3956 mLayersRemoved = true;
3957 setTransactionFlags(eTransactionNeeded);
3958}
3959
Robert Carr695d5282018-12-18 15:27:58 -08003960void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003961{
Robert Carr2e102c92018-10-23 12:11:15 -07003962 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003963 // If a layer has a parent, we allow it to out-live it's handle
3964 // with the idea that the parent holds a reference and will eventually
3965 // be cleaned up. However no one cleans up the top-level so we do so
3966 // here.
3967 if (layer->getParent() == nullptr) {
3968 mCurrentState.layersSortedByZ.remove(layer);
3969 }
3970 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003971
3972 auto it = mLayersByLocalBinderToken.begin();
3973 while (it != mLayersByLocalBinderToken.end()) {
3974 if (it->second == layer) {
3975 it = mLayersByLocalBinderToken.erase(it);
3976 } else {
3977 it++;
3978 }
3979 }
3980
Robert Carr695d5282018-12-18 15:27:58 -08003981 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003982}
3983
Mathias Agopianb60314a2012-04-10 22:09:54 -07003984// ---------------------------------------------------------------------------
3985
Andy McFadden13a082e2012-08-24 10:16:42 -07003986void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003987 const auto display = getDefaultDisplayDeviceLocked();
3988 if (!display) return;
3989
3990 const sp<IBinder> token = display->getDisplayToken().promote();
3991 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003992
Jesse Hall01e29052013-02-19 16:13:35 -08003993 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003994 Vector<ComposerState> state;
3995 Vector<DisplayState> displays;
3996 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003997 d.what = DisplayState::eDisplayProjectionChanged |
3998 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003999 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004000 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004001 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004002 d.frame.makeInvalid();
4003 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004004 d.width = 0;
4005 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004006 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004007 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4008 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004009
Dominik Laskowskie9774092018-12-11 10:04:24 -08004010 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004011
Dominik Laskowski83b88212018-12-11 13:34:06 -08004012 const nsecs_t vsyncPeriod = getVsyncPeriod();
4013 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004014
Brian Andersond0010582017-03-07 13:20:31 -08004015 // Use phase of 0 since phase is not known.
4016 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004017 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004018 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004019}
4020
4021void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004022 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004023 postMessageAsync(
4024 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004025}
4026
Ady Abraham27c70212019-06-11 10:52:26 -07004027void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4028 if (mHWCVsyncState != enabled) {
4029 getHwComposer().setVsyncEnabled(displayId, enabled);
4030 mHWCVsyncState = enabled;
4031 }
4032}
4033
Dominik Laskowskie9774092018-12-11 10:04:24 -08004034void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004035 if (display->isVirtual()) {
4036 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004037 return;
4038 }
4039
Dominik Laskowski075d3172018-05-24 15:50:06 -07004040 const auto displayId = display->getId();
4041 LOG_ALWAYS_FATAL_IF(!displayId);
4042
Dominik Laskowski34157762018-10-31 13:07:19 -07004043 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004044
4045 int currentMode = display->getPowerMode();
4046 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004047 return;
4048 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004050 display->setPowerMode(mode);
4051
Lloyd Pique4dccc412018-01-22 17:21:36 -08004052 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004053 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004054 }
4055
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004056 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004057 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004058 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004059 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004060 mScheduler->onScreenAcquired(mAppConnectionHandle);
4061 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004062 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004063
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004064 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004065 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004066 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004067
4068 struct sched_param param = {0};
4069 param.sched_priority = 1;
4070 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4071 ALOGW("Couldn't set SCHED_FIFO on display on");
4072 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004073 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004074 // Turn off the display
4075 struct sched_param param = {0};
4076 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4077 ALOGW("Couldn't set SCHED_OTHER on display off");
4078 }
4079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004080 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004081 mScheduler->disableHardwareVsync(true);
4082 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004083 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004084
Ady Abraham27c70212019-06-11 10:52:26 -07004085 // Make sure HWVsync is disabled before turning off the display
4086 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4087
Dominik Laskowski075d3172018-05-24 15:50:06 -07004088 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004089 mVisibleRegionsDirty = true;
4090 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004091 } else if (mode == HWC_POWER_MODE_DOZE ||
4092 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004093 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004094 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004095 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004096 mScheduler->onScreenAcquired(mAppConnectionHandle);
4097 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004098 }
4099 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4100 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004101 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004102 mScheduler->disableHardwareVsync(true);
4103 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004104 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004105 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004106 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004107 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004108 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004109 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004110
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004111 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004112 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004113 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004114 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004115 }
4116
Dominik Laskowski34157762018-10-31 13:07:19 -07004117 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004118}
4119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004120void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004121 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004122 const auto display = getDisplayDevice(displayToken);
4123 if (!display) {
4124 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4125 displayToken.get());
4126 } else if (display->isVirtual()) {
4127 ALOGW("Attempt to set power mode %d for virtual display", mode);
4128 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004129 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004130 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004131 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004132}
4133
4134// ---------------------------------------------------------------------------
4135
Dominik Laskowskic2867142019-01-21 11:33:38 -08004136status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4137 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004138 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004139
Mathias Agopianbd115332013-04-18 16:41:04 -07004140 IPCThreadState* ipc = IPCThreadState::self();
4141 const int pid = ipc->getCallingPid();
4142 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004143
Mathias Agopianbd115332013-04-18 16:41:04 -07004144 if ((uid != AID_SHELL) &&
4145 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004146 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4147 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004149 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004150 // (this would indicate SF is stuck, but we want to be able to
4151 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004152 status_t err = mStateLock.timedLock(s2ns(1));
4153 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004154 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004155 StringAppendF(&result,
4156 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4157 "(no locks held)\n",
4158 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004159 }
4160
Dominik Laskowskic2867142019-01-21 11:33:38 -08004161 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004162 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004163 {"--dispsync"s,
4164 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004165 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004166 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4167 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4168 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4169 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4170 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4171 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004172 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004173 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4174 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004175
Dominik Laskowskic2867142019-01-21 11:33:38 -08004176 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004177
Dominik Laskowski46470112019-08-02 13:13:11 -07004178 const auto it = dumpers.find(flag);
4179 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004180 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004181 } else if (!asProto) {
4182 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004183 }
4184
Mathias Agopian9795c422009-08-26 16:36:26 -07004185 if (locked) {
4186 mStateLock.unlock();
4187 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004188
Dominik Laskowski46470112019-08-02 13:13:11 -07004189 if (it == dumpers.end()) {
4190 const LayersProto layersProto = dumpProtoFromMainThread();
4191 if (asProto) {
4192 result.append(layersProto.SerializeAsString());
4193 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004194 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004195 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4196 result.append(LayerProtoParser::layerTreeToString(layerTree));
4197 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004198 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004199 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004200 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004201 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004202 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004203 return NO_ERROR;
4204}
4205
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004206status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4207 if (asProto && mTracing.isEnabled()) {
4208 mTracing.writeToFileAsync();
4209 }
4210
4211 return doDump(fd, DumpArgs(), asProto);
4212}
4213
Dominik Laskowskic2867142019-01-21 11:33:38 -08004214void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004215 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004216 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004217}
4218
Dominik Laskowskic2867142019-01-21 11:33:38 -08004219void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004221
Dominik Laskowskic2867142019-01-21 11:33:38 -08004222 if (args.size() > 1) {
4223 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004224 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004225 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004226 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004227 }
Robert Carr2047fae2016-11-28 14:09:09 -08004228 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004229 } else {
4230 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231 }
4232}
4233
Dominik Laskowskic2867142019-01-21 11:33:38 -08004234void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004235 const bool clearAll = args.size() < 2;
4236 const auto name = clearAll ? String8() : String8(args[1]);
4237
Edgar Arriaga844fa672020-01-16 14:21:42 -08004238 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004239 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004240 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004241 }
Robert Carr2047fae2016-11-28 14:09:09 -08004242 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004243
Svetoslavd85084b2014-03-20 10:28:31 -07004244 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004245}
4246
Dominik Laskowskic2867142019-01-21 11:33:38 -08004247void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4248 mTimeStats->parseArgs(asProto, args, result);
4249}
4250
Jamie Gennis6547ff42013-07-16 20:12:42 -07004251// This should only be called from the main thread. Otherwise it would need
4252// the lock and should use mCurrentState rather than mDrawingState.
4253void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004254 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004255 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004256 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004257
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004258 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004259}
4260
Yiwei Zhang5434a782018-12-05 18:06:32 -08004261void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004262 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004263
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004264 if (isLayerTripleBufferingDisabled())
4265 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004266
Yiwei Zhang5434a782018-12-05 18:06:32 -08004267 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4268 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4269 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4270 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4271 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4272 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004273 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004274}
4275
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004276void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004277 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004278
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004279 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004280 result.append("\n");
4281
Ady Abraham9e16a482019-12-03 17:19:41 -08004282 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004283 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004284 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004285 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004286
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004287 HwcConfigIndexType defaultConfig;
4288 float minFps, maxFps;
4289 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004290 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004291 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004292 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004293 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004294 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4295 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004296
Ana Krulecc2870422019-01-29 19:00:58 -08004297 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004298}
4299
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4301 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004302 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4303 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004304 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004305 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004307 }
David Sodman4a36e932017-11-07 14:29:47 -08004308 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004309 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004310 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004311 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4312 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004313}
4314
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004315void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4316 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004317 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4318 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004319 for (const auto& segment : history) {
4320 if (!segment.usedThirdBuffer) {
4321 stats.twoBufferTime += segment.totalTime;
4322 }
4323 if (segment.occupancyAverage < 1.0f) {
4324 stats.doubleBufferedTime += segment.totalTime;
4325 } else if (segment.occupancyAverage < 2.0f) {
4326 stats.tripleBufferedTime += segment.totalTime;
4327 }
4328 ++stats.numSegments;
4329 stats.totalTime += segment.totalTime;
4330 }
4331}
4332
Yiwei Zhang5434a782018-12-05 18:06:32 -08004333void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4334 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004335
4336 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4337 const size_t count = currentLayers.size();
4338 for (size_t i=0 ; i<count ; i++) {
4339 currentLayers[i]->dumpFrameEvents(result);
4340 }
4341}
4342
Yiwei Zhang5434a782018-12-05 18:06:32 -08004343void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004344 result.append("Buffering stats:\n");
4345 result.append(" [Layer name] <Active time> <Two buffer> "
4346 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004347 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004348 typedef std::tuple<std::string, float, float, float> BufferTuple;
4349 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004350 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004351 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004352 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004353 if (stats.numSegments == 0) {
4354 continue;
4355 }
4356 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4357 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4358 stats.totalTime;
4359 float doubleBufferRatio = static_cast<float>(
4360 stats.doubleBufferedTime) / stats.totalTime;
4361 float tripleBufferRatio = static_cast<float>(
4362 stats.tripleBufferedTime) / stats.totalTime;
4363 sorted.insert({activeTime, {name, twoBufferRatio,
4364 doubleBufferRatio, tripleBufferRatio}});
4365 }
4366 for (const auto& sortedPair : sorted) {
4367 float activeTime = sortedPair.first;
4368 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004369 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4370 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004371 }
4372 result.append("\n");
4373}
4374
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004376 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004377 const auto displayId = display->getId();
4378 if (!displayId) {
4379 continue;
4380 }
4381 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004382 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004383 continue;
4384 }
4385
Yiwei Zhang5434a782018-12-05 18:06:32 -08004386 StringAppendF(&result,
4387 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4388 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004389 uint8_t port;
4390 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004391 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004392 result.append("no identification data\n");
4393 continue;
4394 }
4395
4396 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004397 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004398 continue;
4399 }
4400
4401 const auto edid = parseEdid(data);
4402 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004403 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004404 continue;
4405 }
4406
Yiwei Zhang5434a782018-12-05 18:06:32 -08004407 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004408 result.append(edid->displayName.data(), edid->displayName.length());
4409 result.append("\"\n");
4410 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004411}
4412
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004413void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4414 std::string& result) const {
4415 hwc2_display_t hwcDisplayId;
4416 uint8_t port;
4417 DisplayIdentificationData data;
4418
4419 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4420 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4421 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4422 }
4423}
4424
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004426 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4428 StringAppendF(&result, "DisplayColorSetting: %s\n",
4429 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004430
4431 // TODO: print out if wide-color mode is active or not
4432
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004433 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004434 const auto displayId = display->getId();
4435 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004436 continue;
4437 }
4438
Yiwei Zhang5434a782018-12-05 18:06:32 -08004439 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004441 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004443 }
4444
Lloyd Pique32cbe282018-10-19 13:09:22 -07004445 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 StringAppendF(&result, " Current color mode: %s (%d)\n",
4447 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004448 }
4449 result.append("\n");
4450}
4451
Vishnu Nair8406fd72019-07-30 11:29:31 -07004452LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004453 Mutex::Autolock _l(mStateLock);
4454 const auto device = getDefaultDisplayDeviceLocked();
chaviw1d044282017-09-27 12:19:28 -07004455 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004456 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004457 layer->writeToProto(layersProto, traceFlags, device);
chaviw08f3cb22020-01-13 13:17:21 -08004458 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004459
chaviw1d044282017-09-27 12:19:28 -07004460 return layersProto;
4461}
4462
Alec Mouri6b9e9912020-01-21 10:50:24 -08004463void SurfaceFlinger::dumpHwc(std::string& result) const {
4464 getHwComposer().dump(result);
4465}
4466
Vishnu Nair0f085c62019-08-30 08:49:12 -07004467void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4468 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4469 // it.
4470 LayerProto* rootProto = layersProto.add_layers();
4471 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4472 rootProto->set_id(offscreenRootLayerId);
4473 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004474 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004475
4476 for (Layer* offscreenLayer : mOffscreenLayers) {
4477 // Add layer as child of the fake root
4478 rootProto->add_children(offscreenLayer->sequence);
4479
4480 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004481 LayerProto* layerProto =
4482 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004483 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004484 }
4485}
4486
Vishnu Nair8406fd72019-07-30 11:29:31 -07004487LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4488 LayersProto layersProto;
4489 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4490 return layersProto;
4491}
4492
Vishnu Nair0f085c62019-08-30 08:49:12 -07004493void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4494 result.append("Offscreen Layers:\n");
4495 postMessageSync(new LambdaMessage([&]() {
4496 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004497 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004498 layer->dumpCallingUidPid(result);
4499 });
4500 }
4501 }));
4502}
4503
Dominik Laskowskic2867142019-01-21 11:33:38 -08004504void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4505 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 Colorizer colorizer(colorize);
4507
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004508 // figure out if we're stuck somewhere
4509 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004510 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004511 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4512
4513 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004514 * Dump library configuration.
4515 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004516
4517 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004518 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004519 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004520 appendSfConfigString(result);
4521 appendUiConfigString(result);
4522 appendGuiConfigString(result);
4523 result.append("\n");
4524
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004525 result.append("\nDisplay identification data:\n");
4526 dumpDisplayIdentificationData(result);
4527
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004528 result.append("\nWide-Color information:\n");
4529 dumpWideColorInfo(result);
4530
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004531 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004532 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004533 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004534 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004535 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004536
Andy McFadden41d67d72014-04-25 16:58:34 -07004537 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004538 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004539 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004540 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004541 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004542
Dan Stozab90cf072015-03-05 11:05:59 -08004543 dumpStaticScreenStats(result);
4544 result.append("\n");
4545
Alec Mouri40189b02019-03-05 15:07:54 -08004546 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4547 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4548 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004549
Dan Stozae77c7662016-05-13 11:37:28 -07004550 dumpBufferingStats(result);
4551
Andy McFadden4803b742012-09-24 19:07:20 -07004552 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004553 * Dump the visible layer list
4554 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004556 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4558 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004560
Chia-I Wu2f884132018-09-13 15:17:58 -07004561 {
Lloyd Pique207def92019-02-28 16:09:52 -08004562 StringAppendF(&result, "Composition layers\n");
4563 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004564 auto* compositionState = layer->getCompositionState();
4565 if (!compositionState) return;
4566
4567 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4568 layer->getDebugName() ? layer->getDebugName()
4569 : "<unknown>");
4570 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004571 });
4572 }
4573
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004574 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004575 * Dump Display state
4576 */
4577
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004578 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004579 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004580 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004581 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004582 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004583 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004584 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004585
4586 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004587 * Dump CompositionEngine state
4588 */
4589
4590 mCompositionEngine->dump(result);
4591
4592 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004593 * Dump SurfaceFlinger global state
4594 */
4595
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004596 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004597 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004598 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004599
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004600 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004601
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004602 DebugEGLImageTracker::getInstance()->dump(result);
4603
Dominik Laskowski075d3172018-05-24 15:50:06 -07004604 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004605 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4606 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004607 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4608 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004609 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result,
4611 " transaction-flags : %08x\n"
4612 " gpu_to_cpu_unsupported : %d\n",
4613 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004614
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004615 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004616 displayId && getHwComposer().isConnected(*displayId)) {
4617 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result,
4619 " refresh-rate : %f fps\n"
4620 " x-dpi : %f\n"
4621 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004622 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4623 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004624 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004625
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004627
Dan Stozae22aec72016-08-01 13:20:59 -07004628 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004629 * Tracing state
4630 */
4631 mTracing.dump(result);
4632 result.append("\n");
4633
4634 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004635 * HWC layer minidump
4636 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004637 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004638 const auto displayId = display->getId();
4639 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004640 continue;
4641 }
4642
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004644 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004645 const sp<DisplayDevice> displayDevice = display;
4646 mCurrentState.traverseInZOrder(
4647 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004648 result.append("\n");
4649 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004650
4651 /*
4652 * Dump HWComposer state
4653 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004654 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004655 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004656 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004657 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004659 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004660
4661 /*
4662 * Dump gralloc state
4663 */
4664 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4665 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004666
4667 /*
4668 * Dump VrFlinger state if in use.
4669 */
4670 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4671 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004673 result.append("\n");
4674 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004675
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004676 result.append(mTimeStats->miniDump());
4677 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678}
4679
Chia-I Wu28f320b2018-05-03 11:02:56 -07004680void SurfaceFlinger::updateColorMatrixLocked() {
4681 mat4 colorMatrix;
4682 if (mGlobalSaturationFactor != 1.0f) {
4683 // Rec.709 luma coefficients
4684 float3 luminance{0.213f, 0.715f, 0.072f};
4685 luminance *= 1.0f - mGlobalSaturationFactor;
4686 mat4 saturationMatrix = mat4(
4687 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4688 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4689 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4690 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4691 );
4692 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4693 } else {
4694 colorMatrix = mClientColorMatrix * mDaltonizer();
4695 }
4696
4697 if (mCurrentState.colorMatrix != colorMatrix) {
4698 mCurrentState.colorMatrix = colorMatrix;
4699 mCurrentState.colorMatrixChanged = true;
4700 setTransactionFlags(eTransactionNeeded);
4701 }
4702}
4703
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004704status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004705#pragma clang diagnostic push
4706#pragma clang diagnostic error "-Wswitch-enum"
4707 switch (static_cast<ISurfaceComposerTag>(code)) {
4708 // These methods should at minimum make sure that the client requested
4709 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004710 case BOOT_FINISHED:
4711 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004712 case CREATE_DISPLAY:
4713 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004714 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004715 case GET_ANIMATION_FRAME_STATS:
4716 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004717 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004718 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004719 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004720 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4721 case SET_AUTO_LOW_LATENCY_MODE:
4722 case GET_GAME_CONTENT_TYPE_SUPPORT:
4723 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004724 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004725 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004726 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004727 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004728 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004729 case NOTIFY_POWER_HINT:
4730 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004731 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4732 IPCThreadState* ipc = IPCThreadState::self();
4733 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4734 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004735 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736 }
Robert Carr1db73f62016-12-21 12:58:51 -08004737 return OK;
4738 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004739 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004740 IPCThreadState* ipc = IPCThreadState::self();
4741 const int pid = ipc->getCallingPid();
4742 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004743 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4744 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004745 return PERMISSION_DENIED;
4746 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004747 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004748 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004749 // Used by apps to hook Choreographer to SurfaceFlinger.
4750 case CREATE_DISPLAY_EVENT_CONNECTION:
4751 // The following calls are currently used by clients that do not
4752 // request necessary permissions. However, they do not expose any secret
4753 // information, so it is OK to pass them.
4754 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004755 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004756 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004757 case GET_PHYSICAL_DISPLAY_IDS:
4758 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004759 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004760 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004761 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004762 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004763 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 case GET_DISPLAY_STATS:
4765 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4766 // Calling setTransactionState is safe, because you need to have been
4767 // granted a reference to Client* and Handle* to do anything with it.
4768 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004769 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004770 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004771 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004772 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004773 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004774 // setFrameRate() is deliberately available for apps to call without any
4775 // special permissions.
4776 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004777 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4778 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004779 return OK;
4780 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004781 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004782 case CAPTURE_SCREEN:
4783 case ADD_REGION_SAMPLING_LISTENER:
4784 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004785 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004786 IPCThreadState* ipc = IPCThreadState::self();
4787 const int pid = ipc->getCallingPid();
4788 const int uid = ipc->getCallingUid();
4789 if ((uid != AID_GRAPHICS) &&
4790 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4791 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4792 return PERMISSION_DENIED;
4793 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004794 return OK;
4795 }
chaviw93df2ea2019-04-30 16:45:12 -07004796 case CAPTURE_SCREEN_BY_ID: {
4797 IPCThreadState* ipc = IPCThreadState::self();
4798 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004799 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004800 return OK;
4801 }
4802 return PERMISSION_DENIED;
4803 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004804 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805
4806 // These codes are used for the IBinder protocol to either interrogate the recipient
4807 // side of the transaction for its canonical interface descriptor or to dump its state.
4808 // We let them pass by default.
4809 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4810 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4811 code == IBinder::SYSPROPS_TRANSACTION) {
4812 return OK;
4813 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004814 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004816 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4818 return OK;
4819 }
4820 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4821 return PERMISSION_DENIED;
4822#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004823}
4824
Ana Krulec13be8ad2018-08-21 02:43:56 +00004825status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4826 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004827 status_t credentialCheck = CheckTransactCodeCredentials(code);
4828 if (credentialCheck != OK) {
4829 return credentialCheck;
4830 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004831
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004832 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4833 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004834 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004835 IPCThreadState* ipc = IPCThreadState::self();
4836 const int uid = ipc->getCallingUid();
4837 if (CC_UNLIKELY(uid != AID_SYSTEM
4838 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004839 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004840 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004841 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004842 return PERMISSION_DENIED;
4843 }
4844 int n;
4845 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004846 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004847 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004848 return NO_ERROR;
4849 case 1002: // SHOW_UPDATES
4850 n = data.readInt32();
4851 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004852 invalidateHwcGeometry();
4853 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004854 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004855 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004856 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004857 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004858 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004859 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004860 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004861 setTransactionFlags(
4862 eTransactionNeeded|
4863 eDisplayTransactionNeeded|
4864 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004865 return NO_ERROR;
4866 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004867 case 1006:{ // send empty update
4868 signalRefresh();
4869 return NO_ERROR;
4870 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004871 case 1008: // toggle use of hw composer
4872 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004873 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004874 invalidateHwcGeometry();
4875 repaintEverything();
4876 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004877 case 1009: // toggle use of transform hint
4878 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004879 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004880 invalidateHwcGeometry();
4881 repaintEverything();
4882 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004883 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004884 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 reply->writeInt32(0);
4886 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004887 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004888 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004889 return NO_ERROR;
4890 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004891 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004892 if (!display) {
4893 return NAME_NOT_FOUND;
4894 }
4895
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004896 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004897 return NO_ERROR;
4898 }
4899 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004900 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004901 // daltonize
4902 n = data.readInt32();
4903 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004904 case 1:
4905 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4906 break;
4907 case 2:
4908 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4909 break;
4910 case 3:
4911 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4912 break;
4913 default:
4914 mDaltonizer.setType(ColorBlindnessType::None);
4915 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004916 }
4917 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004918 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004919 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004920 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004921 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004922
4923 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004924 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004925 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004926 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004927 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004928 // apply a color matrix
4929 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004930 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004931 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004932 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004933 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004934 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004935 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004936 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004937 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004938 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004939 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004940
4941 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4942 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004943 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004944 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4945 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4946 }
4947
Chia-I Wu28f320b2018-05-03 11:02:56 -07004948 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004949 return NO_ERROR;
4950 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004951 case 1016: { // Unused.
4952 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004953 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004954 case 1017: {
4955 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004956 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004957 return NO_ERROR;
4958 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004959 case 1018: { // Modify Choreographer's phase offset
4960 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004961 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004962 return NO_ERROR;
4963 }
4964 case 1019: { // Modify SurfaceFlinger's phase offset
4965 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004966 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004967 return NO_ERROR;
4968 }
Irvel468051e2016-06-13 16:44:44 -07004969 case 1020: { // Layer updates interceptor
4970 n = data.readInt32();
4971 if (n) {
4972 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004973 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004974 }
4975 else{
4976 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004977 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004978 }
4979 return NO_ERROR;
4980 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004981 case 1021: { // Disable HWC virtual displays
4982 n = data.readInt32();
4983 mUseHwcVirtualDisplays = !n;
4984 return NO_ERROR;
4985 }
Romain Guy0147a172017-06-01 13:53:56 -07004986 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004987 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004988 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004989
Chia-I Wu28f320b2018-05-03 11:02:56 -07004990 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004991 return NO_ERROR;
4992 }
Romain Guy54f154a2017-10-24 21:40:32 +01004993 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004994 int32_t colorMode;
4995
Chia-I Wu0d711262018-05-21 15:19:35 -07004996 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004997 if (data.readInt32(&colorMode) == NO_ERROR) {
4998 mForceColorMode = static_cast<ColorMode>(colorMode);
4999 }
Romain Guy54f154a2017-10-24 21:40:32 +01005000 invalidateHwcGeometry();
5001 repaintEverything();
5002 return NO_ERROR;
5003 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005004 // Deprecate, use 1030 to check whether the device is color managed.
5005 case 1024: {
5006 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005007 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005008 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005009 n = data.readInt32();
5010 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005011 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005012 Mutex::Autolock lock(mStateLock);
5013 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005014 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005015 reply->writeInt32(NO_ERROR);
5016 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005017 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005018 bool writeFile = false;
5019 {
5020 Mutex::Autolock lock(mStateLock);
5021 mTracingEnabledChanged = true;
5022 writeFile = mTracing.disable();
5023 }
5024
5025 if (writeFile) {
5026 reply->writeInt32(mTracing.writeToFile());
5027 } else {
5028 reply->writeInt32(NO_ERROR);
5029 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005030 }
5031 return NO_ERROR;
5032 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005033 case 1026: { // Get layer tracing status
5034 reply->writeBool(mTracing.isEnabled());
5035 return NO_ERROR;
5036 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005037 // Is a DisplayColorSetting supported?
5038 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005039 const auto display = getDefaultDisplayDevice();
5040 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005041 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005042 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005043
5044 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5045 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005046 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005047 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005048 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005049 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005050 reply->writeBool(true);
5051 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005052 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005053 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005054 break;
5055 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005056 reply->writeBool(
5057 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005058 break;
5059 }
5060 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005061 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005062 // Is VrFlinger active?
5063 case 1028: {
5064 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005065 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005066 return NO_ERROR;
5067 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005068 // Set buffer size for SF tracing (value in KB)
5069 case 1029: {
5070 n = data.readInt32();
5071 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5072 ALOGW("Invalid buffer size: %d KB", n);
5073 reply->writeInt32(BAD_VALUE);
5074 return BAD_VALUE;
5075 }
5076
5077 ALOGD("Updating trace buffer to %d KB", n);
5078 mTracing.setBufferSize(n * 1024);
5079 reply->writeInt32(NO_ERROR);
5080 return NO_ERROR;
5081 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005082 // Is device color managed?
5083 case 1030: {
5084 reply->writeBool(useColorManagement);
5085 return NO_ERROR;
5086 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005087 // Override default composition data space
5088 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5089 // && adb shell stop zygote && adb shell start zygote
5090 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5091 // adb shell stop zygote && adb shell start zygote
5092 case 1031: {
5093 Mutex::Autolock _l(mStateLock);
5094 n = data.readInt32();
5095 if (n) {
5096 n = data.readInt32();
5097 if (n) {
5098 Dataspace dataspace = static_cast<Dataspace>(n);
5099 if (!validateCompositionDataspace(dataspace)) {
5100 return BAD_VALUE;
5101 }
5102 mDefaultCompositionDataspace = dataspace;
5103 }
5104 n = data.readInt32();
5105 if (n) {
5106 Dataspace dataspace = static_cast<Dataspace>(n);
5107 if (!validateCompositionDataspace(dataspace)) {
5108 return BAD_VALUE;
5109 }
5110 mWideColorGamutCompositionDataspace = dataspace;
5111 }
5112 } else {
5113 // restore composition data space.
5114 mDefaultCompositionDataspace = defaultCompositionDataspace;
5115 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5116 }
5117 return NO_ERROR;
5118 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005119 // Set trace flags
5120 case 1033: {
5121 n = data.readUint32();
5122 ALOGD("Updating trace flags to 0x%x", n);
5123 mTracing.setTraceFlags(n);
5124 reply->writeInt32(NO_ERROR);
5125 return NO_ERROR;
5126 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005127 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005128 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005129 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005130 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005131 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005132 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005133 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005134 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005135 } else {
5136 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005137 }
5138 return NO_ERROR;
5139 }
Ady Abraham34392f72019-04-10 11:29:27 -07005140 case 1035: {
5141 n = data.readInt32();
5142 mDebugDisplayConfigSetByBackdoor = false;
5143 if (n >= 0) {
5144 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005145 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005146 if (result != NO_ERROR) {
5147 return result;
5148 }
5149 mDebugDisplayConfigSetByBackdoor = true;
5150 }
5151 return NO_ERROR;
5152 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005153 }
5154 }
5155 return err;
5156}
5157
Steven Thomas6d8110b2017-08-31 18:24:21 -07005158void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005159 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005160 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005161}
5162
Ana Krulec7d1d6832018-12-27 11:10:09 -08005163void SurfaceFlinger::repaintEverythingForHWC() {
5164 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005165 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005166 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005167}
5168
Ady Abrahama09852a2020-02-20 14:23:42 -08005169void SurfaceFlinger::kernelTimerChanged(bool expired) {
5170 static bool updateOverlay =
5171 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5172 if (!updateOverlay || !mRefreshRateOverlay) return;
5173
5174 // Update the overlay on the main thread to avoid race conditions with
5175 // mRefreshRateConfigs->getCurrentRefreshRate()
5176 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5177 if (mRefreshRateOverlay) {
5178 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5179 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005180 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005181 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5182 if (mDesiredActiveConfigChanged) {
5183 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5184 mDesiredActiveConfig.configId);
5185 }
5186
5187 return mRefreshRateConfigs->getCurrentRefreshRate();
5188 }();
5189 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5190
5191 if (current != min) {
5192 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5193 mEventQueue->invalidate();
5194 }
5195 }
5196 }));
5197}
5198
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005199// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5200class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005201public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005202 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5203 ~WindowDisconnector() {
5204 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005205 }
5206
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005207private:
5208 ANativeWindow* mWindow;
5209 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005210};
5211
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005212status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005213 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005214 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5215 const Rect& sourceCrop, uint32_t reqWidth,
5216 uint32_t reqHeight, bool useIdentityTransform,
5217 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005218 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005220 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005221
Dominik Laskowski718f9602019-11-09 20:01:35 -08005222 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5223 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5224 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5225 renderAreaRotation = ui::Transform::ROT_0;
5226 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005227
Chia-I Wu20261cb2018-08-23 12:55:44 -07005228 sp<DisplayDevice> display;
5229 {
5230 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005231
Chia-I Wu20261cb2018-08-23 12:55:44 -07005232 display = getDisplayDeviceLocked(displayToken);
5233 if (!display) return BAD_VALUE;
5234
Chia-I Wucb023152018-08-28 12:57:23 -07005235 // set the requested width/height to the logical display viewport size
5236 // by default
5237 if (reqWidth == 0 || reqHeight == 0) {
5238 reqWidth = uint32_t(display->getViewport().width());
5239 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005240 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005241 }
5242
Peiyong Lin0e003c92018-09-17 11:09:51 -07005243 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005244 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005245
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005246 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5247 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005248 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005249 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005250}
5251
chaviw93df2ea2019-04-30 16:45:12 -07005252static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5253 switch (colorMode) {
5254 case ColorMode::DISPLAY_P3:
5255 case ColorMode::BT2100_PQ:
5256 case ColorMode::BT2100_HLG:
5257 case ColorMode::DISPLAY_BT2020:
5258 return Dataspace::DISPLAY_P3;
5259 default:
5260 return Dataspace::V0_SRGB;
5261 }
5262}
5263
5264const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5265 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5266 if (displayToken) {
5267 return getDisplayDeviceLocked(displayToken);
5268 }
5269 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5270 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005271 return getDisplayByLayerStack(displayOrLayerStack);
5272}
5273
5274const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005275 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005276 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005277 return display;
5278 }
5279 }
5280 return nullptr;
5281}
5282
5283status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5284 sp<GraphicBuffer>* outBuffer) {
5285 sp<DisplayDevice> display;
5286 uint32_t width;
5287 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005288 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005289 {
5290 Mutex::Autolock _l(mStateLock);
5291 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5292 if (!display) {
5293 return BAD_VALUE;
5294 }
5295
5296 width = uint32_t(display->getViewport().width());
5297 height = uint32_t(display->getViewport().height());
5298
Dominik Laskowski718f9602019-11-09 20:01:35 -08005299 const auto orientation = display->getOrientation();
5300 captureOrientation = ui::Transform::toRotationFlags(orientation);
5301
5302 switch (captureOrientation) {
5303 case ui::Transform::ROT_90:
5304 captureOrientation = ui::Transform::ROT_270;
5305 break;
5306
5307 case ui::Transform::ROT_270:
5308 captureOrientation = ui::Transform::ROT_90;
5309 break;
5310
5311 case ui::Transform::ROT_INVALID:
5312 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5313 captureOrientation = ui::Transform::ROT_0;
5314 break;
5315
5316 default:
5317 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005318 }
chaviw93df2ea2019-04-30 16:45:12 -07005319 *outDataspace =
5320 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5321 }
5322
5323 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5324 false /* captureSecureLayers */);
5325
5326 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5327 std::placeholders::_1);
5328 bool ignored = false;
5329 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5330 false /* useIdentityTransform */,
5331 ignored /* outCapturedSecureLayers */);
5332}
5333
Robert Carr866455f2019-04-02 16:28:26 -07005334status_t SurfaceFlinger::captureLayers(
5335 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5336 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5337 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5338 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005339 ATRACE_CALL();
5340
5341 class LayerRenderArea : public RenderArea {
5342 public:
Robert Carr578038f2018-03-09 12:25:24 -08005343 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005344 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005345 bool childrenOnly, const Rect& displayViewport)
5346 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005347 mLayer(layer),
5348 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005349 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005350 mFlinger(flinger),
5351 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005352 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005353 Rect getBounds() const override {
5354 const Layer::State& layerState(mLayer->getDrawingState());
5355 return mLayer->getBufferSize(layerState);
5356 }
Marissa Wall61c58622018-07-18 10:12:20 -07005357 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005358 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005359 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005360 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005361 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005362 }
chaviwa76b2712017-09-20 12:02:26 -07005363 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005364 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005365 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005366 Rect getSourceCrop() const override {
5367 if (mCrop.isEmpty()) {
5368 return getBounds();
5369 } else {
5370 return mCrop;
5371 }
5372 }
Robert Carr578038f2018-03-09 12:25:24 -08005373 class ReparentForDrawing {
5374 public:
5375 const sp<Layer>& oldParent;
5376 const sp<Layer>& newParent;
5377
Vishnu Nair4351ad52019-02-11 14:13:02 -08005378 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5379 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005380 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005381 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005382 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5383 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005384 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005385 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005386 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005387 };
5388
5389 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005390 const Rect sourceCrop = getSourceCrop();
5391 // no need to check rotation because there is none
5392 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5393 sourceCrop.height() != getReqHeight();
5394
Robert Carr578038f2018-03-09 12:25:24 -08005395 if (!mChildrenOnly) {
5396 mTransform = mLayer->getTransform().inverse();
5397 drawLayers();
5398 } else {
5399 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005400 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5401 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005402 // In the "childrenOnly" case we reparent the children to a screenshot
5403 // layer which has no properties set and which does not draw.
5404 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005405 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5406 "Screenshot Parent"s, w, h, 0,
5407 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005408
Vishnu Nair4351ad52019-02-11 14:13:02 -08005409 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005410 drawLayers();
5411 }
5412 }
chaviwa76b2712017-09-20 12:02:26 -07005413
chaviwa76b2712017-09-20 12:02:26 -07005414 private:
chaviw7206d492017-11-10 16:16:12 -08005415 const sp<Layer> mLayer;
5416 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005417
Peiyong Linefefaac2018-08-17 12:27:51 -07005418 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005419 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005420
5421 SurfaceFlinger* mFlinger;
5422 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005423 };
5424
Robert Carrc0df3122019-04-11 13:18:21 -07005425 int reqWidth = 0;
5426 int reqHeight = 0;
5427 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005428 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005429 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005430 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005431 {
5432 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005433
Robert Carrc0df3122019-04-11 13:18:21 -07005434 parent = fromHandle(layerHandleBinder);
5435 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5436 ALOGE("captureLayers called with an invalid or removed parent");
5437 return NAME_NOT_FOUND;
5438 }
5439
5440 const int uid = IPCThreadState::self()->getCallingUid();
5441 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5442 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5443 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5444 return PERMISSION_DENIED;
5445 }
5446
Vishnu Nairefc42e22019-12-03 17:36:12 -08005447 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005448 if (sourceCrop.width() <= 0) {
5449 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005450 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005451 }
5452
5453 if (sourceCrop.height() <= 0) {
5454 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005455 crop.bottom = parentSourceBounds.getHeight();
5456 }
5457
5458 if (crop.isEmpty() || frameScale <= 0.0f) {
5459 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5460 // crop was not specified, or an invalid frame scale was provided.
5461 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005462 }
5463 reqWidth = crop.width() * frameScale;
5464 reqHeight = crop.height() * frameScale;
5465
5466 for (const auto& handle : excludeHandles) {
5467 sp<Layer> excludeLayer = fromHandle(handle);
5468 if (excludeLayer != nullptr) {
5469 excludeLayers.emplace(excludeLayer);
5470 } else {
5471 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5472 return NAME_NOT_FOUND;
5473 }
5474 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005475
5476 auto display = getDisplayByLayerStack(parent->getLayerStack());
5477 if (!display) {
5478 return BAD_VALUE;
5479 }
5480
5481 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005482 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005483
Chia-I Wu20261cb2018-08-23 12:55:44 -07005484 // really small crop or frameScale
5485 if (reqWidth <= 0) {
5486 reqWidth = 1;
5487 }
5488 if (reqHeight <= 0) {
5489 reqHeight = 1;
5490 }
5491
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005492 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5493 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005494 auto traverseLayers = [parent, childrenOnly,
5495 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005496 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5497 if (!layer->isVisible()) {
5498 return;
Robert Carr578038f2018-03-09 12:25:24 -08005499 } else if (childrenOnly && layer == parent.get()) {
5500 return;
chaviwa76b2712017-09-20 12:02:26 -07005501 }
Robert Carr866455f2019-04-02 16:28:26 -07005502
5503 sp<Layer> p = layer;
5504 while (p != nullptr) {
5505 if (excludeLayers.count(p) != 0) {
5506 return;
5507 }
5508 p = p->getParent();
5509 }
5510
chaviwa76b2712017-09-20 12:02:26 -07005511 visitor(layer);
5512 });
5513 };
Robert Carr108b2c72019-04-02 16:32:58 -07005514
5515 bool outCapturedSecureLayers = false;
5516 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5517 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005518}
5519
5520status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5521 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005522 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005523 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005524 bool useIdentityTransform,
5525 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005526 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005527
Peiyong Lin0e003c92018-09-17 11:09:51 -07005528 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005529 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5530 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005531 *outBuffer =
5532 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5533 static_cast<android_pixel_format>(reqPixelFormat), 1,
5534 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005535
Robert Carr108b2c72019-04-02 16:32:58 -07005536 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5537 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005538}
5539
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005540status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5541 TraverseLayersFunction traverseLayers,
5542 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005543 bool useIdentityTransform,
5544 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005545 // This mutex protects syncFd and captureResult for communication of the return values from the
5546 // main thread back to this Binder thread
5547 std::mutex captureMutex;
5548 std::condition_variable captureCondition;
5549 std::unique_lock<std::mutex> captureLock(captureMutex);
5550 int syncFd = -1;
5551 std::optional<status_t> captureResult;
5552
Robert Carr03480e22018-01-04 16:02:06 -08005553 const int uid = IPCThreadState::self()->getCallingUid();
5554 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5555
Dominik Laskowski8c001672018-05-30 16:52:06 -07005556 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005557 // If there is a refresh pending, bug out early and tell the binder thread to try again
5558 // after the refresh.
5559 if (mRefreshPending) {
5560 ATRACE_NAME("Skipping screenshot for now");
5561 std::unique_lock<std::mutex> captureLock(captureMutex);
5562 captureResult = std::make_optional<status_t>(EAGAIN);
5563 captureCondition.notify_one();
5564 return;
5565 }
5566
5567 status_t result = NO_ERROR;
5568 int fd = -1;
5569 {
5570 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005571 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005572 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005573 useIdentityTransform, forSystem, &fd,
5574 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005575 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005576 }
5577
5578 {
5579 std::unique_lock<std::mutex> captureLock(captureMutex);
5580 syncFd = fd;
5581 captureResult = std::make_optional<status_t>(result);
5582 captureCondition.notify_one();
5583 }
5584 });
5585
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005586 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005587 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005588 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005589 while (*captureResult == EAGAIN) {
5590 captureResult.reset();
5591 result = postMessageAsync(message);
5592 if (result != NO_ERROR) {
5593 return result;
5594 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005595 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 }
5597 result = *captureResult;
5598 }
5599
5600 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601 sync_wait(syncFd, -1);
5602 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005604
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005606}
5607
chaviwa76b2712017-09-20 12:02:26 -07005608void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005609 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005610 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5611 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005612 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005613
chaviwa76b2712017-09-20 12:02:26 -07005614 const auto reqWidth = renderArea.getReqWidth();
5615 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005616 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005617 const auto transform = renderArea.getTransform();
5618 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005619 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005620
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005621 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005622 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005623
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005624 // assume that bounds are never offset, and that they are the same as the
5625 // buffer bounds.
5626 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005627 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005628 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005629
5630 // Now take into account the rotation flag. We append a transform that
5631 // rotates the layer stack about the origin, then translate by buffer
5632 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005634 int displacementX = 0;
5635 int displacementY = 0;
5636 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5637 switch (rotation) {
5638 case ui::Transform::ROT_90:
5639 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005640 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005641 break;
5642 case ui::Transform::ROT_180:
5643 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005644 displacementY = renderArea.getBounds().getWidth();
5645 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005646 break;
5647 case ui::Transform::ROT_270:
5648 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005649 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005650 break;
5651 default:
5652 break;
5653 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005654
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005655 // We need to transform the clipping window into the right spot.
5656 // First, rotate the clipping rectangle by the rotation hint to get the
5657 // right orientation
5658 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5659 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5660 const vec4 rotClipTL = rotMatrix * clipTL;
5661 const vec4 rotClipBR = rotMatrix * clipBR;
5662 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5663 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5664 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5665 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5666
5667 // Now reposition the clipping rectangle with the displacement vector
5668 // computed above.
5669 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005670 clientCompositionDisplay.clip =
5671 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5672 newClipRight + displacementX, newClipBottom + displacementY);
5673
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005674 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005675 clientCompositionDisplay.globalTransform =
5676 clipTransform * clientCompositionDisplay.globalTransform;
5677
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005678 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5679 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005680
chaviw50da5042018-04-09 13:49:37 -07005681 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005682
Vishnu Nair9b079a22020-01-21 14:36:08 -08005683 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005684 fillLayer.source.buffer.buffer = nullptr;
5685 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5686 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5687 fillLayer.alpha = half(alpha);
5688 clientCompositionLayers.push_back(fillLayer);
5689
5690 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005691 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005692 const bool supportProtectedContent = false;
5693 Region clip(renderArea.getBounds());
5694 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5695 clip,
5696 useIdentityTransform,
5697 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5698 renderArea.isSecure(),
5699 supportProtectedContent,
5700 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005701 displayViewport,
5702 clientCompositionDisplay.outputDataspace,
5703 true, /* realContentIsVisible */
5704 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005705 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005706 std::vector<compositionengine::LayerFE::LayerSettings> results =
5707 layer->prepareClientCompositionList(targetSettings);
5708 clientCompositionLayers.insert(clientCompositionLayers.end(),
5709 std::make_move_iterator(results.begin()),
5710 std::make_move_iterator(results.end()));
5711 results.clear();
5712
chaviwa76b2712017-09-20 12:02:26 -07005713 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005714
Vishnu Nair9b079a22020-01-21 14:36:08 -08005715 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5716 clientCompositionLayers.reserve(clientCompositionLayers.size());
5717 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5718 std::back_inserter(clientCompositionLayerPointers),
5719 [](compositionengine::LayerFE::LayerSettings& settings)
5720 -> renderengine::LayerSettings* { return &settings; });
5721
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005722 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005723 // Use an empty fence for the buffer fence, since we just created the buffer so
5724 // there is no need for synchronization with the GPU.
5725 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005726 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005727 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005728 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005729 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005730
5731 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005732}
5733
chaviwa76b2712017-09-20 12:02:26 -07005734status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5735 TraverseLayersFunction traverseLayers,
5736 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005737 bool useIdentityTransform, bool forSystem,
5738 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005739 ATRACE_CALL();
5740
chaviwa76b2712017-09-20 12:02:26 -07005741 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005742 outCapturedSecureLayers =
5743 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005744 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005745
Robert Carr03480e22018-01-04 16:02:06 -08005746 // We allow the system server to take screenshots of secure layers for
5747 // use in situations like the Screen-rotation animation and place
5748 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005749 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005750 ALOGW("FB is protected: PERMISSION_DENIED");
5751 return PERMISSION_DENIED;
5752 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005753 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005754 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005755}
5756
chaviw95ef3c42019-02-14 10:55:09 -08005757void SurfaceFlinger::setInputWindowsFinished() {
5758 Mutex::Autolock _l(mStateLock);
5759
5760 mPendingSyncInputWindows = false;
5761 mTransactionCV.broadcast();
5762}
chaviw5f21a5e2019-02-14 10:00:34 -08005763
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005764// ---------------------------------------------------------------------------
5765
Edgar Arriaga844fa672020-01-16 14:21:42 -08005766void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5767 layersSortedByZ.traverse(visitor);
5768}
5769
Dan Stoza412903f2017-04-27 13:42:17 -07005770void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5771 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005772}
5773
Dan Stoza412903f2017-04-27 13:42:17 -07005774void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5775 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005776}
5777
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005778void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005779 const LayerVector::Visitor& visitor) {
5780 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005781 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005782 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005783 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005784 continue;
5785 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005786 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005787 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005788 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005789 return;
5790 }
chaviwa76b2712017-09-20 12:02:26 -07005791 if (!layer->isVisible()) {
5792 return;
5793 }
5794 visitor(layer);
5795 });
5796 }
5797}
5798
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005799status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5800 HwcConfigIndexType defaultConfig,
5801 float minRefreshRate,
5802 float maxRefreshRate) {
5803 Mutex::Autolock lock(mStateLock);
5804
Dominik Laskowski22488f62019-03-28 09:53:04 -07005805 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005806 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5807 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5808 // it should go thru setDesiredActiveConfig, similar to primary display.
5809 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5810 const auto displayId = display->getId();
5811 LOG_ALWAYS_FATAL_IF(!displayId);
5812
5813 HWC2::VsyncPeriodChangeConstraints constraints;
5814 constraints.desiredTimeNanos = systemTime();
5815 constraints.seamlessRequired = false;
5816
5817 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005818 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5819 constraints, &timeline) < 0) {
5820 return BAD_VALUE;
5821 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005822 if (timeline.refreshRequired) {
5823 repaintEverythingForHWC();
5824 }
5825
Ady Abrahamdfa37362020-01-21 18:02:39 -08005826 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005827 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005828 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5829 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005830 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005831 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005832 }
5833
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005834 if (mDebugDisplayConfigSetByBackdoor) {
5835 // ignore this request as config is overridden by backdoor
5836 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005837 }
5838
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005839 bool policyChanged;
5840 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5841 &policyChanged) < 0) {
5842 return BAD_VALUE;
5843 }
5844 if (!policyChanged) {
5845 return NO_ERROR;
5846 }
5847
5848 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5849 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005850
5851 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5852 // that listeners that care about a change in allowed configs can get the notification.
5853 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005854 const nsecs_t vsyncPeriod =
5855 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005856 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005857 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005858
Ana Krulec3f6a2062020-01-23 15:48:01 -08005859 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005860 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005861 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5862 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5863 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5864 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5865 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5866
5867 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5868 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5869 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005870 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005871 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005872 }
5873
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005874 return NO_ERROR;
5875}
5876
Ana Krulec0782b882019-10-15 17:34:54 -07005877status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005878 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005879 float maxRefreshRate) {
5880 ATRACE_CALL();
5881
5882 if (!displayToken) {
5883 return BAD_VALUE;
5884 }
5885
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005886 status_t result = NO_ERROR;
5887
Ana Krulec234bb162019-11-10 22:55:55 +01005888 postMessageSync(new LambdaMessage([&]() {
5889 const auto display = getDisplayDeviceLocked(displayToken);
5890 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005891 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005892 ALOGE("Attempt to set desired display configs for invalid display token %p",
5893 displayToken.get());
5894 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005895 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005896 ALOGW("Attempt to set desired display configs for virtual display");
5897 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005898 result =
5899 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5900 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005901 }
5902 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005903
5904 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005905}
5906
5907status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005908 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005909 float* outMinRefreshRate,
5910 float* outMaxRefreshRate) {
5911 ATRACE_CALL();
5912
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005913 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005914 return BAD_VALUE;
5915 }
5916
5917 Mutex::Autolock lock(mStateLock);
5918 const auto display = getDisplayDeviceLocked(displayToken);
5919 if (!display) {
5920 return NAME_NOT_FOUND;
5921 }
5922
5923 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005924 HwcConfigIndexType defaultConfig;
5925 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5926 *outDefaultConfig = defaultConfig.value();
5927 return NO_ERROR;
5928 } else if (display->isVirtual()) {
5929 return BAD_VALUE;
5930 } else {
5931 const auto displayId = display->getId();
5932 if (!displayId) {
5933 return BAD_VALUE;
5934 }
5935 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5936 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5937 *outMinRefreshRate = 1e9f / vsyncPeriod;
5938 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5939 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005940 }
Ana Krulec0782b882019-10-15 17:34:54 -07005941}
5942
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005943void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005944 mFlinger->setInputWindowsFinished();
5945}
5946
Robert Carrc0df3122019-04-11 13:18:21 -07005947sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005948 BBinder* b = nullptr;
5949 if (handle) {
5950 b = handle->localBinder();
5951 }
Robert Carrc0df3122019-04-11 13:18:21 -07005952 if (b == nullptr) {
5953 return nullptr;
5954 }
5955 auto it = mLayersByLocalBinderToken.find(b);
5956 if (it != mLayersByLocalBinderToken.end()) {
5957 return it->second.promote();
5958 }
5959 return nullptr;
5960}
5961
Dominik Laskowski75848362019-11-11 17:57:20 -08005962void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005963 mNumLayers++;
5964 mScheduler->registerLayer(layer);
5965}
5966
5967void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5968 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005969 removeFromOffscreenLayers(layer);
5970}
5971
5972// WARNING: ONLY CALL THIS FROM LAYER DTOR
5973// Here we add children in the current state to offscreen layers and remove the
5974// layer itself from the offscreen layer list. Since
5975// this is the dtor, it is safe to access the current state. This keeps us
5976// from dangling children layers such that they are not reachable from the
5977// Drawing state nor the offscreen layer list
5978// See b/141111965
5979void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5980 for (auto& child : layer->getCurrentChildren()) {
5981 mOffscreenLayers.emplace(child.get());
5982 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005983 mOffscreenLayers.erase(layer);
5984}
5985
Alec Mouri4545a8a2019-08-08 20:05:32 -07005986void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5987 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5988}
5989
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005990status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5991 float lightPosY, float lightPosZ,
5992 float lightRadius) {
5993 Mutex::Autolock _l(mStateLock);
5994 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5995 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5996 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5997 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5998 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5999
6000 // these values are overridden when calculating the shadow settings for a layer.
6001 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6002 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006003 return NO_ERROR;
6004}
6005
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006006const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6007 const {
6008 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6009 // on the work to remove the table in that bug rather than adding more to
6010 // it.
6011 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6012 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6013 // supported, and exposed via the
6014 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6015 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6016 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6017 };
6018 return genericLayerMetadataKeyMap;
6019}
6020
Steven Thomas62a4cf82020-01-31 12:04:03 -08006021status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6022 int8_t compatibility) {
6023 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6024 return BAD_VALUE;
6025 }
6026
6027 Mutex::Autolock lock(mStateLock);
6028 if (authenticateSurfaceTextureLocked(surface)) {
6029 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6030 if (layer->setFrameRate(
6031 Layer::FrameRate(frameRate,
6032 Layer::FrameRate::convertCompatibility(compatibility)))) {
6033 setTransactionFlags(eTraversalNeeded);
6034 }
6035 } else {
6036 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6037 return BAD_VALUE;
6038 }
6039 return NO_ERROR;
6040}
6041
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006042} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006043
Mathias Agopian3f844832013-08-07 21:24:32 -07006044#if defined(__gl_h_)
6045#error "don't include gl/gl.h in this file"
6046#endif
6047
6048#if defined(__gl2_h_)
6049#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006050#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006051
6052// TODO(b/129481165): remove the #pragma below and fix conversion issues
6053#pragma clang diagnostic pop // ignored "-Wconversion"