blob: 730227855f806aab6b6d9f772ab70a5c21ac3666 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
211
212// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700213int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700214bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800215uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800216bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800217bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800218int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600219bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800220ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700221bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700222bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700223Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
225Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
226ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800227bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700228
Kalle Raitaa099a242017-01-11 11:17:29 -0800229std::string getHwcServiceName() {
230 char value[PROPERTY_VALUE_MAX] = {};
231 property_get("debug.sf.hwc_service_name", value, "default");
232 ALOGI("Using HWComposer service: '%s'", value);
233 return std::string(value);
234}
235
236bool useTrebleTestingOverride() {
237 char value[PROPERTY_VALUE_MAX] = {};
238 property_get("debug.sf.treble_testing_override", value, "false");
239 ALOGI("Treble testing override: '%s'", value);
240 return std::string(value) == "true";
241}
242
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800243std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
244 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800245 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700246 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800247 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800249 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Enhanced");
251 default:
252 return std::string("Unknown ") +
253 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255}
256
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700257SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800258
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700259SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
260 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700262 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700263 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700265 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800266 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
267 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800268
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700269SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800270 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800273
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700275
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800279
Steven Thomas050b2c82017-03-06 11:45:16 -0800280 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800284
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900285 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700286
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 mDefaultCompositionDataspace =
290 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700291 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
292 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 defaultCompositionDataspace = mDefaultCompositionDataspace;
294 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
295 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
296 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
297 wideColorGamutCompositionPixelFormat =
298 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700299
Yichi Chenda901bf2019-06-28 14:58:27 +0800300 mColorSpaceAgnosticDataspace =
301 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800304
Dominik Laskowski718f9602019-11-09 20:01:35 -0800305 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
306 switch (primary_display_orientation(Values::ORIENTATION_0)) {
307 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800308 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800309 case Values::ORIENTATION_90:
310 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800312 case Values::ORIENTATION_180:
313 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_270:
316 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
318 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800319 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800320
Sundong Ahn85131bd2019-02-18 15:51:53 +0900321 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800322
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323 // debugging stuff...
324 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700325
Mathias Agopianb4b17302013-03-20 18:36:41 -0700326 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700327 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700328
Alec Mouri5f487d42020-02-06 09:26:19 -0800329 property_get("ro.build.type", value, "user");
330 mIsUserBuild = strcmp(value, "user") == 0;
331
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332 property_get("debug.sf.showupdates", value, "0");
333 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700334
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700335 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000336
337 // DDMS debugging deprecated (b/120782499)
338 property_get("debug.sf.ddms", value, "0");
339 int debugDdms = atoi(value);
340 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700341
342 property_get("debug.sf.disable_backpressure", value, "0");
343 mPropagateBackpressure = !atoi(value);
344 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700345
Ady Abrahamadb9a992019-09-19 21:21:55 +0000346 property_get("debug.sf.enable_gl_backpressure", value, "0");
347 mPropagateBackpressureClientComposition = atoi(value);
348 ALOGI_IF(mPropagateBackpressureClientComposition,
349 "Enabling backpressure propagation for Client Composition");
350
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800351 property_get("debug.sf.enable_hwc_vds", value, "0");
352 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800353 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800354
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800355 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800356 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800357 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700358
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800359 property_get("ro.surface_flinger.supports_background_blur", value, "0");
360 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800361 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800362 bool disableBlurs = atoi(value);
363 mEnableBlurs = supportsBlurs && !disableBlurs;
364 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
365 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800366 property_get("ro.sf.blurs_are_expensive", value, "0");
367 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800372 mGraphicBufferProducerListSizeLogThreshold =
373 std::max(static_cast<int>(0.95 *
374 static_cast<double>(mMaxGraphicBufferProducerListSize)),
375 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376
Dan Stozaec460082018-12-17 15:35:09 -0800377 property_get("debug.sf.luma_sampling", value, "1");
378 mLumaSampling = atoi(value);
379
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800380 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800381 mDisableClientCompositionCache = atoi(value);
382
Romain Guy11d63f42017-07-20 12:47:14 -0700383 // We should be reading 'persist.sys.sf.color_saturation' here
384 // but since /data may be encrypted, we need to wait until after vold
385 // comes online to attempt to read the property. The property is
386 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800387
388 if (useTrebleTestingOverride()) {
389 // Without the override SurfaceFlinger cannot connect to HIDL
390 // services that are not listed in the manifests. Considered
391 // deriving the setting from the set service name, but it
392 // would be brittle if the name that's not 'default' is used
393 // for production purposes later on.
394 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
395 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800396
397 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400void SurfaceFlinger::onFirstRef()
401{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800402 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403}
404
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700405SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406
Dan Stozac7014012014-02-14 15:03:43 -0800407void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408{
409 // the window manager died on us. prepare its eulogy.
410
Andy McFadden13a082e2012-08-24 10:16:42 -0700411 // restore initial conditions (default device unblank, etc)
412 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413
414 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700415 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416}
417
Robert Carr1db73f62016-12-21 12:58:51 -0800418static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700419 status_t err = client->initCheck();
420 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800421 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422 }
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return nullptr;
424}
425
426sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
427 return initClient(new Client(this));
428}
429
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700430sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
431 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700432{
433 class DisplayToken : public BBinder {
434 sp<SurfaceFlinger> flinger;
435 virtual ~DisplayToken() {
436 // no more references, this display must be terminated
437 Mutex::Autolock _l(flinger->mStateLock);
438 flinger->mCurrentState.displays.removeItem(this);
439 flinger->setTransactionFlags(eDisplayTransactionNeeded);
440 }
441 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700442 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 : flinger(flinger) {
444 }
445 };
446
447 sp<BBinder> token = new DisplayToken(this);
448
449 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 // Display ID is assigned when virtual display is allocated by HWC.
451 DisplayDeviceState state;
452 state.isSecure = secure;
453 state.displayName = displayName;
454 mCurrentState.displays.add(token, state);
455 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456 return token;
457}
458
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 Mutex::Autolock _l(mStateLock);
461
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
463 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700464 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 return;
466 }
467
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
469 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 ALOGE("destroyDisplay called for non-virtual display");
471 return;
472 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 mInterceptor->saveDisplayDeletion(state.sequenceId);
474 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 setTransactionFlags(eDisplayTransactionNeeded);
476}
477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
479 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 const auto internalDisplayId = getInternalDisplayIdLocked();
482 if (!internalDisplayId) {
483 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 }
485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486 std::vector<PhysicalDisplayId> displayIds;
487 displayIds.reserve(mPhysicalDisplayTokens.size());
488 displayIds.push_back(internalDisplayId->value);
489
490 for (const auto& [id, token] : mPhysicalDisplayTokens) {
491 if (id != *internalDisplayId) {
492 displayIds.push_back(id.value);
493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800496 return displayIds;
497}
498
499sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
500 Mutex::Autolock lock(mStateLock);
501 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502}
503
Ady Abraham37965d42018-11-01 13:43:32 -0700504status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
505 if (!outGetColorManagement) {
506 return BAD_VALUE;
507 }
508 *outGetColorManagement = useColorManagement;
509 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700510}
511
Lloyd Pique441d5042018-10-18 16:49:51 -0700512HWComposer& SurfaceFlinger::getHwComposer() const {
513 return mCompositionEngine->getHwComposer();
514}
515
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700516renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
517 return mCompositionEngine->getRenderEngine();
518}
519
Lloyd Pique70d91362018-10-18 16:02:55 -0700520compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
521 return *mCompositionEngine.get();
522}
523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524void SurfaceFlinger::bootFinished()
525{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700526 if (mStartPropertySetThread->join() != NO_ERROR) {
527 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800528 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800529 const nsecs_t now = systemTime();
530 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000531 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700532
Mikael Pessa90092f42019-08-26 17:22:04 -0700533 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000534 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700535
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 // wait patiently for the window manager death
537 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700538 mWindowManager = defaultServiceManager()->getService(name);
539 if (mWindowManager != 0) {
540 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
Robert Carr720e5062018-07-30 17:45:14 -0700542 sp<IBinder> input(defaultServiceManager()->getService(
543 String16("inputflinger")));
544 if (input == nullptr) {
545 ALOGE("Failed to link to input service");
546 } else {
547 mInputFlinger = interface_cast<IInputFlinger>(input);
548 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
Steven Thomas050b2c82017-03-06 11:45:16 -0800550 if (mVrFlinger) {
551 mVrFlinger->OnBootFinished();
552 }
553
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700555 // formerly we would just kill the process, but we now ask it to exit so it
556 // can choose where to stop the animation.
557 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700558
559 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
560 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
561 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700562
Ana Krulecbd6654b2019-02-15 15:18:15 -0800563 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 readPersistentProperties();
565 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800566
Ady Abraham8a82ba62020-01-17 12:43:17 -0800567 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
568 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
569 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
570 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800571 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800572}
573
Dan Stoza436ccf32018-06-21 12:10:12 -0700574uint32_t SurfaceFlinger::getNewTexture() {
575 {
576 std::lock_guard lock(mTexturePoolMutex);
577 if (!mTexturePool.empty()) {
578 uint32_t name = mTexturePool.back();
579 mTexturePool.pop_back();
580 ATRACE_INT("TexturePoolSize", mTexturePool.size());
581 return name;
582 }
583
584 // The pool was too small, so increase it for the future
585 ++mTexturePoolSize;
586 }
587
588 // The pool was empty, so we need to get a new texture name directly using a
589 // blocking call to the main thread
590 uint32_t name = 0;
591 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
592 return name;
593}
594
Mathias Agopian3f844832013-08-07 21:24:32 -0700595void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700596 std::lock_guard lock(mTexturePoolMutex);
597 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
598 // to actually delete this or not based on mTexturePoolSize
599 mTexturePool.push_back(texture);
600 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700601}
602
Wei Wangf9b05ee2017-07-19 20:59:39 -0700603// Do not call property_set on main thread which will be blocked by init
604// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700606 ALOGI( "SurfaceFlinger's main thread ready to run. "
607 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700611 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800612 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700613 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
614 renderengine::RenderEngineCreationArgs::Builder()
615 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
616 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
617 .setUseColorManagerment(useColorManagement)
618 .setEnableProtectedContext(enable_protected_contents(false))
619 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800620 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700621 .setContextPriority(useContextPriority
622 ? renderengine::RenderEngine::ContextPriority::HIGH
623 : renderengine::RenderEngine::ContextPriority::MEDIUM)
624 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800625 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700626
627 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
628 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700629 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800630 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800631 // Process any initial hotplug and resulting display changes.
632 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700633 const auto display = getDefaultDisplayDeviceLocked();
634 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700635 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700636 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800637
Steven Thomas050b2c82017-03-06 11:45:16 -0800638 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700640 // This callback is called from the vr flinger dispatch thread. We
641 // need to call signalTransaction(), which requires holding
642 // mStateLock when we're not on the main thread. Acquiring
643 // mStateLock from the vr flinger dispatch thread might trigger a
644 // deadlock in surface flinger (see b/66916578), so post a message
645 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700646 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700647 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
648 mVrFlingerRequestsDisplay = requestDisplay;
649 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700650 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800651 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700652 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
653 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700654 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 .value_or(0),
656 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 if (!mVrFlinger) {
658 ALOGE("Failed to start vrflinger");
659 }
660 }
661
Mathias Agopian92a979a2012-08-02 18:32:23 -0700662 // initialize our drawing state
663 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700664
Andy McFadden13a082e2012-08-24 10:16:42 -0700665 // set initial conditions (e.g. unblank default device)
666 initializeDisplays();
667
Steven Thomas137d4bc2019-07-25 16:55:14 -0700668 char primeShaderCache[PROPERTY_VALUE_MAX];
669 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
670 if (atoi(primeShaderCache)) {
671 getRenderEngine().primeCache();
672 }
Dan Stoza4e637772016-07-28 13:31:51 -0700673
Wei Wangf9b05ee2017-07-19 20:59:39 -0700674 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700675
676 const bool presentFenceReliable =
677 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
678 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679
680 if (mStartPropertySetThread->Start() != NO_ERROR) {
681 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800682 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800683
Dan Stoza9e56aa02015-11-02 13:00:03 -0800684 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700685}
686
Romain Guy11d63f42017-07-20 12:47:14 -0700687void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700688 Mutex::Autolock _l(mStateLock);
689
Romain Guy11d63f42017-07-20 12:47:14 -0700690 char value[PROPERTY_VALUE_MAX];
691
692 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800693 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700694 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800695 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100696
697 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700698 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800699
700 property_get("persist.sys.sf.color_mode", value, "0");
701 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700702}
703
Mathias Agopiana67e4182012-06-19 17:26:12 -0700704void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800705 // Start boot animation service by setting a property mailbox
706 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700707 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800708 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 if (mStartPropertySetThread->join() != NO_ERROR) {
710 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800711 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700712}
713
Mathias Agopian875d8e12013-06-07 15:35:48 -0700714size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700715 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700716}
717
Mathias Agopian875d8e12013-06-07 15:35:48 -0700718size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700719 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700720}
721
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800722// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800723
Jamie Gennis582270d2011-08-17 18:19:00 -0700724bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800725 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800726 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800727 return authenticateSurfaceTextureLocked(bufferProducer);
728}
729
730bool SurfaceFlinger::authenticateSurfaceTextureLocked(
731 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800732 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800733 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800734}
735
Brian Anderson6b376712017-04-04 10:51:39 -0700736status_t SurfaceFlinger::getSupportedFrameTimestamps(
737 std::vector<FrameEvent>* outSupported) const {
738 *outSupported = {
739 FrameEvent::REQUESTED_PRESENT,
740 FrameEvent::ACQUIRE,
741 FrameEvent::LATCH,
742 FrameEvent::FIRST_REFRESH_START,
743 FrameEvent::LAST_REFRESH_START,
744 FrameEvent::GPU_COMPOSITION_DONE,
745 FrameEvent::DEQUEUE_READY,
746 FrameEvent::RELEASE,
747 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700748 ConditionalLock _l(mStateLock,
749 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700750 if (!getHwComposer().hasCapability(
751 HWC2::Capability::PresentFenceIsNotReliable)) {
752 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
753 }
754 return NO_ERROR;
755}
756
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800757status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
758 if (!displayToken || !state) {
759 return BAD_VALUE;
760 }
761
762 Mutex::Autolock lock(mStateLock);
763
764 const auto display = getDisplayDeviceLocked(displayToken);
765 if (!display) {
766 return NAME_NOT_FOUND;
767 }
768
769 state->layerStack = display->getLayerStack();
770 state->orientation = display->getOrientation();
771
772 const Rect viewport = display->getViewport();
773 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
774
775 return NO_ERROR;
776}
777
778status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
779 if (!displayToken || !info) {
780 return BAD_VALUE;
781 }
782
783 Mutex::Autolock lock(mStateLock);
784
785 const auto display = getDisplayDeviceLocked(displayToken);
786 if (!display) {
787 return NAME_NOT_FOUND;
788 }
789
Dominik Laskowski55c85402020-01-21 16:25:47 -0800790 if (const auto connectionType = display->getConnectionType())
791 info->connectionType = *connectionType;
792 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800793 return INVALID_OPERATION;
794 }
795
796 if (mEmulatedDisplayDensity) {
797 info->density = mEmulatedDisplayDensity;
798 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800799 info->density = info->connectionType == DisplayConnectionType::Internal
800 ? mInternalDisplayDensity
801 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800802 }
803
804 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200805 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800806
807 return NO_ERROR;
808}
809
Dominik Laskowski22488f62019-03-28 09:53:04 -0700810status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800811 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700812 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 return BAD_VALUE;
814 }
815
Dominik Laskowski22488f62019-03-28 09:53:04 -0700816 Mutex::Autolock lock(mStateLock);
817
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800818 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700819 if (!displayId) {
820 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700821 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700824
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dominik Laskowski075d3172018-05-24 15:50:06 -0700827 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800828 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 auto width = hwConfig->getWidth();
831 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700832
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800833 auto xDpi = hwConfig->getDpiX();
834 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700835
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836 if (isInternal &&
837 (internalDisplayOrientation == ui::ROTATION_90 ||
838 internalDisplayOrientation == ui::ROTATION_270)) {
839 std::swap(width, height);
840 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 }
842
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800843 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800844
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800845 if (mEmulatedDisplayDensity) {
846 config.xDpi = mEmulatedDisplayDensity;
847 config.yDpi = mEmulatedDisplayDensity;
848 } else {
849 config.xDpi = xDpi;
850 config.yDpi = yDpi;
851 }
852
853 const nsecs_t period = hwConfig->getVsyncPeriod();
854 config.refreshRate = 1e9f / period;
855
856 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
857 config.appVsyncOffset = offsets.late.app;
858 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859
Andy McFadden91b2ca82014-06-13 14:04:23 -0700860 // This is how far in advance a buffer must be queued for
861 // presentation at a given time. If you want a buffer to appear
862 // on the screen at time N, you must submit the buffer before
863 // (N - presentationDeadline).
864 //
865 // Normally it's one full refresh period (to give SF a chance to
866 // latch the buffer), but this can be reduced by configuring a
867 // DispSync offset. Any additional delays introduced by the hardware
868 // composer or panel must be accounted for here.
869 //
870 // We add an additional 1ms to allow for processing time and
871 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700873
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800874 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700875 }
876
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 return NO_ERROR;
878}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700879
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700880status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
881 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700882 return BAD_VALUE;
883 }
884
Ana Krulecc2870422019-01-29 19:00:58 -0800885 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700886 return NO_ERROR;
887}
888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
890 const auto display = getDisplayDevice(displayToken);
891 if (!display) {
892 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800893 return BAD_VALUE;
894 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700895
Steven Thomasc9098452019-09-30 17:15:05 -0700896 if (display->isPrimary()) {
897 std::lock_guard<std::mutex> lock(mActiveConfigLock);
898 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800899 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700900 }
Steven Thomasc9098452019-09-30 17:15:05 -0700901 }
Ady Abraham2139f732019-11-13 18:56:40 -0800902
903 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700904}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700905
Ady Abraham03b02dd2019-03-21 15:40:11 -0700906void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800907 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800908 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
909 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800910
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800911 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800912 // config twice. However event generation config might have changed so we need to update it
913 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800914 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700915 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
916 mDesiredActiveConfig = info;
917 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800918
919 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800920 // This will trigger HWC refresh without resetting the idle timer.
921 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700922 // Start receiving vsync samples now, so that we can detect a period
923 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800924 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700925 // As we called to set period, we will call to onRefreshRateChangeCompleted once
926 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700927 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800928
Ady Abraham9e16a482019-12-03 17:19:41 -0800929 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
930 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800932 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700933
934 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800935 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700936 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937}
938
939status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
940 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800941
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100942 if (!displayToken) {
943 return BAD_VALUE;
944 }
Ady Abraham838de062019-02-04 10:24:03 -0800945
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100946 status_t result = NO_ERROR;
947
948 postMessageSync(new LambdaMessage([&]() {
949 const auto display = getDisplayDeviceLocked(displayToken);
950 if (!display) {
951 ALOGE("Attempt to set allowed display configs for invalid display token %p",
952 displayToken.get());
953 result = BAD_VALUE;
954 } else if (display->isVirtual()) {
955 ALOGW("Attempt to set allowed display configs for virtual display");
956 result = BAD_VALUE;
957 } else {
958 HwcConfigIndexType config(mode);
959 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
960 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
961 refreshRate.fps);
962 }
963 }));
964
965 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966}
967
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800968void SurfaceFlinger::setActiveConfigInternal() {
969 ATRACE_CALL();
970
Dominik Laskowski22488f62019-03-28 09:53:04 -0700971 const auto display = getDefaultDisplayDeviceLocked();
972 if (!display) {
973 return;
974 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975
Dominik Laskowski22488f62019-03-28 09:53:04 -0700976 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800977 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700978 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 display->setActiveConfig(mUpcomingActiveConfig.configId);
980
Ady Abraham2139f732019-11-13 18:56:40 -0800981 auto refreshRate =
982 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800983 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
984 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800985 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700986
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800987 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700988 const nsecs_t vsyncPeriod =
989 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
990 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800991 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700992 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800993 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994}
995
Ady Abraham53852a52019-05-28 18:07:44 -0700996void SurfaceFlinger::desiredActiveConfigChangeDone() {
997 std::lock_guard<std::mutex> lock(mActiveConfigLock);
998 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
999 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001000
Kevin DuBois5988f482020-01-17 09:03:32 -08001001 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001002 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001003 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001004 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1005 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001006}
1007
Dominik Laskowski22488f62019-03-28 09:53:04 -07001008bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001009 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001010 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001012 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001014 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001015 return true;
1016 }
1017
1018 // We received the present fence from the HWC, so we assume it successfully updated
1019 // the config, hence we update SF.
1020 mCheckPendingFence = false;
1021 setActiveConfigInternal();
1022 }
1023
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024 // Store the local variable to release the lock.
1025 ActiveConfigInfo desiredActiveConfig;
1026 {
1027 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (!mDesiredActiveConfigChanged) {
1029 return false;
1030 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 desiredActiveConfig = mDesiredActiveConfig;
1032 }
1033
Ady Abraham2139f732019-11-13 18:56:40 -08001034 auto refreshRate =
1035 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1036 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1037 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001038 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1040 // display is not valid or we are already in the requested mode
1041 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001042 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001044 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045
Ady Abraham838de062019-02-04 10:24:03 -08001046 // Desired active config was set, it is different than the config currently in use, however
1047 // allowed configs might have change by the time we process the refresh.
1048 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001049 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001050 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001051 return false;
1052 }
Alec Mouri7f015182019-07-11 13:56:22 -07001053
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 mUpcomingActiveConfig = desiredActiveConfig;
1055 const auto displayId = display->getId();
1056 LOG_ALWAYS_FATAL_IF(!displayId);
1057
Ady Abraham2139f732019-11-13 18:56:40 -08001058 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001059
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001060 // TODO(b/142753666) use constrains
1061 HWC2::VsyncPeriodChangeConstraints constraints;
1062 constraints.desiredTimeNanos = systemTime();
1063 constraints.seamlessRequired = false;
1064
1065 HWC2::VsyncPeriodChangeTimeline outTimeline;
1066 auto status =
1067 getHwComposer().setActiveConfigWithConstraints(*displayId,
1068 mUpcomingActiveConfig.configId.value(),
1069 constraints, &outTimeline);
1070 if (status != NO_ERROR) {
1071 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1072 return false;
1073 }
1074
1075 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1076 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001078 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001079}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1082 Vector<ColorMode>* outColorModes) {
1083 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001084 return BAD_VALUE;
1085 }
1086
Peiyong Lina52f0292018-03-14 17:26:31 -07001087 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001088 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001089 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001090 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1091
1092 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1093 if (!displayId) {
1094 return NAME_NOT_FOUND;
1095 }
1096
Dominik Laskowski075d3172018-05-24 15:50:06 -07001097 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001098 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001099 }
Michael Wright28f24d02016-07-12 13:30:53 -07001100 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001101
1102 // If it's built-in display and the configuration claims it's not wide color capable,
1103 // filter out all wide color modes. The typical reason why this happens is that the
1104 // hardware is not good enough to support GPU composition of wide color, and thus the
1105 // OEMs choose to disable this capability.
1106 if (isInternalDisplay && !hasWideColorDisplay) {
1107 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1108 isWideColorMode);
1109 } else {
1110 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1111 }
Michael Wright28f24d02016-07-12 13:30:53 -07001112
1113 return NO_ERROR;
1114}
1115
Daniel Solomon42d04562019-01-20 21:03:19 -08001116status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1117 ui::DisplayPrimaries &primaries) {
1118 if (!displayToken) {
1119 return BAD_VALUE;
1120 }
1121
1122 // Currently we only support this API for a single internal display.
1123 if (getInternalDisplayToken() != displayToken) {
1124 return BAD_VALUE;
1125 }
1126
1127 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1128 return NO_ERROR;
1129}
1130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1132 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001133 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001134 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001135 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001136}
1137
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001138status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001139 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001140 Vector<ColorMode> modes;
1141 getDisplayColorModes(displayToken, &modes);
1142 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1143 if (mode < ColorMode::NATIVE || !exists) {
1144 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1145 decodeColorMode(mode).c_str(), mode, displayToken.get());
1146 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001147 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001148 const auto display = getDisplayDevice(displayToken);
1149 if (!display) {
1150 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1151 decodeColorMode(mode).c_str(), mode, displayToken.get());
1152 } else if (display->isVirtual()) {
1153 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1154 decodeColorMode(mode).c_str(), mode);
1155 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001156 display->getCompositionDisplay()->setColorProfile(
1157 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1158 RenderIntent::COLORIMETRIC,
1159 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160 }
1161 }));
1162
Michael Wright28f24d02016-07-12 13:30:53 -07001163 return NO_ERROR;
1164}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001165
Galia Peycheva5492cb52019-10-30 14:13:16 +01001166status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1167 bool* outSupport) const {
1168 Mutex::Autolock _l(mStateLock);
1169
1170 if (!displayToken) {
1171 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1172 return BAD_VALUE;
1173 }
1174 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1175 if (!displayId) {
1176 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1177 displayToken.get());
1178 return NAME_NOT_FOUND;
1179 }
1180 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1181 HWC2::DisplayCapability::AutoLowLatencyMode);
1182 return NO_ERROR;
1183}
1184
1185void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1186 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1187}
1188
1189void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1190 if (!displayToken) {
1191 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1192 return;
1193 }
1194 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1195 if (!displayId) {
1196 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1197 displayToken.get());
1198 return;
1199 }
1200
1201 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1202}
1203
1204status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1205 bool* outSupport) const {
1206 Mutex::Autolock _l(mStateLock);
1207
1208 if (!displayToken) {
1209 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1210 return BAD_VALUE;
1211 }
1212 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1213 if (!displayId) {
1214 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1215 displayToken.get());
1216 return NAME_NOT_FOUND;
1217 }
1218
1219 std::vector<HWC2::ContentType> outSupportedContentTypes;
1220 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1221 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1222 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1223 return NO_ERROR;
1224}
1225
1226void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1227 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1228}
1229
1230void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1231 if (!displayToken) {
1232 ALOGE("setGameContentType() failed. Missing display token.");
1233 return;
1234 }
1235 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1236 if (!displayId) {
1237 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1238 displayToken.get());
1239 return;
1240 }
1241
1242 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1243 getHwComposer().setContentType(*displayId, type);
1244}
1245
Svetoslavd85084b2014-03-20 10:28:31 -07001246status_t SurfaceFlinger::clearAnimationFrameStats() {
1247 Mutex::Autolock _l(mStateLock);
1248 mAnimFrameTracker.clearStats();
1249 return NO_ERROR;
1250}
1251
1252status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1253 Mutex::Autolock _l(mStateLock);
1254 mAnimFrameTracker.getStats(outStats);
1255 return NO_ERROR;
1256}
1257
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001258status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1259 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001260 Mutex::Autolock _l(mStateLock);
1261
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001262 const auto display = getDisplayDeviceLocked(displayToken);
1263 if (!display) {
1264 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001265 return BAD_VALUE;
1266 }
1267
Peiyong Linfb069302018-04-25 14:34:31 -07001268 // At this point the DisplayDeivce should already be set up,
1269 // meaning the luminance information is already queried from
1270 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001271 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001272 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1273 capabilities.getDesiredMaxLuminance(),
1274 capabilities.getDesiredMaxAverageLuminance(),
1275 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001276
1277 return NO_ERROR;
1278}
1279
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001280std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1281 const DisplayDevice& display) const {
1282 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1283 // avoid repetitive HAL IPC and EDID parsing.
1284 const auto displayId = display.getId();
1285 LOG_FATAL_IF(!displayId);
1286
1287 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1288 LOG_FATAL_IF(!hwcDisplayId);
1289
1290 uint8_t port;
1291 DisplayIdentificationData data;
1292 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1293 ALOGV("%s: No identification data.", __FUNCTION__);
1294 return {};
1295 }
1296
1297 const auto info = parseDisplayIdentificationData(port, data);
1298 if (!info) {
1299 return {};
1300 }
1301 return info->deviceProductInfo;
1302}
1303
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001304status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1305 ui::PixelFormat* outFormat,
1306 ui::Dataspace* outDataspace,
1307 uint8_t* outComponentMask) const {
1308 if (!outFormat || !outDataspace || !outComponentMask) {
1309 return BAD_VALUE;
1310 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001311 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001312 if (!display || !display->getId()) {
1313 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1314 return BAD_VALUE;
1315 }
1316 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1317 outDataspace, outComponentMask);
1318}
1319
Kevin DuBois74e53772018-11-19 10:52:38 -08001320status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1321 bool enable, uint8_t componentMask,
1322 uint64_t maxFrames) const {
1323 const auto display = getDisplayDevice(displayToken);
1324 if (!display || !display->getId()) {
1325 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1326 return BAD_VALUE;
1327 }
1328
1329 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1330 componentMask, maxFrames);
1331}
1332
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001333status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1334 uint64_t maxFrames, uint64_t timestamp,
1335 DisplayedFrameStats* outStats) const {
1336 const auto display = getDisplayDevice(displayToken);
1337 if (!display || !display->getId()) {
1338 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1339 return BAD_VALUE;
1340 }
1341
1342 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1343 outStats);
1344}
1345
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001346status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1347 if (!outSupported) {
1348 return BAD_VALUE;
1349 }
1350 *outSupported = getRenderEngine().supportsProtectedContent();
1351 return NO_ERROR;
1352}
1353
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001354status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1355 bool* outIsWideColorDisplay) const {
1356 if (!displayToken || !outIsWideColorDisplay) {
1357 return BAD_VALUE;
1358 }
1359 Mutex::Autolock _l(mStateLock);
1360 const auto display = getDisplayDeviceLocked(displayToken);
1361 if (!display) {
1362 return BAD_VALUE;
1363 }
Peiyong Linff84a152019-05-17 18:36:19 -07001364
1365 // Use hasWideColorDisplay to override built-in display.
1366 const auto displayId = display->getId();
1367 if (displayId && displayId == getInternalDisplayIdLocked()) {
1368 *outIsWideColorDisplay = hasWideColorDisplay;
1369 return NO_ERROR;
1370 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001371 *outIsWideColorDisplay = display->hasWideColorGamut();
1372 return NO_ERROR;
1373}
1374
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001375status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001376 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001377 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001378
Dominik Laskowski6505f792019-09-18 11:10:05 -07001379 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1380 mEventQueue->setEventConnection(
1381 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001382 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001383 }));
1384
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001385 return NO_ERROR;
1386}
1387
1388status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001389 Mutex::Autolock lock(mStateLock);
1390 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001391}
1392
Lloyd Pique755e3192018-01-31 16:46:15 -08001393status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1394 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001395 // Try to acquire a lock for 1s, fail gracefully
1396 const status_t err = mStateLock.timedLock(s2ns(1));
1397 const bool locked = (err == NO_ERROR);
1398 if (!locked) {
1399 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1400 return TIMED_OUT;
1401 }
1402
1403 outLayers->clear();
1404 mCurrentState.traverseInZOrder([&](Layer* layer) {
1405 outLayers->push_back(layer->getLayerDebugInfo());
1406 });
1407
1408 mStateLock.unlock();
1409 return NO_ERROR;
1410}
1411
Peiyong Linc6780972018-10-28 15:24:08 -07001412status_t SurfaceFlinger::getCompositionPreference(
1413 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1414 Dataspace* outWideColorGamutDataspace,
1415 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001416 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001417 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001418 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001419 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001420 return NO_ERROR;
1421}
1422
Dan Stozaec460082018-12-17 15:35:09 -08001423status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1424 const sp<IBinder>& stopLayerHandle,
1425 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001426 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001427 return BAD_VALUE;
1428 }
1429 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001430 return NO_ERROR;
1431}
1432
Dan Stozaec460082018-12-17 15:35:09 -08001433status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001434 if (!listener) {
1435 return BAD_VALUE;
1436 }
Dan Stozaec460082018-12-17 15:35:09 -08001437 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001438 return NO_ERROR;
1439}
Dan Gittik57e63c52019-01-18 16:37:54 +00001440
1441status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1442 bool* outSupport) const {
1443 if (!displayToken || !outSupport) {
1444 return BAD_VALUE;
1445 }
1446 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1447 if (!displayId) {
1448 return NAME_NOT_FOUND;
1449 }
1450 *outSupport =
1451 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1452 return NO_ERROR;
1453}
1454
1455status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1456 float brightness) const {
1457 if (!displayToken) {
1458 return BAD_VALUE;
1459 }
1460 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1461 if (!displayId) {
1462 return NAME_NOT_FOUND;
1463 }
1464 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1465}
1466
Ady Abraham8532d012019-05-08 14:50:56 -07001467status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1468 PowerHint powerHint = static_cast<PowerHint>(hintId);
1469
1470 if (powerHint == PowerHint::INTERACTION) {
1471 mScheduler->notifyTouchEvent();
1472 }
1473
1474 return NO_ERROR;
1475}
1476
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001477// ----------------------------------------------------------------------------
1478
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001479sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001480 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001481 const auto& handle =
1482 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001483
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001484 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001485}
1486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001487// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001488
1489void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001490 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001491}
1492
1493void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001494 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001495 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001496 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001497}
1498
1499void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001500 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001501 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001502 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001503}
1504
1505void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001506 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001507 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001508}
1509
1510status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001511 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001512 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513}
1514
1515status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001516 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001517 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001518 if (res == NO_ERROR) {
1519 msg->wait();
1520 }
1521 return res;
1522}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001523
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001524void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001525 do {
1526 waitForEvent();
1527 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001528}
1529
Dominik Laskowski83b88212018-12-11 13:34:06 -08001530nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001531 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001532 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1533 return 0;
1534 }
1535
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001536 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001537}
1538
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001539void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001540 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001541 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001542 ATRACE_NAME("SF onVsync");
1543
Steven Thomas3cfac282017-02-06 12:29:30 -08001544 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001546 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 return;
1548 }
1549
Dominik Laskowski075d3172018-05-24 15:50:06 -07001550 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001551 return;
1552 }
1553
Dominik Laskowski075d3172018-05-24 15:50:06 -07001554 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001555 // For now, we don't do anything with external display vsyncs.
1556 return;
1557 }
1558
Alec Mourif8e689c2019-05-20 18:32:22 -07001559 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001560 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001561 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001562 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001563 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001564}
1565
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001566void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001567 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1568 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001569}
1570
Ady Abraham2139f732019-11-13 18:56:40 -08001571bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001572 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001573}
1574
Ady Abraham2139f732019-11-13 18:56:40 -08001575void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1576 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001577 const auto display = getDefaultDisplayDeviceLocked();
1578 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001579 return;
1580 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001581 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001582
Ana Krulec7d1d6832018-12-27 11:10:09 -08001583 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001584 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1585 ALOGV("Skipping config %d as it is not part of allowed configs",
1586 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001587 return;
1588 }
1589
Ady Abraham2139f732019-11-13 18:56:40 -08001590 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001591}
1592
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001593void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001594 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001595 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001596 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001597
Lloyd Piqueba04e622017-12-14 17:11:26 -08001598 // Ignore events that do not have the right sequenceId.
1599 if (sequenceId != getBE().mComposerSequenceId) {
1600 return;
1601 }
1602
Steven Thomasb02664d2017-07-26 18:48:28 -07001603 // Only lock if we're not on the main thread. This function is normally
1604 // called on a hwbinder thread, but for the primary display it's called on
1605 // the main thread with the state lock already held, so don't attempt to
1606 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001607 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001608
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001609 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001610
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001611 if (std::this_thread::get_id() == mMainThreadId) {
1612 // Process all pending hot plug events immediately if we are on the main thread.
1613 processDisplayHotplugEventsLocked();
1614 }
1615
Lloyd Piqueba04e622017-12-14 17:11:26 -08001616 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001617}
1618
Ady Abraham7159f572019-10-11 11:10:18 -07001619void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001620 int32_t sequenceId, hwc2_display_t /*display*/,
1621 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1622 Mutex::Autolock lock(mStateLock);
1623 if (sequenceId != getBE().mComposerSequenceId) {
1624 return;
1625 }
1626 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001627}
1628
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001629void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1630 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1631 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1632}
1633
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001634void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001635 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001636 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001637 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001638 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001639 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001640}
1641
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001642void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001643 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001644
1645 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1646 // display power state.
1647 postMessageAsync(new LambdaMessage(
1648 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1649}
1650
1651void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1652 ATRACE_CALL();
1653
Ady Abraham27c70212019-06-11 10:52:26 -07001654 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1655
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001656 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001657 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1658 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001659 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001660 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001661 }
Mathias Agopian86303202012-07-24 22:46:10 -07001662}
1663
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001665void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001666 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001667 // Clear the drawing state so that the logic inside of
1668 // handleTransactionLocked will fire. It will determine the delta between
1669 // mCurrentState and mDrawingState and re-apply all changes when we make the
1670 // transition.
1671 mDrawingState.displays.clear();
1672 mDisplays.clear();
1673}
1674
Steven Thomas050b2c82017-03-06 11:45:16 -08001675void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001676 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001677 if (!mVrFlinger)
1678 return;
1679 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001680 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001681 return;
1682 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001683
Lloyd Pique441d5042018-10-18 16:49:51 -07001684 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001685 ALOGE("Vr flinger is only supported for remote hardware composer"
1686 " service connections. Ignoring request to transition to vr"
1687 " flinger.");
1688 mVrFlingerRequestsDisplay = false;
1689 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001690 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001691
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001692 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001693
Steven Thomas0123ac62018-07-12 11:32:34 -07001694 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001695 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001696
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001697 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001698
1699 // Clear out all the output layers from the composition engine for all
1700 // displays before destroying the hardware composer interface. This ensures
1701 // any HWC layers are destroyed through that interface before it becomes
1702 // invalid.
1703 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001704 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001705 }
1706
Steven Thomas0123ac62018-07-12 11:32:34 -07001707 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1708 // called below. Clear the reference now so we don't accidentally use it
1709 // later.
1710 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001711
Steven Thomasb02664d2017-07-26 18:48:28 -07001712 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001713 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001714 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001715
Steven Thomasb02664d2017-07-26 18:48:28 -07001716 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001717 // Delete the current instance before creating the new one
1718 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1719 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1720 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001721 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001722
Lloyd Pique441d5042018-10-18 16:49:51 -07001723 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001724 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001725
1726 if (vrFlingerRequestsDisplay) {
1727 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001729
1730 mVisibleRegionsDirty = true;
1731 invalidateHwcGeometry();
1732
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001733 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001734 display = getDefaultDisplayDeviceLocked();
1735 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001736 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001737
Steven Thomasb02664d2017-07-26 18:48:28 -07001738 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001739 const nsecs_t vsyncPeriod = getVsyncPeriod();
1740 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001741
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001742 // The present fences returned from vr_hwc are not an accurate
1743 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001744 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001745
Steven Thomasb02664d2017-07-26 18:48:28 -07001746 // Use phase of 0 since phase is not known.
1747 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001748 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001749 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001750
Ana Krulecc2870422019-01-29 19:00:58 -08001751 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001752
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001753 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001754 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001755}
1756
Ady Abraham11579302019-09-19 12:35:58 -07001757bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1758 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001759 // We are storing the last 2 present fences. If sf's phase offset is to be
1760 // woken up before the actual vsync but targeting the next vsync, we need to check
1761 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001762 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1763 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001764
Ady Abraham11579302019-09-19 12:35:58 -07001765 if (fence == Fence::NO_FENCE) {
1766 return false;
1767 }
1768
1769 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1770 fence->wait(graceTimeMs);
1771 }
1772
1773 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001774}
1775
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001776void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001777 DisplayStatInfo stats;
1778 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001779 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001780 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001781 mExpectedPresentTime.store(
1782 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001783}
1784
Dominik Laskowski22488f62019-03-28 09:53:04 -07001785void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001786 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001787 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001788 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001789 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001790 // calculate the expected present time once and use the cached
1791 // value throughout this frame to make sure all layers are
1792 // seeing this same value.
1793 populateExpectedPresentTime();
1794
Ady Abraham11579302019-09-19 12:35:58 -07001795 // When Backpressure propagation is enabled we want to give a small grace period
1796 // for the present fence to fire instead of just giving up on this frame to handle cases
1797 // where present fence is just about to get signaled.
1798 const int graceTimeForPresentFenceMs =
1799 (mPropagateBackpressure &&
1800 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1801 ? 1
1802 : 0;
1803 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1804 previousFrameMissed(
1805 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001806 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1807 mHadDeviceComposition && frameMissed};
1808 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1809 mHadClientComposition && frameMissed};
1810
Alec Mouricc0fc602019-02-26 21:45:19 -08001811 if (frameMissed) {
1812 mFrameMissedCount++;
1813 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001814 if (mMissedFrameJankCount == 0) {
1815 mMissedFrameJankStart = systemTime();
1816 }
1817 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001818 }
1819
Alec Mouri40189b02019-03-05 15:07:54 -08001820 if (hwcFrameMissed) {
1821 mHwcFrameMissedCount++;
1822 }
1823
1824 if (gpuFrameMissed) {
1825 mGpuFrameMissedCount++;
1826 }
1827
Ady Abrahamadb9a992019-09-19 21:21:55 +00001828 if (frameMissed && mPropagateBackpressure) {
1829 if ((hwcFrameMissed && !gpuFrameMissed) ||
1830 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001831 signalLayerUpdate();
1832 break;
1833 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001834 }
Dan Stoza50182882016-07-08 12:02:20 -07001835
Alec Mouri5f487d42020-02-06 09:26:19 -08001836 // Our jank window is always at least 100ms since we missed a
1837 // frame...
1838 static constexpr nsecs_t kMinJankyDuration =
1839 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1840 // ...but if it's larger than 1s then we missed the trace cutoff.
1841 static constexpr nsecs_t kMaxJankyDuration =
1842 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1843 // If we're in a user build then don't push any atoms
1844 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1845 const auto displayDevice = getDefaultDisplayDeviceLocked();
1846 // Only report jank when the display is on, as displays in DOZE
1847 // power mode may operate at a different frame rate than is
1848 // reported in their config, which causes noticeable (but less
1849 // severe) jank.
1850 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1851 const nsecs_t currentTime = systemTime();
1852 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1853 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1854 ATRACE_NAME("Jank detected");
1855 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1856 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1857 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1858 jankyDurationMillis, mMissedFrameJankCount);
1859 }
1860
1861 // We either reported a jank event or we missed the trace
1862 // window, so clear counters here.
1863 if (jankDuration > kMinJankyDuration) {
1864 mMissedFrameJankCount = 0;
1865 mMissedFrameJankStart = 0;
1866 }
1867 }
1868 }
1869
Steven Thomas050b2c82017-03-06 11:45:16 -08001870 // Now that we're going to make it to the handleMessageTransaction()
1871 // call below it's safe to call updateVrFlinger(), which will
1872 // potentially trigger a display handoff.
1873 updateVrFlinger();
1874
Dan Stoza6b9454d2014-11-07 16:00:59 -08001875 bool refreshNeeded = handleMessageTransaction();
1876 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001877
Ana Krulecc84d09b2019-11-02 23:10:29 +01001878 // Layers need to get updated (in the previous line) before we can use them for
1879 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001880 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1881 // and may eventually call to ~Layer() if it holds the last reference
1882 {
1883 Mutex::Autolock _l(mStateLock);
1884 mScheduler->chooseRefreshRateForContent();
1885 }
1886
Ana Krulecc84d09b2019-11-02 23:10:29 +01001887 if (performSetActiveConfig()) {
1888 break;
1889 }
1890
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001891 updateCursorAsync();
1892 updateInputFlinger();
1893
Dan Stoza58784442014-12-02 16:58:17 -08001894 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001895 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001896 // Signal a refresh if a transaction modified the window state,
1897 // a new buffer was latched, or if HWC has requested a full
1898 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001899 if (mFrameStartTime <= 0) {
1900 // We should only use the time of the first invalidate
1901 // message that signals a refresh as the beginning of the
1902 // frame. Otherwise the real frame time will be
1903 // underestimated.
1904 mFrameStartTime = frameStart;
1905 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001906 signalRefresh();
1907 }
1908 break;
1909 }
1910 case MessageQueue::REFRESH: {
1911 handleMessageRefresh();
1912 break;
1913 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001914 }
1915}
1916
Dan Stoza6b9454d2014-11-07 16:00:59 -08001917bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001918 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001919 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001920
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001921 bool flushedATransaction = flushTransactionQueues();
1922
1923 bool runHandleTransaction = transactionFlags &&
1924 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1925
1926 if (runHandleTransaction) {
1927 handleTransaction(eTransactionMask);
1928 } else {
1929 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001930 }
1931
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001932 if (transactionFlushNeeded()) {
1933 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001934 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001935
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001936 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001937}
1938
Mathias Agopian4fec8732012-06-29 14:12:52 -07001939void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001940 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001941
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001942 mRefreshPending = false;
1943
Lloyd Piqueab039b52019-02-13 14:22:42 -08001944 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001945 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001946 for (const auto& [_, display] : mDisplays) {
1947 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1948 }
1949 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001950 if (auto layerFE = layer->getCompositionEngineLayerFE())
1951 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001952 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001953 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1954 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001955 if (auto layerFE = layer->getCompositionEngineLayerFE())
1956 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001957 }
1958
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001959 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001960 refreshArgs.outputColorSetting = useColorManagement
1961 ? mDisplayColorSetting
1962 : compositionengine::OutputColorSetting::kUnmanaged;
1963 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1964 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001965
1966 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1967 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001968 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001969
1970 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1971 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1972 mDrawingState.colorMatrixChanged = false;
1973 }
1974
1975 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1976
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001977 if (mDebugRegion != 0) {
1978 refreshArgs.devOptFlashDirtyRegionsDelay =
1979 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1980 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001981
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001982 mGeometryInvalid = false;
1983
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001984 // Store the present time just before calling to the composition engine so we could notify
1985 // the scheduler.
1986 const auto presentTime = systemTime();
1987
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001988 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001989 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1990 // Reset the frame start time now that we've recorded this frame.
1991 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001992
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001993 mScheduler->onDisplayRefreshed(presentTime);
1994
David Sodmanfa9b2af2017-12-24 13:28:59 -08001995 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001996 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001997
Lloyd Pique66d68602019-02-13 14:23:31 -08001998 mHadClientComposition =
1999 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2000 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002001 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2002 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002003 });
2004 mHadDeviceComposition =
2005 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2006 auto& displayDevice = tokenDisplayPair.second;
2007 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2008 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002009 mReusedClientComposition =
2010 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2011 auto& displayDevice = tokenDisplayPair.second;
2012 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2013 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002014
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002015 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002016
David Sodman7e4ae112018-02-09 15:02:28 -08002017 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002018 if (mVisibleRegionsDirty) {
2019 mVisibleRegionsDirty = false;
2020 if (mTracingEnabled) {
2021 mTracing.notify("visibleRegionsDirty");
2022 }
2023 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002024
2025 if (mCompositionEngine->needsAnotherUpdate()) {
2026 signalLayerUpdate();
2027 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002028}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002029
David Sodmanfa9b2af2017-12-24 13:28:59 -08002030
2031bool SurfaceFlinger::handleMessageInvalidate() {
2032 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002033 bool refreshNeeded = handlePageFlip();
2034
Vishnu Nair4351ad52019-02-11 14:13:02 -08002035 if (mVisibleRegionsDirty) {
2036 computeLayerBounds();
2037 }
2038
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002039 for (auto& layer : mLayersPendingRefresh) {
2040 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002041 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002042 invalidateLayerStack(layer, visibleReg);
2043 }
2044 mLayersPendingRefresh.clear();
2045 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002046}
2047
Ana Krulece588e312018-09-18 12:32:24 -07002048void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2049 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 // Update queue of past composite+present times and determine the
2051 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002052 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002054 while (!getBE().mCompositePresentTimes.empty()) {
2055 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002056 // Cached values should have been updated before calling this method,
2057 // which helps avoid duplicate syscalls.
2058 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2059 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2060 break;
2061 }
2062 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002063 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064 }
2065
2066 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002067 while (getBE().mCompositePresentTimes.size() > 16) {
2068 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069 }
2070
Ana Krulece588e312018-09-18 12:32:24 -07002071 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002072}
2073
Ana Krulece588e312018-09-18 12:32:24 -07002074void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2075 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076 // Integer division and modulo round toward 0 not -inf, so we need to
2077 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002078 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2079 ? (stats.vsyncPeriod -
2080 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2081 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002082
Ady Abraham9e16a482019-12-03 17:19:41 -08002083 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002084 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002085 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002086 }
2087
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088 // Snap the latency to a value that removes scheduling jitter from the
2089 // composition and present times, which often have >1ms of jitter.
2090 // Reducing jitter is important if an app attempts to extrapolate
2091 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002092 // Snapping also allows an app to precisely calculate
2093 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002094 nsecs_t bias = stats.vsyncPeriod / 2;
2095 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2096 nsecs_t snappedCompositeToPresentLatency =
2097 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098
David Sodman99974d22017-11-28 12:04:33 -08002099 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002100 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2101 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002102 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002103}
2104
David Sodman2b406362017-12-15 13:33:47 -08002105void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002106{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 ATRACE_CALL();
2108 ALOGV("postComposition");
2109
Brian Andersonf6386862016-10-31 16:34:13 -07002110 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002111 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002112 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002113 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002114 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002115 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002116
David Sodman73beded2017-11-15 11:56:06 -08002117 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002119 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002121 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2122 ->getRenderSurface()
2123 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002124 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002125 } else {
2126 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2127 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002128
David Sodman73beded2017-11-15 11:56:06 -08002129 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002130 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2131 mPreviousPresentFences[0] = displayDevice
2132 ? getHwComposer().getPresentFence(*displayDevice->getId())
2133 : Fence::NO_FENCE;
2134 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002135 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002136
Ana Krulece588e312018-09-18 12:32:24 -07002137 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002138 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002139
Lloyd Piqueab039b52019-02-13 14:22:42 -08002140 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2141 // be sampled a little later than when we started doing work for this frame,
2142 // but that should be okay since updateCompositorTiming has snapping logic.
2143 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2144 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002145 CompositorTiming compositorTiming;
2146 {
David Sodman99974d22017-11-28 12:04:33 -08002147 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2148 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002149 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002150
Edgar Arriaga844fa672020-01-16 14:21:42 -08002151 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002152 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2153 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002154 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002155 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002156 }
Robert Carr2047fae2016-11-28 14:09:09 -08002157 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002158
Ady Abraham92fa2f42020-02-11 15:33:56 -08002159 if (displayDevice && displayDevice->isPrimary() &&
2160 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002161 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002162 }
2163
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002164 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002165 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2166 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002167 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002168 }
2169 }
2170
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002171 if (mAnimCompositionPending) {
2172 mAnimCompositionPending = false;
2173
Brian Anderson4e606e32017-03-16 15:34:57 -07002174 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002175 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002176 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002177 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002178 // The HWC doesn't support present fences, so use the refresh
2179 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002180 const nsecs_t presentTime =
2181 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002182 mAnimFrameTracker.setActualPresentTime(presentTime);
2183 }
2184 mAnimFrameTracker.advanceFrame();
2185 }
Dan Stozab90cf072015-03-05 11:05:59 -08002186
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002187 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002188 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002189 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002190 }
2191
Vishnu Nair9b079a22020-01-21 14:36:08 -08002192 if (mReusedClientComposition) {
2193 mTimeStats->incrementClientCompositionReusedFrames();
2194 }
2195
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002196 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002197
Alec Mouri717bcb62020-02-10 17:07:19 -08002198 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2199 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2200 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2201
Lloyd Pique32cbe282018-10-19 13:09:22 -07002202 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2203 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002204 return;
2205 }
2206
2207 nsecs_t currentTime = systemTime();
2208 if (mHasPoweredOff) {
2209 mHasPoweredOff = false;
2210 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002211 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002212 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002213 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2214 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002215 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002216 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002217 }
David Sodman4a36e932017-11-07 14:29:47 -08002218 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002219 }
David Sodman4a36e932017-11-07 14:29:47 -08002220 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002221
2222 {
2223 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002224 if (mTexturePool.size() < mTexturePoolSize) {
2225 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002226 const size_t offset = mTexturePool.size();
2227 mTexturePool.resize(mTexturePoolSize);
2228 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2229 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002230 } else if (mTexturePool.size() > mTexturePoolSize) {
2231 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2232 const size_t offset = mTexturePoolSize;
2233 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2234 mTexturePool.resize(mTexturePoolSize);
2235 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002236 }
2237 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002238
Ady Abrahambe0f9482019-04-24 15:41:53 -07002239 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002240 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002241
Kevin DuBois413287f2019-02-25 08:46:47 -08002242 if (mLumaSampling && mRegionSamplingThread) {
2243 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002244 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002245
2246 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2247 // side-effect of getTotalSize(), so we check that again here
2248 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002249 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002250 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2251 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002252}
2253
Vishnu Nair4351ad52019-02-11 14:13:02 -08002254void SurfaceFlinger::computeLayerBounds() {
2255 for (const auto& pair : mDisplays) {
2256 const auto& displayDevice = pair.second;
2257 const auto display = displayDevice->getCompositionDisplay();
2258 for (const auto& layer : mDrawingState.layersSortedByZ) {
2259 // only consider the layers on the given layer stack
2260 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002261 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002262 }
2263
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002264 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2265 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002266 }
2267 }
2268}
2269
David Sodmanfa9b2af2017-12-24 13:28:59 -08002270void SurfaceFlinger::postFrame()
2271{
2272 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 const auto display = getDefaultDisplayDeviceLocked();
2274 if (display && getHwComposer().isConnected(*display->getId())) {
2275 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002276 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2277 logFrameStats();
2278 }
2279 }
2280}
2281
Mathias Agopian87baae12012-07-31 12:38:26 -07002282void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283{
Mathias Agopian841cde52012-03-01 15:44:37 -08002284 ATRACE_CALL();
2285
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002286 // here we keep a copy of the drawing state (that is the state that's
2287 // going to be overwritten by handleTransactionLocked()) outside of
2288 // mStateLock so that the side-effects of the State assignment
2289 // don't happen with mStateLock held (which can cause deadlocks).
2290 State drawingState(mDrawingState);
2291
Mathias Agopianca4d3602011-05-19 15:38:14 -07002292 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002293 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294
Mathias Agopianca4d3602011-05-19 15:38:14 -07002295 // Here we're guaranteed that some transaction flags are set
2296 // so we can call handleTransactionLocked() unconditionally.
2297 // We call getTransactionFlags(), which will also clear the flags,
2298 // with mStateLock held to guarantee that mCurrentState won't change
2299 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002300
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002301 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002302 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002303 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002304
Mathias Agopianca4d3602011-05-19 15:38:14 -07002305 mDebugInTransaction = 0;
2306 invalidateHwcGeometry();
2307 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002308}
2309
Lloyd Piqueba04e622017-12-14 17:11:26 -08002310void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2311 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002312 const std::optional<DisplayIdentificationInfo> info =
2313 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002314
Dominik Laskowski075d3172018-05-24 15:50:06 -07002315 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002316 continue;
2317 }
2318
Dominik Laskowski55c85402020-01-21 16:25:47 -08002319 const DisplayId displayId = info->id;
2320 const auto it = mPhysicalDisplayTokens.find(displayId);
2321
Lloyd Piqueba04e622017-12-14 17:11:26 -08002322 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002323 if (it == mPhysicalDisplayTokens.end()) {
2324 ALOGV("Creating display %s", to_string(displayId).c_str());
2325
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002326 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002327 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002328 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002329
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002331 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 state.isSecure = true; // All physical displays are currently considered secure.
2333 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002334
2335 sp<IBinder> token = new BBinder();
2336 mCurrentState.displays.add(token, state);
2337 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2338
Dominik Laskowski075d3172018-05-24 15:50:06 -07002339 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002340 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002341 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002342 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002343
Dominik Laskowski55c85402020-01-21 16:25:47 -08002344 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002345 if (index >= 0) {
2346 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2347 mInterceptor->saveDisplayDeletion(state.sequenceId);
2348 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002349 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002350 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002351 }
2352
2353 processDisplayChangesLocked();
2354 }
2355
2356 mPendingHotplugEvents.clear();
2357}
2358
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002359void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002360 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2361 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002362}
2363
Lloyd Pique99d3da52018-01-22 17:48:03 -08002364sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002365 const wp<IBinder>& displayToken,
2366 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002367 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002369 auto displayId = compositionDisplay->getDisplayId();
2370 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002371 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002372 creationArgs.isSecure = state.isSecure;
2373 creationArgs.displaySurface = dispSurface;
2374 creationArgs.hasWideColorGamut = false;
2375 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376
Dominik Laskowski55c85402020-01-21 16:25:47 -08002377 if (const auto& physical = state.physical) {
2378 creationArgs.connectionType = physical->type;
2379 }
2380
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002381 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002382 creationArgs.isPrimary = isInternalDisplay;
2383
2384 if (useColorManagement && displayId) {
2385 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002387 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002388 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002390
Dominik Laskowski7e045462018-05-30 13:02:02 -07002391 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002393 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394 }
tangrobin6753a022018-08-10 10:58:54 +08002395 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396
Dominik Laskowski075d3172018-05-24 15:50:06 -07002397 if (displayId) {
2398 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002399 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002401 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402
Lloyd Pique90c115d2018-09-18 21:39:42 -07002403 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002405 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002406
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 // Make sure that composition can never be stalled by a virtual display
2408 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002409 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002410 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2412 }
2413
Dominik Laskowski718f9602019-11-09 20:01:35 -08002414 creationArgs.physicalOrientation =
2415 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002416
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002418 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419
Lloyd Pique9370a482019-10-03 17:58:30 -07002420 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002421
2422 if (maxFrameBufferAcquiredBuffers >= 3) {
2423 nativeWindowSurface->preallocateBuffers();
2424 }
2425
2426 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002427 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002428 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002430 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002431 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002432 display->getCompositionDisplay()->setColorProfile(
2433 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2434 RenderIntent::COLORIMETRIC,
2435 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 if (!state.isVirtual()) {
2437 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002438 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2439 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002440 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 display->setLayerStack(state.layerStack);
2443 display->setProjection(state.orientation, state.viewport, state.frame);
2444 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002446 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002447}
2448
Lloyd Pique347200f2017-12-14 17:00:15 -08002449void SurfaceFlinger::processDisplayChangesLocked() {
2450 // here we take advantage of Vector's copy-on-write semantics to
2451 // improve performance by skipping the transaction entirely when
2452 // know that the lists are identical
2453 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2454 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2455 if (!curr.isIdenticalTo(draw)) {
2456 mVisibleRegionsDirty = true;
2457 const size_t cc = curr.size();
2458 size_t dc = draw.size();
2459
2460 // find the displays that were removed
2461 // (ie: in drawing state but not in current state)
2462 // also handle displays that changed
2463 // (ie: displays that are in both lists)
2464 for (size_t i = 0; i < dc;) {
2465 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2466 if (j < 0) {
2467 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002468 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002469 // Save display ID before disconnecting.
2470 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002471 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002472
2473 if (!display->isVirtual()) {
2474 LOG_ALWAYS_FATAL_IF(!displayId);
2475 dispatchDisplayHotplugEvent(displayId->value, false);
2476 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002478
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002479 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 } else {
2481 // this display is in both lists. see if something changed.
2482 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002484 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2485 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2486 if (state_binder != draw_binder) {
2487 // changing the surface is like destroying and
2488 // recreating the DisplayDevice, so we just remove it
2489 // from the drawing state, so that it get re-added
2490 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002491 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002492 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002493 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002494 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 mDrawingState.displays.removeItemsAt(i);
2496 dc--;
2497 // at this point we must loop to the next item
2498 continue;
2499 }
2500
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002503 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002504 }
2505 if ((state.orientation != draw[i].orientation) ||
2506 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002507 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 }
2509 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002511 if (display->isPrimary()) {
2512 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2513 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 }
2515 }
2516 }
2517 ++i;
2518 }
2519
2520 // find displays that were added
2521 // (ie: in current state but not in drawing state)
2522 for (size_t i = 0; i < cc; i++) {
2523 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2524 const DisplayDeviceState& state(curr[i]);
2525
Lloyd Pique9370a482019-10-03 17:58:30 -07002526 int width = 0;
2527 int height = 0;
2528 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2529 if (state.physical) {
2530 const auto& activeConfig =
2531 getCompositionEngine().getHwComposer().getActiveConfig(
2532 state.physical->id);
2533 width = activeConfig->getWidth();
2534 height = activeConfig->getHeight();
2535 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2536 } else if (state.surface != nullptr) {
2537 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2538 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2539 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2540 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2541 int intPixelFormat;
2542 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2543 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2544 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2545 } else {
2546 // Virtual displays without a surface are dormant:
2547 // they have external state (layer stack, projection,
2548 // etc.) but no internal state (i.e. a DisplayDevice).
2549 continue;
2550 }
2551
2552 compositionengine::DisplayCreationArgsBuilder builder;
2553 if (const auto& physical = state.physical) {
2554 builder.setPhysical({physical->id, physical->type});
2555 }
2556 builder.setPixels(ui::Size(width, height));
2557 builder.setPixelFormat(pixelFormat);
2558 builder.setIsSecure(state.isSecure);
2559 builder.setLayerStackId(state.layerStack);
2560 builder.setPowerAdvisor(&mPowerAdvisor);
2561 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2562 getHwComposer().isUsingVrComposer());
2563 builder.setName(state.displayName);
2564 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2565
Lloyd Pique542307f2018-10-19 13:24:08 -07002566 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 sp<IGraphicBufferProducer> producer;
2568 sp<IGraphicBufferProducer> bqProducer;
2569 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002570 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002571
Lloyd Pique9370a482019-10-03 17:58:30 -07002572 std::optional<DisplayId> displayId = compositionDisplay->getId();
2573
Dominik Laskowski663bd282018-04-19 15:26:54 -07002574 if (state.isVirtual()) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002575 sp<VirtualDisplaySurface> vds =
2576 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2577 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002578
Lloyd Pique9370a482019-10-03 17:58:30 -07002579 dispSurface = vds;
2580 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002581 } else {
2582 ALOGE_IF(state.surface != nullptr,
2583 "adding a supported display, but rendering "
2584 "surface is provided (%p), ignoring it",
2585 state.surface.get());
2586
Lloyd Pique9370a482019-10-03 17:58:30 -07002587 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002589 producer = bqProducer;
2590 }
2591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002592 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002593 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002594 mDisplays.emplace(displayToken,
Lloyd Pique9370a482019-10-03 17:58:30 -07002595 setupNewDisplayDeviceInternal(displayToken,
2596 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002597 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002598 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002600 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002602
2603 const auto displayDevice = mDisplays[displayToken];
2604 if (displayDevice->isPrimary()) {
2605 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2606 displayDevice->getHeight());
2607 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 }
2609 }
2610 }
2611 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002612
2613 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002614}
2615
Mathias Agopian87baae12012-07-31 12:38:26 -07002616void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002617{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002618 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2619
Dan Stoza7dde5992015-05-22 09:51:44 -07002620 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002621 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002622 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002623 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002624
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 /*
2626 * Traversal of the children
2627 * (perform the transaction for each of them if needed)
2628 */
2629
Marissa Wall06255332019-03-27 13:48:27 -07002630 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002631 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002633 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634
2635 const uint32_t flags = layer->doTransaction(0);
2636 if (flags & Layer::eVisibleRegion)
2637 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002638
2639 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002640 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002641 }
Robert Carr2047fae2016-11-28 14:09:09 -08002642 });
Marissa Wall06255332019-03-27 13:48:27 -07002643 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 }
2645
2646 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002647 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 */
2649
Mathias Agopiane57f2922012-08-09 16:29:12 -07002650 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002651 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002652 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002656 // The transform hint might have changed for some layers
2657 // (either because a display has changed, or because a layer
2658 // as changed).
2659 //
2660 // Walk through all the layers in currentLayers,
2661 // and update their transform hint.
2662 //
2663 // If a layer is visible only on a single display, then that
2664 // display is used to calculate the hint, otherwise we use the
2665 // default display.
2666 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002667 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002668 // the hint is set before we acquire a buffer from the surface texture.
2669 //
2670 // NOTE: layer transactions have taken place already, so we use their
2671 // drawing state. However, SurfaceFlinger's own transaction has not
2672 // happened yet, so we must use the current state layer list
2673 // (soon to become the drawing state list).
2674 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002675 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002676 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002677 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002678 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002679 // NOTE: we rely on the fact that layers are sorted by
2680 // layerStack first (so we don't have to traverse the list
2681 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002682 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002683 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002684 currentlayerStack = layerStack;
2685 // figure out if this layerstack is mirrored
2686 // (more than one display) if so, pick the default display,
2687 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002688 hintDisplay = nullptr;
2689 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002690 if (display->getCompositionDisplay()
2691 ->belongsInOutput(layer->getLayerStack(),
2692 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002693 if (hintDisplay) {
2694 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002695 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002698 }
2699 }
2700 }
2701 }
Chet Haase91d25932013-04-11 15:24:55 -07002702
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002703 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002704 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2705 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002706
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002707 // could be null when this layer is using a layerStack
2708 // that is not visible on any display. Also can occur at
2709 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002710 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002711 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002712
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002713 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002714 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 if (hintDisplay) {
2716 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002717 }
Robert Carr2047fae2016-11-28 14:09:09 -08002718
2719 first = false;
2720 });
Mathias Agopian84300952012-11-21 16:02:13 -08002721 }
2722
2723
Mathias Agopian3559b072012-08-15 13:46:03 -07002724 /*
2725 * Perform our own transaction if needed
2726 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727
2728 if (mLayersAdded) {
2729 mLayersAdded = false;
2730 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002731 mVisibleRegionsDirty = true;
2732 }
2733
2734 // some layers might have been removed, so
2735 // we need to update the regions they're exposing.
2736 if (mLayersRemoved) {
2737 mLayersRemoved = false;
2738 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002739 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002740 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002741 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002742 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002743 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002744 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002745 }
Robert Carr2047fae2016-11-28 14:09:09 -08002746 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 }
2748
Vishnu Nairec0ab382019-02-13 15:32:56 -08002749 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002751}
2752
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002753void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002754 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002755 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002756 return;
2757 }
2758
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002759 if (mVisibleRegionsDirty || mInputInfoChanged) {
2760 mInputInfoChanged = false;
2761 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002762 } else if (mInputWindowCommands.syncInputWindows) {
2763 // If the caller requested to sync input windows, but there are no
2764 // changes to input windows, notify immediately.
2765 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002766 }
2767
Arthur Hung6cbb9752019-09-05 16:38:18 +08002768 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002769}
2770
2771void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002772 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002773
2774 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2775 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002776 // When calculating the screen bounds we ignore the transparent region since it may
2777 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002778 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002779 }
2780 });
chaviw291d88a2019-02-14 10:33:58 -08002781
2782 mInputFlinger->setInputWindows(inputHandles,
2783 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2784 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002785}
2786
Vishnu Nairec0ab382019-02-13 15:32:56 -08002787void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002788 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002789 mPendingInputWindowCommands.clear();
2790}
2791
Riley Andrews03414a12014-07-01 14:22:59 -07002792void SurfaceFlinger::updateCursorAsync()
2793{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002794 compositionengine::CompositionRefreshArgs refreshArgs;
2795 for (const auto& [_, display] : mDisplays) {
2796 if (display->getId()) {
2797 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002798 }
2799 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002800
2801 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002802}
2803
Ady Abraham2139f732019-11-13 18:56:40 -08002804void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002805 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2806 // If this is called from the main thread mStateLock must be locked before
2807 // Currently the only way to call this function from the main thread is from
2808 // Sheduler::chooseRefreshRateForContent
2809
2810 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002811 changeRefreshRateLocked(refreshRate, event);
2812}
2813
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002814void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2815 if (mScheduler) {
2816 // In practice it's not allowed to hotplug in/out the primary display once it's been
2817 // connected during startup, but some tests do it, so just warn and return.
2818 ALOGW("Can't re-init scheduler");
2819 return;
2820 }
2821
Ady Abraham2139f732019-11-13 18:56:40 -08002822 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002823 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002824 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002825 primaryDisplayId),
2826 currentConfig);
2827 mRefreshRateStats =
2828 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2829 currentConfig, HWC_POWER_MODE_OFF);
2830 mRefreshRateStats->setConfigMode(currentConfig);
2831
Ady Abraham9e16a482019-12-03 17:19:41 -08002832 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2833
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002834 // start the EventThread
2835 mScheduler =
2836 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002837 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002838 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002839 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002840 impl::EventThread::InterceptVSyncsCallback());
2841 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002842 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002843 [this](nsecs_t timestamp) {
2844 mInterceptor->saveVSyncEvent(timestamp);
2845 });
2846
2847 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2848 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002849 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002850
2851 mRegionSamplingThread =
2852 new RegionSamplingThread(*this, *mScheduler,
2853 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002854 // Dispatch a config change request for the primary display on scheduler
2855 // initialization, so that the EventThreads always contain a reference to a
2856 // prior configuration.
2857 //
2858 // This is a bit hacky, but this avoids a back-pointer into the main SF
2859 // classes from EventThread, and there should be no run-time binder cost
2860 // anyway since there are no connected apps at this point.
2861 const nsecs_t vsyncPeriod =
2862 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2863 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2864 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002865}
2866
Mathias Agopian4fec8732012-06-29 14:12:52 -07002867void SurfaceFlinger::commitTransaction()
2868{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002869 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002870
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002871 mTransactionPending = false;
2872 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002873 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874}
2875
Lloyd Pique58e24a32019-08-01 15:50:14 -07002876void SurfaceFlinger::commitTransactionLocked() {
2877 if (!mLayersPendingRemoval.isEmpty()) {
2878 // Notify removed layers now that they can't be drawn from
2879 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002880 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002881
2882 // Ensure any buffers set to display on any children are released.
2883 if (l->isRemovedFromCurrentState()) {
2884 l->latchAndReleaseBuffer();
2885 }
2886
2887 // If the layer has been removed and has no parent, then it will not be reachable
2888 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2889 // ensure we can copy its current to drawing state.
2890 if (!l->getParent()) {
2891 mOffscreenLayers.emplace(l.get());
2892 }
2893 }
2894 mLayersPendingRemoval.clear();
2895 }
2896
2897 // If this transaction is part of a window animation then the next frame
2898 // we composite should be considered an animation as well.
2899 mAnimCompositionPending = mAnimTransactionPending;
2900
2901 mDrawingState = mCurrentState;
2902 // clear the "changed" flags in current state
2903 mCurrentState.colorMatrixChanged = false;
2904
Edgar Arriaga844fa672020-01-16 14:21:42 -08002905 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002906 layer->commitChildList();
2907
2908 // If the layer can be reached when traversing mDrawingState, then the layer is no
2909 // longer offscreen. Remove the layer from the offscreenLayer set.
2910 if (mOffscreenLayers.count(layer)) {
2911 mOffscreenLayers.erase(layer);
2912 }
2913 });
2914
2915 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002916 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002917}
2918
Nataniel Borges2b796da2019-02-15 13:32:18 -08002919void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2920 if (mTracingEnabledChanged) {
2921 mTracingEnabled = mTracing.isEnabled();
2922 mTracingEnabledChanged = false;
2923 }
2924
2925 // Synchronize with Tracing thread
2926 std::unique_lock<std::mutex> lock;
2927 if (mTracingEnabled) {
2928 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2929 }
2930
2931 lockedOperation();
2932
2933 // Synchronize with Tracing thread
2934 if (mTracingEnabled) {
2935 lock.unlock();
2936 }
2937}
2938
chaviw74d90ad2019-04-26 14:45:26 -07002939void SurfaceFlinger::commitOffscreenLayers() {
2940 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002941 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002942 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2943 if (!trFlags) return;
2944
2945 layer->doTransaction(0);
2946 layer->commitChildList();
2947 });
2948 }
2949}
2950
Chia-I Wuab0c3192017-08-01 11:29:00 -07002951void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002952 for (const auto& [token, displayDevice] : mDisplays) {
2953 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002954 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002955 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002956 }
2957 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002958}
2959
Dan Stoza6b9454d2014-11-07 16:00:59 -08002960bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961{
Ady Abraham09bd3922019-04-08 10:44:56 -07002962 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 ALOGV("handlePageFlip");
2964
Brian Andersond6927fb2016-07-23 23:37:30 -07002965 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966
Mathias Agopian4fec8732012-06-29 14:12:52 -07002967 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002968 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002969 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002970
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002971 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2972
Eric Penner51c59cd2014-07-28 19:51:58 -07002973 // Store the set of layers that need updates. This set must not change as
2974 // buffers are being latched, as this could result in a deadlock.
2975 // Example: Two producers share the same command stream and:
2976 // 1.) Layer 0 is latched
2977 // 2.) Layer 0 gets a new frame
2978 // 2.) Layer 1 gets a new frame
2979 // 3.) Layer 1 is latched.
2980 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2981 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002982 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002983 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002984 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002985 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002986 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002987 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002988 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002989 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002990 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002991 } else {
2992 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002993 }
Robert Carr2047fae2016-11-28 14:09:09 -08002994 });
2995
chaviw49a108c2019-08-12 11:23:06 -07002996 // The client can continue submitting buffers for offscreen layers, but they will not
2997 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2998 // layers to ensure dequeueBuffer doesn't block indefinitely.
2999 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003000 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003001 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3002 }
3003
Lloyd Piquef2c79392018-12-20 16:23:33 -08003004 if (!mLayersWithQueuedFrames.empty()) {
3005 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3006 // writes to Layer current state. See also b/119481871
3007 Mutex::Autolock lock(mStateLock);
3008
3009 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003010 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003011 mLayersPendingRefresh.push_back(layer);
3012 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003013 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003014 if (layer->isBufferLatched()) {
3015 newDataLatched = true;
3016 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003017 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003019
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003020 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003021
3022 // If we will need to wake up at some time in the future to deal with a
3023 // queued frame that shouldn't be displayed during this vsync period, wake
3024 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003025 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003026 signalLayerUpdate();
3027 }
3028
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003029 // enter boot animation on first buffer latch
3030 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3031 ALOGI("Enter boot animation");
3032 mBootStage = BootStage::BOOTANIMATION;
3033 }
3034
Edgar Arriaga844fa672020-01-16 14:21:42 -08003035 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003036
Dan Stoza6b9454d2014-11-07 16:00:59 -08003037 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003038 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Mathias Agopianad456f92011-01-13 17:53:01 -08003041void SurfaceFlinger::invalidateHwcGeometry()
3042{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003044}
3045
Robert Carrc0df3122019-04-11 13:18:21 -07003046status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3047 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3048 const sp<IBinder>& parentHandle,
3049 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003050 // add this layer to the current state list
3051 {
3052 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003053 sp<Layer> parent;
3054 if (parentHandle != nullptr) {
3055 parent = fromHandle(parentHandle);
3056 if (parent == nullptr) {
3057 return NAME_NOT_FOUND;
3058 }
3059 } else {
3060 parent = parentLayer;
3061 }
3062
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003064 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003065 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003066 return NO_MEMORY;
3067 }
Robert Carrc0df3122019-04-11 13:18:21 -07003068
3069 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3070
Robert Carrb89ea9d2018-12-10 13:01:14 -08003071 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003072 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003073 } else if (parent == nullptr) {
3074 lbc->onRemovedFromCurrentState();
3075 } else if (parent->isRemovedFromCurrentState()) {
3076 parent->addChild(lbc);
3077 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003078 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003079 parent->addChild(lbc);
3080 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003081
Yiwei Zhang243b3782018-05-15 17:40:04 -07003082 if (gbc != nullptr) {
3083 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3084 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3085 mMaxGraphicBufferProducerListSize,
3086 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3087 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003088 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003089 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3090 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3091 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3092 mNumLayers.load());
3093 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003094 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003096 }
3097
Mathias Agopian96f08192010-06-02 23:28:45 -07003098 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003099 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003100
Dan Stoza7d89d062015-04-30 13:29:25 -07003101 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003102}
3103
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003104uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003105 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003106}
3107
Mathias Agopian3f844832013-08-07 21:24:32 -07003108uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003109 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110}
3111
Mathias Agopian3f844832013-08-07 21:24:32 -07003112uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003113 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003114}
3115
3116uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003117 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003118 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003119 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003121 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 }
3123 return old;
3124}
3125
Marissa Wall713b63f2018-10-17 15:42:43 -07003126bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003127 // to prevent onHandleDestroyed from being called while the lock is held,
3128 // we must keep a copy of the transactions (specifically the composer
3129 // states) around outside the scope of the lock
3130 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003131 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003132 {
3133 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003134
Valerie Haufce31b82019-04-30 16:41:14 -07003135 auto it = mTransactionQueues.begin();
3136 while (it != mTransactionQueues.end()) {
3137 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003138
Valerie Haufce31b82019-04-30 16:41:14 -07003139 while (!transactionQueue.empty()) {
3140 const auto& transaction = transactionQueue.front();
3141 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003142 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003143 transaction.states)) {
3144 setTransactionFlags(eTransactionFlushNeeded);
3145 break;
3146 }
3147 transactions.push_back(transaction);
3148 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3149 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003150 transaction.buffer, transaction.postTime,
3151 transaction.privileged, transaction.hasListenerCallbacks,
3152 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003153 transactionQueue.pop();
3154 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003155 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003156
Valerie Haufce31b82019-04-30 16:41:14 -07003157 if (transactionQueue.empty()) {
3158 it = mTransactionQueues.erase(it);
3159 mTransactionCV.broadcast();
3160 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003161 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003162 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003163 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003164 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003165 return flushedATransaction;
3166}
3167
3168bool SurfaceFlinger::transactionFlushNeeded() {
3169 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003170}
3171
chaviwca27f252018-02-06 16:46:39 -08003172
Marissa Wall17b4e452018-12-26 16:32:34 -08003173bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003174 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003175 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003176 if (!useCachedExpectedPresentTime)
3177 populateExpectedPresentTime();
3178
3179 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003180 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3181 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3182 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3183 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3184 return false;
3185 }
3186
Marissa Wall713b63f2018-10-17 15:42:43 -07003187 for (const ComposerState& state : states) {
3188 const layer_state_t& s = state.state;
3189 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3190 continue;
3191 }
3192 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003193 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003194 }
3195 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003196 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003197}
3198
Valerie Hau9dab9732019-08-20 09:29:25 -07003199void SurfaceFlinger::setTransactionState(
3200 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3201 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3202 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3203 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003204 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003205
Valerie Haubc6ddb12019-03-08 11:10:15 -08003206 const int64_t postTime = systemTime();
3207
Robert Carr14167e02019-02-13 13:50:55 -08003208 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3209
Mathias Agopian698c0872011-06-28 19:09:31 -07003210 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003211
Marissa Wall713b63f2018-10-17 15:42:43 -07003212 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003213 auto itr = mTransactionQueues.find(applyToken);
3214 // if this is an animation frame, wait until prior animation frame has
3215 // been applied by SF
3216 if (flags & eAnimation) {
3217 while (itr != mTransactionQueues.end()) {
3218 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3219 if (CC_UNLIKELY(err != NO_ERROR)) {
3220 ALOGW_IF(err == TIMED_OUT,
3221 "setTransactionState timed out "
3222 "waiting for animation frame to apply");
3223 break;
3224 }
3225 itr = mTransactionQueues.find(applyToken);
3226 }
3227 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003228
3229 // Expected present time is computed and cached on invalidate, so it may be stale.
3230 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3231 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003232 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003233 uncacheBuffer, postTime, privileged,
3234 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003235 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003236 return;
3237 }
3238
Valerie Haubc6ddb12019-03-08 11:10:15 -08003239 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003240 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3241 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003242}
3243
Valerie Hau9dab9732019-08-20 09:29:25 -07003244void SurfaceFlinger::applyTransactionState(
3245 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3246 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3247 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3248 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3249 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003250 uint32_t transactionFlags = 0;
3251
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003252 if (flags & eAnimation) {
3253 // For window updates that are part of an animation we must wait for
3254 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003255 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003256 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003257 if (CC_UNLIKELY(err != NO_ERROR)) {
3258 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003259 // caller after a few seconds.
3260 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3261 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003262 mAnimTransactionPending = false;
3263 break;
3264 }
3265 }
3266 }
3267
chaviwca27f252018-02-06 16:46:39 -08003268 for (const DisplayState& display : displays) {
3269 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003270 }
3271
Valerie Hau9dab9732019-08-20 09:29:25 -07003272 // start and end registration for listeners w/ no surface so they can get their callback. Note
3273 // that listeners with SurfaceControls will start registration during setClientStateLocked
3274 // below.
3275 for (const auto& listener : listenerCallbacks) {
3276 mTransactionCompletedThread.startRegistration(listener);
3277 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003278 }
3279
Valerie Hau9dab9732019-08-20 09:29:25 -07003280 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003281 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003282 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003283 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3284 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003285 }
3286
Valerie Hau9dab9732019-08-20 09:29:25 -07003287 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003288 mTransactionCompletedThread.endRegistration(listenerCallback);
3289 }
3290
Marissa Walle2ffb422018-10-12 11:33:52 -07003291 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003292 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003293 mTransactionCompletedThread.sendCallbacks();
3294 }
3295 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003296
chaviw273171b2018-12-26 11:46:30 -08003297 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3298
Marissa Wall947d34e2019-03-29 14:03:53 -07003299 if (uncacheBuffer.isValid()) {
3300 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003301 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003302 }
3303
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003304 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3305 // anyway. This can be used as a flush mechanism for previous async transactions.
3306 // Empty animation transaction can be used to simulate back-pressure, so also force a
3307 // transaction for empty animation transactions.
3308 if (transactionFlags == 0 &&
3309 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003310 transactionFlags = eTransactionNeeded;
3311 }
3312
Marissa Wall06255332019-03-27 13:48:27 -07003313 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3314 // so we don't have to wake up again next frame to preform an uneeded traversal.
3315 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3316 transactionFlags = transactionFlags & (~eTraversalNeeded);
3317 mTraversalNeededMainThread = true;
3318 }
3319
Mathias Agopian386aa982011-11-07 21:58:03 -08003320 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003321 if (mInterceptor->isEnabled()) {
3322 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003323 }
Irvel468051e2016-06-13 16:44:44 -07003324
Mathias Agopian386aa982011-11-07 21:58:03 -08003325 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003326 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3327 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003328 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003329
3330 // if this is a synchronous transaction, wait for it to take effect
3331 // before returning.
3332 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003333 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003334 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003335 if (flags & eAnimation) {
3336 mAnimTransactionPending = true;
3337 }
chaviw4fe36852019-04-15 16:25:49 -07003338 if (mPendingInputWindowCommands.syncInputWindows) {
3339 mPendingSyncInputWindows = true;
3340 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003341
3342 // applyTransactionState can be called by either the main SF thread or by
3343 // another process through setTransactionState. While a given process may wish
3344 // to wait on synchronous transactions, the main SF thread should never
3345 // be blocked. Therefore, we only wait if isMainThread is false.
3346 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003347 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3348 if (CC_UNLIKELY(err != NO_ERROR)) {
3349 // just in case something goes wrong in SF, return to the
3350 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3352 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003353 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003354 break;
3355 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003356 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 }
3358}
3359
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003360uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3361 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3362 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003363
Mathias Agopiane57f2922012-08-09 16:29:12 -07003364 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003365 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3366
3367 const uint32_t what = s.what;
3368 if (what & DisplayState::eSurfaceChanged) {
3369 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3370 state.surface = s.surface;
3371 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003372 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003374 if (what & DisplayState::eLayerStackChanged) {
3375 if (state.layerStack != s.layerStack) {
3376 state.layerStack = s.layerStack;
3377 flags |= eDisplayTransactionNeeded;
3378 }
3379 }
3380 if (what & DisplayState::eDisplayProjectionChanged) {
3381 if (state.orientation != s.orientation) {
3382 state.orientation = s.orientation;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 if (state.frame != s.frame) {
3386 state.frame = s.frame;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 if (state.viewport != s.viewport) {
3390 state.viewport = s.viewport;
3391 flags |= eDisplayTransactionNeeded;
3392 }
3393 }
3394 if (what & DisplayState::eDisplaySizeChanged) {
3395 if (state.width != s.width) {
3396 state.width = s.width;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 if (state.height != s.height) {
3400 state.height = s.height;
3401 flags |= eDisplayTransactionNeeded;
3402 }
3403 }
3404
Mathias Agopiane57f2922012-08-09 16:29:12 -07003405 return flags;
3406}
3407
Robert Carr14167e02019-02-13 13:50:55 -08003408bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003409 IPCThreadState* ipc = IPCThreadState::self();
3410 const int pid = ipc->getCallingPid();
3411 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003412 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003413 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003414 return false;
3415 }
3416 return true;
3417}
3418
Marissa Wall3dad52d2019-03-22 14:03:19 -07003419uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003420 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3421 bool privileged,
3422 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003423 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003424
Valerie Hau9dab9732019-08-20 09:29:25 -07003425 for (auto& listener : s.listeners) {
3426 // note that startRegistration will not re-register if the listener has
3427 // already be registered for a prior surface control
3428 mTransactionCompletedThread.startRegistration(listener);
3429 listenerCallbacks.insert(listener);
3430 }
3431
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003432 sp<Layer> layer = nullptr;
3433 if (s.surface) {
3434 layer = fromHandle(s.surface);
3435 } else {
3436 // The client may provide us a null handle. Treat it as if the layer was removed.
3437 ALOGW("Attempt to set client state with a null layer handle");
3438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003440 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003441 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003442 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003443 }
chaviw8b3871a2017-11-01 17:41:01 -07003444 return 0;
3445 }
3446
chaviw8b3871a2017-11-01 17:41:01 -07003447 uint32_t flags = 0;
3448
Garfield Tan8a3083e2018-12-03 13:21:07 -08003449 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003450
3451 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3452 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003453 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003454 layer->pushPendingState();
3455 }
3456
Valerie Hau871d6352020-01-29 08:44:02 -08003457 // Only set by BLAST adapter layers
3458 if (what & layer_state_t::eProducerDisconnect) {
3459 layer->onDisconnect();
3460 }
3461
chaviw8b3871a2017-11-01 17:41:01 -07003462 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003463 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003464 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003465 }
chaviw8b3871a2017-11-01 17:41:01 -07003466 }
3467 if (what & layer_state_t::eLayerChanged) {
3468 // NOTE: index needs to be calculated before we update the state
3469 const auto& p = layer->getParent();
3470 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003471 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003472 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 mCurrentState.layersSortedByZ.removeAt(idx);
3474 mCurrentState.layersSortedByZ.add(layer);
3475 // we need traversal (state changed)
3476 // AND transaction (list changed)
3477 flags |= eTransactionNeeded|eTraversalNeeded;
3478 }
chaviw8b3871a2017-11-01 17:41:01 -07003479 } else {
3480 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003481 flags |= eTransactionNeeded|eTraversalNeeded;
3482 }
3483 }
chaviw8b3871a2017-11-01 17:41:01 -07003484 }
3485 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003486 // NOTE: index needs to be calculated before we update the state
3487 const auto& p = layer->getParent();
3488 if (p == nullptr) {
3489 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3490 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3491 mCurrentState.layersSortedByZ.removeAt(idx);
3492 mCurrentState.layersSortedByZ.add(layer);
3493 // we need traversal (state changed)
3494 // AND transaction (list changed)
3495 flags |= eTransactionNeeded|eTraversalNeeded;
3496 }
3497 } else {
3498 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3499 flags |= eTransactionNeeded|eTraversalNeeded;
3500 }
chaviw8b3871a2017-11-01 17:41:01 -07003501 }
3502 }
3503 if (what & layer_state_t::eSizeChanged) {
3504 if (layer->setSize(s.w, s.h)) {
3505 flags |= eTraversalNeeded;
3506 }
3507 }
3508 if (what & layer_state_t::eAlphaChanged) {
3509 if (layer->setAlpha(s.alpha))
3510 flags |= eTraversalNeeded;
3511 }
3512 if (what & layer_state_t::eColorChanged) {
3513 if (layer->setColor(s.color))
3514 flags |= eTraversalNeeded;
3515 }
Peiyong Lind3788632018-09-18 16:01:31 -07003516 if (what & layer_state_t::eColorTransformChanged) {
3517 if (layer->setColorTransform(s.colorTransform)) {
3518 flags |= eTraversalNeeded;
3519 }
3520 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003521 if (what & layer_state_t::eBackgroundColorChanged) {
3522 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3523 flags |= eTraversalNeeded;
3524 }
3525 }
chaviw8b3871a2017-11-01 17:41:01 -07003526 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527 // TODO: b/109894387
3528 //
3529 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3530 // rotation. To see the problem observe that if we have a square parent, and a child
3531 // of the same size, then we rotate the child 45 degrees around it's center, the child
3532 // must now be cropped to a non rectangular 8 sided region.
3533 //
3534 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3535 // private API, and the WindowManager only uses rotation in one case, which is on a top
3536 // level layer in which cropping is not an issue.
3537 //
3538 // However given that abuse of rotation matrices could lead to surfaces extending outside
3539 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3540 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3541 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003542 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003543 flags |= eTraversalNeeded;
3544 }
3545 if (what & layer_state_t::eTransparentRegionChanged) {
3546 if (layer->setTransparentRegionHint(s.transparentRegion))
3547 flags |= eTraversalNeeded;
3548 }
3549 if (what & layer_state_t::eFlagsChanged) {
3550 if (layer->setFlags(s.flags, s.mask))
3551 flags |= eTraversalNeeded;
3552 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003553 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003554 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003555 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003556 if (what & layer_state_t::eCornerRadiusChanged) {
3557 if (layer->setCornerRadius(s.cornerRadius))
3558 flags |= eTraversalNeeded;
3559 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003560 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3561 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3562 }
chaviw8b3871a2017-11-01 17:41:01 -07003563 if (what & layer_state_t::eLayerStackChanged) {
3564 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3565 // We only allow setting layer stacks for top level layers,
3566 // everything else inherits layer stack from its parent.
3567 if (layer->hasParent()) {
3568 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003569 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003570 } else if (idx < 0) {
3571 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003572 "that also does not appear in the top level layer list. Something"
3573 " has gone wrong.",
3574 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003575 } else if (layer->setLayerStack(s.layerStack)) {
3576 mCurrentState.layersSortedByZ.removeAt(idx);
3577 mCurrentState.layersSortedByZ.add(layer);
3578 // we need traversal (state changed)
3579 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003580 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003581 }
3582 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003583 if (what & layer_state_t::eDeferTransaction_legacy) {
3584 if (s.barrierHandle_legacy != nullptr) {
3585 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3586 } else if (s.barrierGbp_legacy != nullptr) {
3587 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003588 if (authenticateSurfaceTextureLocked(gbp)) {
3589 const auto& otherLayer =
3590 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003591 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003592 } else {
3593 ALOGE("Attempt to defer transaction to to an"
3594 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003595 }
3596 }
chaviw8b3871a2017-11-01 17:41:01 -07003597 // We don't trigger a traversal here because if no other state is
3598 // changed, we don't want this to cause any more work
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 if (what & layer_state_t::eReparentChildren) {
3601 if (layer->reparentChildren(s.reparentHandle)) {
3602 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003603 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 if (what & layer_state_t::eDetachChildren) {
3606 layer->detachChildren();
3607 }
3608 if (what & layer_state_t::eOverrideScalingModeChanged) {
3609 layer->setOverrideScalingMode(s.overrideScalingMode);
3610 // We don't trigger a traversal here because if no other state is
3611 // changed, we don't want this to cause any more work
3612 }
Marissa Wall61c58622018-07-18 10:12:20 -07003613 if (what & layer_state_t::eTransformChanged) {
3614 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3615 }
3616 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3617 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3618 flags |= eTraversalNeeded;
3619 }
3620 if (what & layer_state_t::eCropChanged) {
3621 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3622 }
Marissa Wall861616d2018-10-22 12:52:23 -07003623 if (what & layer_state_t::eFrameChanged) {
3624 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3625 }
Marissa Wall61c58622018-07-18 10:12:20 -07003626 if (what & layer_state_t::eAcquireFenceChanged) {
3627 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3628 }
3629 if (what & layer_state_t::eDataspaceChanged) {
3630 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3631 }
3632 if (what & layer_state_t::eHdrMetadataChanged) {
3633 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3634 }
3635 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3636 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eApiChanged) {
3639 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eSidebandStreamChanged) {
3642 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3643 }
Robert Carr720e5062018-07-30 17:45:14 -07003644 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003645 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003646 layer->setInputInfo(s.inputInfo);
3647 flags |= eTraversalNeeded;
3648 } else {
3649 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3650 }
Robert Carr720e5062018-07-30 17:45:14 -07003651 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003652 if (what & layer_state_t::eMetadataChanged) {
3653 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3654 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003655 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3656 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3657 flags |= eTraversalNeeded;
3658 }
3659 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003660 if (what & layer_state_t::eShadowRadiusChanged) {
3661 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3662 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003663 if (what & layer_state_t::eFrameRateSelectionPriority) {
3664 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3665 flags |= eTraversalNeeded;
3666 }
3667 }
Steven Thomas3172e202020-01-06 19:25:30 -08003668 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003669 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3670 "SurfaceFlinger::setClientStateLocked") &&
3671 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3672 Layer::FrameRate::convertCompatibility(
3673 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003674 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003675 }
Steven Thomas3172e202020-01-06 19:25:30 -08003676 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003677 // This has to happen after we reparent children because when we reparent to null we remove
3678 // child layers from current state and remove its relative z. If the children are reparented in
3679 // the same transaction, then we have to make sure we reparent the children first so we do not
3680 // lose its relative z order.
3681 if (what & layer_state_t::eReparent) {
3682 bool hadParent = layer->hasParent();
3683 if (layer->reparent(s.parentHandleForChild)) {
3684 if (!hadParent) {
3685 mCurrentState.layersSortedByZ.remove(layer);
3686 }
3687 flags |= eTransactionNeeded | eTraversalNeeded;
3688 }
3689 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003690 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003691 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3692 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003693 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3694 }
3695 }
Marissa Wall78b72202019-03-15 14:58:34 -07003696 bool bufferChanged = what & layer_state_t::eBufferChanged;
3697 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3698 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003699 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003700 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003701 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3702 if (success) {
3703 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3704 success = ClientCache::getInstance()
3705 .registerErasedRecipient(s.cachedBuffer,
3706 wp<ClientCache::ErasedRecipient>(this));
3707 if (!success) {
3708 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3709 }
3710 }
Marissa Wall78b72202019-03-15 14:58:34 -07003711 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003712 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003713 } else if (bufferChanged) {
3714 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003715 }
Marissa Wall78b72202019-03-15 14:58:34 -07003716 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003717 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3718 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003719 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003720 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003721 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003722 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3723 // Do not put anything that updates layer state or modifies flags after
3724 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003725 return flags;
3726}
3727
chaviw273171b2018-12-26 11:46:30 -08003728uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3729 uint32_t flags = 0;
3730 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3731 flags |= eTraversalNeeded;
3732 }
3733
chaviwa911b102019-02-14 10:18:33 -08003734 if (inputWindowCommands.syncInputWindows) {
3735 flags |= eTraversalNeeded;
3736 }
3737
Vishnu Nairec0ab382019-02-13 15:32:56 -08003738 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003739 return flags;
3740}
3741
chaviwfe94a222019-08-21 13:52:59 -07003742status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3743 sp<IBinder>* outHandle) {
3744 if (!mirrorFromHandle) {
3745 return NAME_NOT_FOUND;
3746 }
3747
3748 sp<Layer> mirrorLayer;
3749 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003750 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003751
3752 {
3753 Mutex::Autolock _l(mStateLock);
3754 mirrorFrom = fromHandle(mirrorFromHandle);
3755 if (!mirrorFrom) {
3756 return NAME_NOT_FOUND;
3757 }
3758
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3760 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003761 if (result != NO_ERROR) {
3762 return result;
3763 }
3764
3765 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3766 }
3767
3768 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3769}
3770
Marissa Wall2d814fb2019-04-09 18:52:57 +00003771status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3772 uint32_t h, PixelFormat format, uint32_t flags,
3773 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003774 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003775 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3776 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003777 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003778 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003779 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003780 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003781 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003782
Robert Carrc0df3122019-04-11 13:18:21 -07003783 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3784 "Expected only one of parentLayer or parentHandle to be non-null. "
3785 "Programmer error?");
3786
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003787 status_t result = NO_ERROR;
3788
3789 sp<Layer> layer;
3790
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003791 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003792
Evan Roskya1f1e152019-01-24 16:17:46 -08003793 bool primaryDisplayOnly = false;
3794
3795 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3796 // TODO b/64227542
3797 if (metadata.has(METADATA_WINDOW_TYPE)) {
3798 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3799 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003800 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003801 primaryDisplayOnly = true;
3802 }
3803 }
3804
Mathias Agopian3165cc22012-08-08 19:42:09 -07003805 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003806 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003807 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3808 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003809
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003810 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003811 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003812 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003813 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003814 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003815 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003816 // check if buffer size is set for color layer.
3817 if (w > 0 || h > 0) {
3818 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3819 int(w), int(h));
3820 return BAD_VALUE;
3821 }
3822
Vishnu Nairfa247b12020-02-11 08:58:26 -08003823 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3824 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003825 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003826 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003827 // check if buffer size is set for container layer.
3828 if (w > 0 || h > 0) {
3829 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3830 int(w), int(h));
3831 return BAD_VALUE;
3832 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003833 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3834 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003835 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003836 default:
3837 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003838 break;
3839 }
3840
Dan Stoza7d89d062015-04-30 13:29:25 -07003841 if (result != NO_ERROR) {
3842 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003844
Evan Roskya1f1e152019-01-24 16:17:46 -08003845 if (primaryDisplayOnly) {
3846 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003847 }
3848
Robert Carrb89ea9d2018-12-10 13:01:14 -08003849 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003850 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3851 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003852 if (result != NO_ERROR) {
3853 return result;
3854 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003855 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003856
3857 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003858 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859}
3860
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003861std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3862 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003863
3864 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003865 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003866
Dan Stoza436ccf32018-06-21 12:10:12 -07003867 // Grab the state lock since we're accessing mCurrentState
3868 Mutex::Autolock lock(mStateLock);
3869
Cody Northropbc755282017-03-31 12:00:08 -06003870 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003871 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003872 while (matchFound) {
3873 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003874 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003875 if (layer->getName() == uniqueName) {
3876 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003877 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003878 }
3879 });
3880 }
3881
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003882 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003883 return uniqueName;
3884}
3885
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003886status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003887 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003888 LayerMetadata metadata, PixelFormat& format,
3889 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003890 sp<IGraphicBufferProducer>* gbp,
3891 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003893 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 case PIXEL_FORMAT_TRANSPARENT:
3895 case PIXEL_FORMAT_TRANSLUCENT:
3896 format = PIXEL_FORMAT_RGBA_8888;
3897 break;
3898 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003899 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900 break;
3901 }
3902
chaviwb4c6e582019-08-16 14:35:07 -07003903 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003904 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003905 args.textureName = getNewTexture();
3906 {
3907 // Grab the SF state lock during this since it's the only safe way to access
3908 // RenderEngine when creating a BufferLayerConsumer
3909 // TODO: Check if this lock is still needed here
3910 Mutex::Autolock lock(mStateLock);
3911 layer = getFactory().createBufferQueueLayer(args);
3912 }
3913
Marissa Wallfd668622018-05-10 10:21:13 -07003914 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003915 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003916 *handle = layer->getHandle();
3917 *gbp = layer->getProducer();
3918 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003920
Marissa Wallfd668622018-05-10 10:21:13 -07003921 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003922 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923}
3924
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003925status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003926 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003927 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003928 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003929 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003930 args.displayDevice = getDefaultDisplayDevice();
3931 args.textureName = getNewTexture();
3932 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003933 if (outTransformHint) {
3934 *outTransformHint = layer->getTransformHint();
3935 }
Marissa Wall61c58622018-07-18 10:12:20 -07003936 *handle = layer->getHandle();
3937 *outLayer = layer;
3938
3939 return NO_ERROR;
3940}
3941
Vishnu Nairfa247b12020-02-11 08:58:26 -08003942status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3943 uint32_t h, uint32_t flags, LayerMetadata metadata,
3944 sp<IBinder>* handle, sp<Layer>* outLayer) {
3945 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003946 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003947 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003948 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003949}
3950
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003951status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003952 uint32_t w, uint32_t h, uint32_t flags,
3953 LayerMetadata metadata, sp<IBinder>* handle,
3954 sp<Layer>* outLayer) {
3955 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003956 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003957 *handle = (*outLayer)->getHandle();
3958 return NO_ERROR;
3959}
3960
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003961void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003962 mLayersPendingRemoval.add(layer);
3963 mLayersRemoved = true;
3964 setTransactionFlags(eTransactionNeeded);
3965}
3966
Robert Carr695d5282018-12-18 15:27:58 -08003967void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003968{
Robert Carr2e102c92018-10-23 12:11:15 -07003969 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003970 // If a layer has a parent, we allow it to out-live it's handle
3971 // with the idea that the parent holds a reference and will eventually
3972 // be cleaned up. However no one cleans up the top-level so we do so
3973 // here.
3974 if (layer->getParent() == nullptr) {
3975 mCurrentState.layersSortedByZ.remove(layer);
3976 }
3977 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003978
3979 auto it = mLayersByLocalBinderToken.begin();
3980 while (it != mLayersByLocalBinderToken.end()) {
3981 if (it->second == layer) {
3982 it = mLayersByLocalBinderToken.erase(it);
3983 } else {
3984 it++;
3985 }
3986 }
3987
Robert Carr695d5282018-12-18 15:27:58 -08003988 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003989}
3990
Mathias Agopianb60314a2012-04-10 22:09:54 -07003991// ---------------------------------------------------------------------------
3992
Andy McFadden13a082e2012-08-24 10:16:42 -07003993void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003994 const auto display = getDefaultDisplayDeviceLocked();
3995 if (!display) return;
3996
3997 const sp<IBinder> token = display->getDisplayToken().promote();
3998 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003999
Jesse Hall01e29052013-02-19 16:13:35 -08004000 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004001 Vector<ComposerState> state;
4002 Vector<DisplayState> displays;
4003 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004004 d.what = DisplayState::eDisplayProjectionChanged |
4005 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004006 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004007 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004008 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004009 d.frame.makeInvalid();
4010 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004011 d.width = 0;
4012 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004013 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004014 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4015 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004016
Dominik Laskowskie9774092018-12-11 10:04:24 -08004017 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004018
Dominik Laskowski83b88212018-12-11 13:34:06 -08004019 const nsecs_t vsyncPeriod = getVsyncPeriod();
4020 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004021
Brian Andersond0010582017-03-07 13:20:31 -08004022 // Use phase of 0 since phase is not known.
4023 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004024 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004025 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004026}
4027
4028void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004029 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004030 postMessageAsync(
4031 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004032}
4033
Ady Abraham27c70212019-06-11 10:52:26 -07004034void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4035 if (mHWCVsyncState != enabled) {
4036 getHwComposer().setVsyncEnabled(displayId, enabled);
4037 mHWCVsyncState = enabled;
4038 }
4039}
4040
Dominik Laskowskie9774092018-12-11 10:04:24 -08004041void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004042 if (display->isVirtual()) {
4043 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004044 return;
4045 }
4046
Dominik Laskowski075d3172018-05-24 15:50:06 -07004047 const auto displayId = display->getId();
4048 LOG_ALWAYS_FATAL_IF(!displayId);
4049
Dominik Laskowski34157762018-10-31 13:07:19 -07004050 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004051
4052 int currentMode = display->getPowerMode();
4053 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004054 return;
4055 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004057 display->setPowerMode(mode);
4058
Lloyd Pique4dccc412018-01-22 17:21:36 -08004059 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004060 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004061 }
4062
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004063 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004064 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004065 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004066 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004067 mScheduler->onScreenAcquired(mAppConnectionHandle);
4068 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004069 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004070
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004071 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004072 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004073 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004074
4075 struct sched_param param = {0};
4076 param.sched_priority = 1;
4077 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4078 ALOGW("Couldn't set SCHED_FIFO on display on");
4079 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004080 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004081 // Turn off the display
4082 struct sched_param param = {0};
4083 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4084 ALOGW("Couldn't set SCHED_OTHER on display off");
4085 }
4086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004087 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004088 mScheduler->disableHardwareVsync(true);
4089 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004090 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004091
Ady Abraham27c70212019-06-11 10:52:26 -07004092 // Make sure HWVsync is disabled before turning off the display
4093 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4094
Dominik Laskowski075d3172018-05-24 15:50:06 -07004095 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004096 mVisibleRegionsDirty = true;
4097 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004098 } else if (mode == HWC_POWER_MODE_DOZE ||
4099 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004100 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004101 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004103 mScheduler->onScreenAcquired(mAppConnectionHandle);
4104 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004105 }
4106 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4107 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004108 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004109 mScheduler->disableHardwareVsync(true);
4110 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004111 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004112 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004113 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004114 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004115 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004116 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004117
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004118 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004119 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004120 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004121 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004122 }
4123
Dominik Laskowski34157762018-10-31 13:07:19 -07004124 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004125}
4126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004127void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004128 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004129 const auto display = getDisplayDevice(displayToken);
4130 if (!display) {
4131 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4132 displayToken.get());
4133 } else if (display->isVirtual()) {
4134 ALOGW("Attempt to set power mode %d for virtual display", mode);
4135 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004136 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004137 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004138 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004139}
4140
4141// ---------------------------------------------------------------------------
4142
Dominik Laskowskic2867142019-01-21 11:33:38 -08004143status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4144 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004145 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004146
Mathias Agopianbd115332013-04-18 16:41:04 -07004147 IPCThreadState* ipc = IPCThreadState::self();
4148 const int pid = ipc->getCallingPid();
4149 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004150
Mathias Agopianbd115332013-04-18 16:41:04 -07004151 if ((uid != AID_SHELL) &&
4152 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004153 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4154 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004156 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004157 // (this would indicate SF is stuck, but we want to be able to
4158 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004159 status_t err = mStateLock.timedLock(s2ns(1));
4160 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004161 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004162 StringAppendF(&result,
4163 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4164 "(no locks held)\n",
4165 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004166 }
4167
Dominik Laskowskic2867142019-01-21 11:33:38 -08004168 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004169 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004170 {"--dispsync"s,
4171 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004172 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004173 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4174 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4175 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4176 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4177 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4178 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004179 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004180 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4181 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004182
Dominik Laskowskic2867142019-01-21 11:33:38 -08004183 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004184
Dominik Laskowski46470112019-08-02 13:13:11 -07004185 const auto it = dumpers.find(flag);
4186 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004187 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004188 } else if (!asProto) {
4189 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004190 }
4191
Mathias Agopian9795c422009-08-26 16:36:26 -07004192 if (locked) {
4193 mStateLock.unlock();
4194 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004195
Dominik Laskowski46470112019-08-02 13:13:11 -07004196 if (it == dumpers.end()) {
4197 const LayersProto layersProto = dumpProtoFromMainThread();
4198 if (asProto) {
4199 result.append(layersProto.SerializeAsString());
4200 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004201 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004202 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4203 result.append(LayerProtoParser::layerTreeToString(layerTree));
4204 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004205 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004206 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004207 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004208 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004209 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004210 return NO_ERROR;
4211}
4212
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004213status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4214 if (asProto && mTracing.isEnabled()) {
4215 mTracing.writeToFileAsync();
4216 }
4217
4218 return doDump(fd, DumpArgs(), asProto);
4219}
4220
Dominik Laskowskic2867142019-01-21 11:33:38 -08004221void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004222 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004223 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004224}
4225
Dominik Laskowskic2867142019-01-21 11:33:38 -08004226void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004227 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004228
Dominik Laskowskic2867142019-01-21 11:33:38 -08004229 if (args.size() > 1) {
4230 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004231 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004232 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004233 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004234 }
Robert Carr2047fae2016-11-28 14:09:09 -08004235 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004236 } else {
4237 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004238 }
4239}
4240
Dominik Laskowskic2867142019-01-21 11:33:38 -08004241void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004242 const bool clearAll = args.size() < 2;
4243 const auto name = clearAll ? String8() : String8(args[1]);
4244
Edgar Arriaga844fa672020-01-16 14:21:42 -08004245 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004246 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004247 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004248 }
Robert Carr2047fae2016-11-28 14:09:09 -08004249 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004250
Svetoslavd85084b2014-03-20 10:28:31 -07004251 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004252}
4253
Dominik Laskowskic2867142019-01-21 11:33:38 -08004254void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4255 mTimeStats->parseArgs(asProto, args, result);
4256}
4257
Jamie Gennis6547ff42013-07-16 20:12:42 -07004258// This should only be called from the main thread. Otherwise it would need
4259// the lock and should use mCurrentState rather than mDrawingState.
4260void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004261 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004262 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004263 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004264
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004265 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004266}
4267
Yiwei Zhang5434a782018-12-05 18:06:32 -08004268void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004269 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004270
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004271 if (isLayerTripleBufferingDisabled())
4272 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004273
Yiwei Zhang5434a782018-12-05 18:06:32 -08004274 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4275 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4276 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4277 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4278 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4279 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004280 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004281}
4282
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004283void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004284 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004285
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004286 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004287 result.append("\n");
4288
Ady Abraham9e16a482019-12-03 17:19:41 -08004289 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004290 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004291 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004292 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004293
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004294 HwcConfigIndexType defaultConfig;
4295 float minFps, maxFps;
4296 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004297 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004298 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004299 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004300 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004301 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4302 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004303
Ana Krulecc2870422019-01-29 19:00:58 -08004304 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004305}
4306
Yiwei Zhang5434a782018-12-05 18:06:32 -08004307void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4308 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004309 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4310 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004311 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004312 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004314 }
David Sodman4a36e932017-11-07 14:29:47 -08004315 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004316 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004317 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4319 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004320}
4321
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004322void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4323 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004324 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4325 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004326 for (const auto& segment : history) {
4327 if (!segment.usedThirdBuffer) {
4328 stats.twoBufferTime += segment.totalTime;
4329 }
4330 if (segment.occupancyAverage < 1.0f) {
4331 stats.doubleBufferedTime += segment.totalTime;
4332 } else if (segment.occupancyAverage < 2.0f) {
4333 stats.tripleBufferedTime += segment.totalTime;
4334 }
4335 ++stats.numSegments;
4336 stats.totalTime += segment.totalTime;
4337 }
4338}
4339
Yiwei Zhang5434a782018-12-05 18:06:32 -08004340void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4341 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004342
4343 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4344 const size_t count = currentLayers.size();
4345 for (size_t i=0 ; i<count ; i++) {
4346 currentLayers[i]->dumpFrameEvents(result);
4347 }
4348}
4349
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004351 result.append("Buffering stats:\n");
4352 result.append(" [Layer name] <Active time> <Two buffer> "
4353 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004354 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004355 typedef std::tuple<std::string, float, float, float> BufferTuple;
4356 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004357 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004358 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004359 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004360 if (stats.numSegments == 0) {
4361 continue;
4362 }
4363 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4364 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4365 stats.totalTime;
4366 float doubleBufferRatio = static_cast<float>(
4367 stats.doubleBufferedTime) / stats.totalTime;
4368 float tripleBufferRatio = static_cast<float>(
4369 stats.tripleBufferedTime) / stats.totalTime;
4370 sorted.insert({activeTime, {name, twoBufferRatio,
4371 doubleBufferRatio, tripleBufferRatio}});
4372 }
4373 for (const auto& sortedPair : sorted) {
4374 float activeTime = sortedPair.first;
4375 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4377 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004378 }
4379 result.append("\n");
4380}
4381
Yiwei Zhang5434a782018-12-05 18:06:32 -08004382void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004383 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004384 const auto displayId = display->getId();
4385 if (!displayId) {
4386 continue;
4387 }
4388 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004389 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004390 continue;
4391 }
4392
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393 StringAppendF(&result,
4394 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4395 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004396 uint8_t port;
4397 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004399 result.append("no identification data\n");
4400 continue;
4401 }
4402
4403 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004404 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004405 continue;
4406 }
4407
4408 const auto edid = parseEdid(data);
4409 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004410 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004411 continue;
4412 }
4413
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004415 result.append(edid->displayName.data(), edid->displayName.length());
4416 result.append("\"\n");
4417 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004418}
4419
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004420void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4421 std::string& result) const {
4422 hwc2_display_t hwcDisplayId;
4423 uint8_t port;
4424 DisplayIdentificationData data;
4425
4426 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4427 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4428 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4429 }
4430}
4431
Yiwei Zhang5434a782018-12-05 18:06:32 -08004432void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004433 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004434 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4435 StringAppendF(&result, "DisplayColorSetting: %s\n",
4436 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004437
4438 // TODO: print out if wide-color mode is active or not
4439
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004440 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004441 const auto displayId = display->getId();
4442 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004443 continue;
4444 }
4445
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004447 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004448 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004449 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004450 }
4451
Lloyd Pique32cbe282018-10-19 13:09:22 -07004452 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, " Current color mode: %s (%d)\n",
4454 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004455 }
4456 result.append("\n");
4457}
4458
Vishnu Nair8406fd72019-07-30 11:29:31 -07004459LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004460 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004461 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4462 layer->writeToProto(layersProto, traceFlags);
4463 }
chaviw1d044282017-09-27 12:19:28 -07004464 return layersProto;
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
chaviw6d89e2d2020-01-14 14:42:01 -08004481 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004482 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004483 }
4484}
4485
Vishnu Nair8406fd72019-07-30 11:29:31 -07004486LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4487 LayersProto layersProto;
4488 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4489 return layersProto;
4490}
4491
Vishnu Nair0f085c62019-08-30 08:49:12 -07004492void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4493 result.append("Offscreen Layers:\n");
4494 postMessageSync(new LambdaMessage([&]() {
4495 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004496 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004497 layer->dumpCallingUidPid(result);
4498 });
4499 }
4500 }));
4501}
4502
Dominik Laskowskic2867142019-01-21 11:33:38 -08004503void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4504 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004505 Colorizer colorizer(colorize);
4506
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004507 // figure out if we're stuck somewhere
4508 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004510 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4511
4512 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004513 * Dump library configuration.
4514 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004515
4516 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004517 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004518 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004519 appendSfConfigString(result);
4520 appendUiConfigString(result);
4521 appendGuiConfigString(result);
4522 result.append("\n");
4523
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004524 result.append("\nDisplay identification data:\n");
4525 dumpDisplayIdentificationData(result);
4526
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004527 result.append("\nWide-Color information:\n");
4528 dumpWideColorInfo(result);
4529
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004530 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004531 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004532 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004533 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004534 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004535
Andy McFadden41d67d72014-04-25 16:58:34 -07004536 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004537 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004538 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004539 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004540 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004541
Dan Stozab90cf072015-03-05 11:05:59 -08004542 dumpStaticScreenStats(result);
4543 result.append("\n");
4544
Alec Mouri40189b02019-03-05 15:07:54 -08004545 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4546 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4547 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004548
Dan Stozae77c7662016-05-13 11:37:28 -07004549 dumpBufferingStats(result);
4550
Andy McFadden4803b742012-09-24 19:07:20 -07004551 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004552 * Dump the visible layer list
4553 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004555 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4557 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004558 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004559
Chia-I Wu2f884132018-09-13 15:17:58 -07004560 {
Lloyd Pique207def92019-02-28 16:09:52 -08004561 StringAppendF(&result, "Composition layers\n");
4562 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004563 auto* compositionState = layer->getCompositionState();
4564 if (!compositionState) return;
4565
4566 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4567 layer->getDebugName() ? layer->getDebugName()
4568 : "<unknown>");
4569 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004570 });
4571 }
4572
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004573 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004574 * Dump Display state
4575 */
4576
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004577 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004579 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004580 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004581 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004582 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004583 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004584
4585 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004586 * Dump CompositionEngine state
4587 */
4588
4589 mCompositionEngine->dump(result);
4590
4591 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004592 * Dump SurfaceFlinger global state
4593 */
4594
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004596 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004597 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004598
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004599 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004600
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004601 DebugEGLImageTracker::getInstance()->dump(result);
4602
Dominik Laskowski075d3172018-05-24 15:50:06 -07004603 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004604 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4605 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004606 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4607 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004608 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result,
4610 " transaction-flags : %08x\n"
4611 " gpu_to_cpu_unsupported : %d\n",
4612 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004613
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004614 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004615 displayId && getHwComposer().isConnected(*displayId)) {
4616 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result,
4618 " refresh-rate : %f fps\n"
4619 " x-dpi : %f\n"
4620 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004621 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4622 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004623 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004624
Yiwei Zhang5434a782018-12-05 18:06:32 -08004625 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626
Dan Stozae22aec72016-08-01 13:20:59 -07004627 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004628 * Tracing state
4629 */
4630 mTracing.dump(result);
4631 result.append("\n");
4632
4633 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004634 * HWC layer minidump
4635 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004636 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004637 const auto displayId = display->getId();
4638 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004639 continue;
4640 }
4641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004643 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004644 const sp<DisplayDevice> displayDevice = display;
4645 mCurrentState.traverseInZOrder(
4646 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004647 result.append("\n");
4648 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004649
4650 /*
4651 * Dump HWComposer state
4652 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004653 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004654 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004656 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004658 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004659
4660 /*
4661 * Dump gralloc state
4662 */
4663 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4664 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004665
4666 /*
4667 * Dump VrFlinger state if in use.
4668 */
4669 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4670 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004672 result.append("\n");
4673 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004674
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004675 result.append(mTimeStats->miniDump());
4676 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677}
4678
Chia-I Wu28f320b2018-05-03 11:02:56 -07004679void SurfaceFlinger::updateColorMatrixLocked() {
4680 mat4 colorMatrix;
4681 if (mGlobalSaturationFactor != 1.0f) {
4682 // Rec.709 luma coefficients
4683 float3 luminance{0.213f, 0.715f, 0.072f};
4684 luminance *= 1.0f - mGlobalSaturationFactor;
4685 mat4 saturationMatrix = mat4(
4686 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4687 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4688 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4689 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4690 );
4691 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4692 } else {
4693 colorMatrix = mClientColorMatrix * mDaltonizer();
4694 }
4695
4696 if (mCurrentState.colorMatrix != colorMatrix) {
4697 mCurrentState.colorMatrix = colorMatrix;
4698 mCurrentState.colorMatrixChanged = true;
4699 setTransactionFlags(eTransactionNeeded);
4700 }
4701}
4702
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004703status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704#pragma clang diagnostic push
4705#pragma clang diagnostic error "-Wswitch-enum"
4706 switch (static_cast<ISurfaceComposerTag>(code)) {
4707 // These methods should at minimum make sure that the client requested
4708 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004709 case BOOT_FINISHED:
4710 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004711 case CREATE_DISPLAY:
4712 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004713 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004714 case GET_ANIMATION_FRAME_STATS:
4715 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004716 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004717 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004718 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004719 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4720 case SET_AUTO_LOW_LATENCY_MODE:
4721 case GET_GAME_CONTENT_TYPE_SUPPORT:
4722 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004723 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004724 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004725 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004726 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004727 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004728 case NOTIFY_POWER_HINT:
4729 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004730 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4731 IPCThreadState* ipc = IPCThreadState::self();
4732 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4733 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004734 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004735 }
Robert Carr1db73f62016-12-21 12:58:51 -08004736 return OK;
4737 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004738 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004739 IPCThreadState* ipc = IPCThreadState::self();
4740 const int pid = ipc->getCallingPid();
4741 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004742 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4743 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004744 return PERMISSION_DENIED;
4745 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004746 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004747 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004748 // Used by apps to hook Choreographer to SurfaceFlinger.
4749 case CREATE_DISPLAY_EVENT_CONNECTION:
4750 // The following calls are currently used by clients that do not
4751 // request necessary permissions. However, they do not expose any secret
4752 // information, so it is OK to pass them.
4753 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004754 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004756 case GET_PHYSICAL_DISPLAY_IDS:
4757 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004758 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004759 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004760 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004761 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004762 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004763 case GET_DISPLAY_STATS:
4764 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4765 // Calling setTransactionState is safe, because you need to have been
4766 // granted a reference to Client* and Handle* to do anything with it.
4767 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004768 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004769 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004770 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004771 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004772 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004773 // setFrameRate() is deliberately available for apps to call without any
4774 // special permissions.
4775 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004776 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4777 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778 return OK;
4779 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004780 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004781 case CAPTURE_SCREEN:
4782 case ADD_REGION_SAMPLING_LISTENER:
4783 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004784 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004785 IPCThreadState* ipc = IPCThreadState::self();
4786 const int pid = ipc->getCallingPid();
4787 const int uid = ipc->getCallingUid();
4788 if ((uid != AID_GRAPHICS) &&
4789 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4790 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4791 return PERMISSION_DENIED;
4792 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004793 return OK;
4794 }
chaviw93df2ea2019-04-30 16:45:12 -07004795 case CAPTURE_SCREEN_BY_ID: {
4796 IPCThreadState* ipc = IPCThreadState::self();
4797 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004798 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004799 return OK;
4800 }
4801 return PERMISSION_DENIED;
4802 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004803 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004804
4805 // These codes are used for the IBinder protocol to either interrogate the recipient
4806 // side of the transaction for its canonical interface descriptor or to dump its state.
4807 // We let them pass by default.
4808 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4809 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4810 code == IBinder::SYSPROPS_TRANSACTION) {
4811 return OK;
4812 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004813 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004814 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004815 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004816 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4817 return OK;
4818 }
4819 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4820 return PERMISSION_DENIED;
4821#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004822}
4823
Ana Krulec13be8ad2018-08-21 02:43:56 +00004824status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4825 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004826 status_t credentialCheck = CheckTransactCodeCredentials(code);
4827 if (credentialCheck != OK) {
4828 return credentialCheck;
4829 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004830
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004831 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4832 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004833 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004834 IPCThreadState* ipc = IPCThreadState::self();
4835 const int uid = ipc->getCallingUid();
4836 if (CC_UNLIKELY(uid != AID_SYSTEM
4837 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004838 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004839 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004840 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004841 return PERMISSION_DENIED;
4842 }
4843 int n;
4844 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004845 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004846 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004847 return NO_ERROR;
4848 case 1002: // SHOW_UPDATES
4849 n = data.readInt32();
4850 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004851 invalidateHwcGeometry();
4852 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004854 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004855 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004856 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004857 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004858 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004859 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004860 setTransactionFlags(
4861 eTransactionNeeded|
4862 eDisplayTransactionNeeded|
4863 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004864 return NO_ERROR;
4865 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004866 case 1006:{ // send empty update
4867 signalRefresh();
4868 return NO_ERROR;
4869 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004870 case 1008: // toggle use of hw composer
4871 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004872 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004873 invalidateHwcGeometry();
4874 repaintEverything();
4875 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004876 case 1009: // toggle use of transform hint
4877 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004878 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004879 invalidateHwcGeometry();
4880 repaintEverything();
4881 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004882 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004883 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 reply->writeInt32(0);
4885 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004886 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004887 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 return NO_ERROR;
4889 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004890 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004891 if (!display) {
4892 return NAME_NOT_FOUND;
4893 }
4894
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004895 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004896 return NO_ERROR;
4897 }
4898 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004899 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004900 // daltonize
4901 n = data.readInt32();
4902 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004903 case 1:
4904 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4905 break;
4906 case 2:
4907 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4908 break;
4909 case 3:
4910 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4911 break;
4912 default:
4913 mDaltonizer.setType(ColorBlindnessType::None);
4914 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004915 }
4916 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004917 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004918 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004919 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004920 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004921
4922 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004923 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004925 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004926 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004927 // apply a color matrix
4928 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004929 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004930 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004931 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004932 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004933 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004934 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004935 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004936 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004937 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004938 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004939
4940 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4941 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004942 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004943 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4944 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4945 }
4946
Chia-I Wu28f320b2018-05-03 11:02:56 -07004947 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004948 return NO_ERROR;
4949 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004950 case 1016: { // Unused.
4951 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004952 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004953 case 1017: {
4954 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004955 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004956 return NO_ERROR;
4957 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004958 case 1018: { // Modify Choreographer's phase offset
4959 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004960 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004961 return NO_ERROR;
4962 }
4963 case 1019: { // Modify SurfaceFlinger's phase offset
4964 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004965 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004966 return NO_ERROR;
4967 }
Irvel468051e2016-06-13 16:44:44 -07004968 case 1020: { // Layer updates interceptor
4969 n = data.readInt32();
4970 if (n) {
4971 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004972 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004973 }
4974 else{
4975 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004976 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004977 }
4978 return NO_ERROR;
4979 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004980 case 1021: { // Disable HWC virtual displays
4981 n = data.readInt32();
4982 mUseHwcVirtualDisplays = !n;
4983 return NO_ERROR;
4984 }
Romain Guy0147a172017-06-01 13:53:56 -07004985 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004986 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004987 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004988
Chia-I Wu28f320b2018-05-03 11:02:56 -07004989 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004990 return NO_ERROR;
4991 }
Romain Guy54f154a2017-10-24 21:40:32 +01004992 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004993 int32_t colorMode;
4994
Chia-I Wu0d711262018-05-21 15:19:35 -07004995 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004996 if (data.readInt32(&colorMode) == NO_ERROR) {
4997 mForceColorMode = static_cast<ColorMode>(colorMode);
4998 }
Romain Guy54f154a2017-10-24 21:40:32 +01004999 invalidateHwcGeometry();
5000 repaintEverything();
5001 return NO_ERROR;
5002 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005003 // Deprecate, use 1030 to check whether the device is color managed.
5004 case 1024: {
5005 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005006 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005007 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005008 n = data.readInt32();
5009 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005010 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005011 Mutex::Autolock lock(mStateLock);
5012 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005013 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005014 reply->writeInt32(NO_ERROR);
5015 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005016 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005017 bool writeFile = false;
5018 {
5019 Mutex::Autolock lock(mStateLock);
5020 mTracingEnabledChanged = true;
5021 writeFile = mTracing.disable();
5022 }
5023
5024 if (writeFile) {
5025 reply->writeInt32(mTracing.writeToFile());
5026 } else {
5027 reply->writeInt32(NO_ERROR);
5028 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005029 }
5030 return NO_ERROR;
5031 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005032 case 1026: { // Get layer tracing status
5033 reply->writeBool(mTracing.isEnabled());
5034 return NO_ERROR;
5035 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005036 // Is a DisplayColorSetting supported?
5037 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005038 const auto display = getDefaultDisplayDevice();
5039 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005040 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005041 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005042
5043 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5044 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005045 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005046 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005047 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005048 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005049 reply->writeBool(true);
5050 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005051 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005052 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005053 break;
5054 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005055 reply->writeBool(
5056 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005057 break;
5058 }
5059 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005060 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005061 // Is VrFlinger active?
5062 case 1028: {
5063 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005064 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005065 return NO_ERROR;
5066 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005067 // Set buffer size for SF tracing (value in KB)
5068 case 1029: {
5069 n = data.readInt32();
5070 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5071 ALOGW("Invalid buffer size: %d KB", n);
5072 reply->writeInt32(BAD_VALUE);
5073 return BAD_VALUE;
5074 }
5075
5076 ALOGD("Updating trace buffer to %d KB", n);
5077 mTracing.setBufferSize(n * 1024);
5078 reply->writeInt32(NO_ERROR);
5079 return NO_ERROR;
5080 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005081 // Is device color managed?
5082 case 1030: {
5083 reply->writeBool(useColorManagement);
5084 return NO_ERROR;
5085 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005086 // Override default composition data space
5087 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5088 // && adb shell stop zygote && adb shell start zygote
5089 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5090 // adb shell stop zygote && adb shell start zygote
5091 case 1031: {
5092 Mutex::Autolock _l(mStateLock);
5093 n = data.readInt32();
5094 if (n) {
5095 n = data.readInt32();
5096 if (n) {
5097 Dataspace dataspace = static_cast<Dataspace>(n);
5098 if (!validateCompositionDataspace(dataspace)) {
5099 return BAD_VALUE;
5100 }
5101 mDefaultCompositionDataspace = dataspace;
5102 }
5103 n = data.readInt32();
5104 if (n) {
5105 Dataspace dataspace = static_cast<Dataspace>(n);
5106 if (!validateCompositionDataspace(dataspace)) {
5107 return BAD_VALUE;
5108 }
5109 mWideColorGamutCompositionDataspace = dataspace;
5110 }
5111 } else {
5112 // restore composition data space.
5113 mDefaultCompositionDataspace = defaultCompositionDataspace;
5114 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5115 }
5116 return NO_ERROR;
5117 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005118 // Set trace flags
5119 case 1033: {
5120 n = data.readUint32();
5121 ALOGD("Updating trace flags to 0x%x", n);
5122 mTracing.setTraceFlags(n);
5123 reply->writeInt32(NO_ERROR);
5124 return NO_ERROR;
5125 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005126 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005127 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005128 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005129 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005130 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5131 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005132 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005133 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005134 } else {
5135 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005136 }
5137 return NO_ERROR;
5138 }
Ady Abraham34392f72019-04-10 11:29:27 -07005139 case 1035: {
5140 n = data.readInt32();
5141 mDebugDisplayConfigSetByBackdoor = false;
5142 if (n >= 0) {
5143 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005144 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005145 if (result != NO_ERROR) {
5146 return result;
5147 }
5148 mDebugDisplayConfigSetByBackdoor = true;
5149 }
5150 return NO_ERROR;
5151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 }
5153 }
5154 return err;
5155}
5156
Steven Thomas6d8110b2017-08-31 18:24:21 -07005157void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005158 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005159 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005160}
5161
Ana Krulec7d1d6832018-12-27 11:10:09 -08005162void SurfaceFlinger::repaintEverythingForHWC() {
5163 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005164 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005165 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005166}
5167
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005168// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5169class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005170public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005171 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5172 ~WindowDisconnector() {
5173 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005174 }
5175
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005176private:
5177 ANativeWindow* mWindow;
5178 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005179};
5180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005181status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005182 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005183 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5184 const Rect& sourceCrop, uint32_t reqWidth,
5185 uint32_t reqHeight, bool useIdentityTransform,
5186 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005187 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005188
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005189 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005190
Dominik Laskowski718f9602019-11-09 20:01:35 -08005191 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5192 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5193 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5194 renderAreaRotation = ui::Transform::ROT_0;
5195 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005196
Chia-I Wu20261cb2018-08-23 12:55:44 -07005197 sp<DisplayDevice> display;
5198 {
5199 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005200
Chia-I Wu20261cb2018-08-23 12:55:44 -07005201 display = getDisplayDeviceLocked(displayToken);
5202 if (!display) return BAD_VALUE;
5203
Chia-I Wucb023152018-08-28 12:57:23 -07005204 // set the requested width/height to the logical display viewport size
5205 // by default
5206 if (reqWidth == 0 || reqHeight == 0) {
5207 reqWidth = uint32_t(display->getViewport().width());
5208 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005209 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005210 }
5211
Peiyong Lin0e003c92018-09-17 11:09:51 -07005212 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005213 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005214
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005215 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5216 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005217 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005218 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005219}
5220
chaviw93df2ea2019-04-30 16:45:12 -07005221static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5222 switch (colorMode) {
5223 case ColorMode::DISPLAY_P3:
5224 case ColorMode::BT2100_PQ:
5225 case ColorMode::BT2100_HLG:
5226 case ColorMode::DISPLAY_BT2020:
5227 return Dataspace::DISPLAY_P3;
5228 default:
5229 return Dataspace::V0_SRGB;
5230 }
5231}
5232
5233const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5234 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5235 if (displayToken) {
5236 return getDisplayDeviceLocked(displayToken);
5237 }
5238 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5239 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005240 return getDisplayByLayerStack(displayOrLayerStack);
5241}
5242
5243const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005244 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005245 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005246 return display;
5247 }
5248 }
5249 return nullptr;
5250}
5251
5252status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5253 sp<GraphicBuffer>* outBuffer) {
5254 sp<DisplayDevice> display;
5255 uint32_t width;
5256 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005257 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005258 {
5259 Mutex::Autolock _l(mStateLock);
5260 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5261 if (!display) {
5262 return BAD_VALUE;
5263 }
5264
5265 width = uint32_t(display->getViewport().width());
5266 height = uint32_t(display->getViewport().height());
5267
Dominik Laskowski718f9602019-11-09 20:01:35 -08005268 const auto orientation = display->getOrientation();
5269 captureOrientation = ui::Transform::toRotationFlags(orientation);
5270
5271 switch (captureOrientation) {
5272 case ui::Transform::ROT_90:
5273 captureOrientation = ui::Transform::ROT_270;
5274 break;
5275
5276 case ui::Transform::ROT_270:
5277 captureOrientation = ui::Transform::ROT_90;
5278 break;
5279
5280 case ui::Transform::ROT_INVALID:
5281 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5282 captureOrientation = ui::Transform::ROT_0;
5283 break;
5284
5285 default:
5286 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005287 }
chaviw93df2ea2019-04-30 16:45:12 -07005288 *outDataspace =
5289 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5290 }
5291
5292 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5293 false /* captureSecureLayers */);
5294
5295 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5296 std::placeholders::_1);
5297 bool ignored = false;
5298 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5299 false /* useIdentityTransform */,
5300 ignored /* outCapturedSecureLayers */);
5301}
5302
Robert Carr866455f2019-04-02 16:28:26 -07005303status_t SurfaceFlinger::captureLayers(
5304 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5305 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5306 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5307 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005308 ATRACE_CALL();
5309
5310 class LayerRenderArea : public RenderArea {
5311 public:
Robert Carr578038f2018-03-09 12:25:24 -08005312 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005313 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005314 bool childrenOnly, const Rect& displayViewport)
5315 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005316 mLayer(layer),
5317 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005318 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005319 mFlinger(flinger),
5320 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005321 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005322 Rect getBounds() const override {
5323 const Layer::State& layerState(mLayer->getDrawingState());
5324 return mLayer->getBufferSize(layerState);
5325 }
Marissa Wall61c58622018-07-18 10:12:20 -07005326 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005327 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005328 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005329 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005330 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005331 }
chaviwa76b2712017-09-20 12:02:26 -07005332 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005333 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005334 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005335 Rect getSourceCrop() const override {
5336 if (mCrop.isEmpty()) {
5337 return getBounds();
5338 } else {
5339 return mCrop;
5340 }
5341 }
Robert Carr578038f2018-03-09 12:25:24 -08005342 class ReparentForDrawing {
5343 public:
5344 const sp<Layer>& oldParent;
5345 const sp<Layer>& newParent;
5346
Vishnu Nair4351ad52019-02-11 14:13:02 -08005347 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5348 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005349 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005350 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005351 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5352 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005353 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005354 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005355 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005356 };
5357
5358 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005359 const Rect sourceCrop = getSourceCrop();
5360 // no need to check rotation because there is none
5361 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5362 sourceCrop.height() != getReqHeight();
5363
Robert Carr578038f2018-03-09 12:25:24 -08005364 if (!mChildrenOnly) {
5365 mTransform = mLayer->getTransform().inverse();
5366 drawLayers();
5367 } else {
5368 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005369 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5370 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005371 // In the "childrenOnly" case we reparent the children to a screenshot
5372 // layer which has no properties set and which does not draw.
5373 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005374 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5375 "Screenshot Parent"s, w, h, 0,
5376 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005377
Vishnu Nair4351ad52019-02-11 14:13:02 -08005378 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005379 drawLayers();
5380 }
5381 }
chaviwa76b2712017-09-20 12:02:26 -07005382
chaviwa76b2712017-09-20 12:02:26 -07005383 private:
chaviw7206d492017-11-10 16:16:12 -08005384 const sp<Layer> mLayer;
5385 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005386
Peiyong Linefefaac2018-08-17 12:27:51 -07005387 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005388 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005389
5390 SurfaceFlinger* mFlinger;
5391 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005392 };
5393
Robert Carrc0df3122019-04-11 13:18:21 -07005394 int reqWidth = 0;
5395 int reqHeight = 0;
5396 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005397 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005398 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005399 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005400 {
5401 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005402
Robert Carrc0df3122019-04-11 13:18:21 -07005403 parent = fromHandle(layerHandleBinder);
5404 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5405 ALOGE("captureLayers called with an invalid or removed parent");
5406 return NAME_NOT_FOUND;
5407 }
5408
5409 const int uid = IPCThreadState::self()->getCallingUid();
5410 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5411 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5412 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5413 return PERMISSION_DENIED;
5414 }
5415
Vishnu Nairefc42e22019-12-03 17:36:12 -08005416 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005417 if (sourceCrop.width() <= 0) {
5418 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005419 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005420 }
5421
5422 if (sourceCrop.height() <= 0) {
5423 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005424 crop.bottom = parentSourceBounds.getHeight();
5425 }
5426
5427 if (crop.isEmpty() || frameScale <= 0.0f) {
5428 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5429 // crop was not specified, or an invalid frame scale was provided.
5430 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005431 }
5432 reqWidth = crop.width() * frameScale;
5433 reqHeight = crop.height() * frameScale;
5434
5435 for (const auto& handle : excludeHandles) {
5436 sp<Layer> excludeLayer = fromHandle(handle);
5437 if (excludeLayer != nullptr) {
5438 excludeLayers.emplace(excludeLayer);
5439 } else {
5440 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5441 return NAME_NOT_FOUND;
5442 }
5443 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005444
5445 auto display = getDisplayByLayerStack(parent->getLayerStack());
5446 if (!display) {
5447 return BAD_VALUE;
5448 }
5449
5450 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005451 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005452
Chia-I Wu20261cb2018-08-23 12:55:44 -07005453 // really small crop or frameScale
5454 if (reqWidth <= 0) {
5455 reqWidth = 1;
5456 }
5457 if (reqHeight <= 0) {
5458 reqHeight = 1;
5459 }
5460
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005461 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5462 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005463 auto traverseLayers = [parent, childrenOnly,
5464 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005465 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5466 if (!layer->isVisible()) {
5467 return;
Robert Carr578038f2018-03-09 12:25:24 -08005468 } else if (childrenOnly && layer == parent.get()) {
5469 return;
chaviwa76b2712017-09-20 12:02:26 -07005470 }
Robert Carr866455f2019-04-02 16:28:26 -07005471
5472 sp<Layer> p = layer;
5473 while (p != nullptr) {
5474 if (excludeLayers.count(p) != 0) {
5475 return;
5476 }
5477 p = p->getParent();
5478 }
5479
chaviwa76b2712017-09-20 12:02:26 -07005480 visitor(layer);
5481 });
5482 };
Robert Carr108b2c72019-04-02 16:32:58 -07005483
5484 bool outCapturedSecureLayers = false;
5485 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5486 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005487}
5488
5489status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5490 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005491 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005492 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005493 bool useIdentityTransform,
5494 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005495 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005496
Peiyong Lin0e003c92018-09-17 11:09:51 -07005497 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005498 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5499 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005500 *outBuffer =
5501 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5502 static_cast<android_pixel_format>(reqPixelFormat), 1,
5503 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504
Robert Carr108b2c72019-04-02 16:32:58 -07005505 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5506 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005507}
5508
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005509status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5510 TraverseLayersFunction traverseLayers,
5511 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005512 bool useIdentityTransform,
5513 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005514 // This mutex protects syncFd and captureResult for communication of the return values from the
5515 // main thread back to this Binder thread
5516 std::mutex captureMutex;
5517 std::condition_variable captureCondition;
5518 std::unique_lock<std::mutex> captureLock(captureMutex);
5519 int syncFd = -1;
5520 std::optional<status_t> captureResult;
5521
Robert Carr03480e22018-01-04 16:02:06 -08005522 const int uid = IPCThreadState::self()->getCallingUid();
5523 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5524
Dominik Laskowski8c001672018-05-30 16:52:06 -07005525 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526 // If there is a refresh pending, bug out early and tell the binder thread to try again
5527 // after the refresh.
5528 if (mRefreshPending) {
5529 ATRACE_NAME("Skipping screenshot for now");
5530 std::unique_lock<std::mutex> captureLock(captureMutex);
5531 captureResult = std::make_optional<status_t>(EAGAIN);
5532 captureCondition.notify_one();
5533 return;
5534 }
5535
5536 status_t result = NO_ERROR;
5537 int fd = -1;
5538 {
5539 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005540 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005541 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005542 useIdentityTransform, forSystem, &fd,
5543 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005544 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005545 }
5546
5547 {
5548 std::unique_lock<std::mutex> captureLock(captureMutex);
5549 syncFd = fd;
5550 captureResult = std::make_optional<status_t>(result);
5551 captureCondition.notify_one();
5552 }
5553 });
5554
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005555 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005556 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005557 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005558 while (*captureResult == EAGAIN) {
5559 captureResult.reset();
5560 result = postMessageAsync(message);
5561 if (result != NO_ERROR) {
5562 return result;
5563 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005564 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005565 }
5566 result = *captureResult;
5567 }
5568
5569 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005570 sync_wait(syncFd, -1);
5571 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005572 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005573
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005574 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005575}
5576
chaviwa76b2712017-09-20 12:02:26 -07005577void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005578 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005579 const sp<GraphicBuffer>& buffer,
5580 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005581 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005582
chaviwa76b2712017-09-20 12:02:26 -07005583 const auto reqWidth = renderArea.getReqWidth();
5584 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005585 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005586 const auto transform = renderArea.getTransform();
5587 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005588 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005589
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005590 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005591 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005592
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005593 // assume that bounds are never offset, and that they are the same as the
5594 // buffer bounds.
5595 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005596 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005597 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005598
5599 // Now take into account the rotation flag. We append a transform that
5600 // rotates the layer stack about the origin, then translate by buffer
5601 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005602 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005603 int displacementX = 0;
5604 int displacementY = 0;
5605 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5606 switch (rotation) {
5607 case ui::Transform::ROT_90:
5608 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005609 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005610 break;
5611 case ui::Transform::ROT_180:
5612 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005613 displacementY = renderArea.getBounds().getWidth();
5614 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005615 break;
5616 case ui::Transform::ROT_270:
5617 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005618 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005619 break;
5620 default:
5621 break;
5622 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005623
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005624 // We need to transform the clipping window into the right spot.
5625 // First, rotate the clipping rectangle by the rotation hint to get the
5626 // right orientation
5627 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5628 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5629 const vec4 rotClipTL = rotMatrix * clipTL;
5630 const vec4 rotClipBR = rotMatrix * clipBR;
5631 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5632 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5633 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5634 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5635
5636 // Now reposition the clipping rectangle with the displacement vector
5637 // computed above.
5638 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005639 clientCompositionDisplay.clip =
5640 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5641 newClipRight + displacementX, newClipBottom + displacementY);
5642
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005643 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005644 clientCompositionDisplay.globalTransform =
5645 clipTransform * clientCompositionDisplay.globalTransform;
5646
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005647 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5648 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005649
chaviw50da5042018-04-09 13:49:37 -07005650 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005651
Vishnu Nair9b079a22020-01-21 14:36:08 -08005652 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005653 fillLayer.source.buffer.buffer = nullptr;
5654 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5655 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5656 fillLayer.alpha = half(alpha);
5657 clientCompositionLayers.push_back(fillLayer);
5658
5659 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005660 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005661 const bool supportProtectedContent = false;
5662 Region clip(renderArea.getBounds());
5663 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5664 clip,
5665 useIdentityTransform,
5666 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5667 renderArea.isSecure(),
5668 supportProtectedContent,
5669 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005670 displayViewport,
5671 clientCompositionDisplay.outputDataspace,
5672 true, /* realContentIsVisible */
5673 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005674 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005675 std::vector<compositionengine::LayerFE::LayerSettings> results =
5676 layer->prepareClientCompositionList(targetSettings);
5677 clientCompositionLayers.insert(clientCompositionLayers.end(),
5678 std::make_move_iterator(results.begin()),
5679 std::make_move_iterator(results.end()));
5680 results.clear();
5681
chaviwa76b2712017-09-20 12:02:26 -07005682 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005683
Vishnu Nair9b079a22020-01-21 14:36:08 -08005684 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5685 clientCompositionLayers.reserve(clientCompositionLayers.size());
5686 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5687 std::back_inserter(clientCompositionLayerPointers),
5688 [](compositionengine::LayerFE::LayerSettings& settings)
5689 -> renderengine::LayerSettings* { return &settings; });
5690
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005691 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005692 // Use an empty fence for the buffer fence, since we just created the buffer so
5693 // there is no need for synchronization with the GPU.
5694 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005696 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005697 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005698 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699
5700 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005701}
5702
chaviwa76b2712017-09-20 12:02:26 -07005703status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5704 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005705 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005706 bool useIdentityTransform, bool forSystem,
5707 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005708 ATRACE_CALL();
5709
chaviwa76b2712017-09-20 12:02:26 -07005710 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005711 outCapturedSecureLayers =
5712 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005713 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005714
Robert Carr03480e22018-01-04 16:02:06 -08005715 // We allow the system server to take screenshots of secure layers for
5716 // use in situations like the Screen-rotation animation and place
5717 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005718 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005719 ALOGW("FB is protected: PERMISSION_DENIED");
5720 return PERMISSION_DENIED;
5721 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005722 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005723 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005724}
5725
chaviw95ef3c42019-02-14 10:55:09 -08005726void SurfaceFlinger::setInputWindowsFinished() {
5727 Mutex::Autolock _l(mStateLock);
5728
5729 mPendingSyncInputWindows = false;
5730 mTransactionCV.broadcast();
5731}
chaviw5f21a5e2019-02-14 10:00:34 -08005732
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005733// ---------------------------------------------------------------------------
5734
Edgar Arriaga844fa672020-01-16 14:21:42 -08005735void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5736 layersSortedByZ.traverse(visitor);
5737}
5738
Dan Stoza412903f2017-04-27 13:42:17 -07005739void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5740 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005741}
5742
Dan Stoza412903f2017-04-27 13:42:17 -07005743void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5744 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005745}
5746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005747void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005748 const LayerVector::Visitor& visitor) {
5749 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005750 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005751 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005752 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005753 continue;
5754 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005755 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005756 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005757 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005758 return;
5759 }
chaviwa76b2712017-09-20 12:02:26 -07005760 if (!layer->isVisible()) {
5761 return;
5762 }
5763 visitor(layer);
5764 });
5765 }
5766}
5767
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005768status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5769 HwcConfigIndexType defaultConfig,
5770 float minRefreshRate,
5771 float maxRefreshRate) {
5772 Mutex::Autolock lock(mStateLock);
5773
Dominik Laskowski22488f62019-03-28 09:53:04 -07005774 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005775 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5776 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5777 // it should go thru setDesiredActiveConfig, similar to primary display.
5778 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5779 const auto displayId = display->getId();
5780 LOG_ALWAYS_FATAL_IF(!displayId);
5781
5782 HWC2::VsyncPeriodChangeConstraints constraints;
5783 constraints.desiredTimeNanos = systemTime();
5784 constraints.seamlessRequired = false;
5785
5786 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005787 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5788 constraints, &timeline) < 0) {
5789 return BAD_VALUE;
5790 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005791 if (timeline.refreshRequired) {
5792 repaintEverythingForHWC();
5793 }
5794
Ady Abrahamdfa37362020-01-21 18:02:39 -08005795 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005796 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005797 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5798 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005799 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005800 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005801 }
5802
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005803 if (mDebugDisplayConfigSetByBackdoor) {
5804 // ignore this request as config is overridden by backdoor
5805 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005806 }
5807
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005808 bool policyChanged;
5809 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5810 &policyChanged) < 0) {
5811 return BAD_VALUE;
5812 }
5813 if (!policyChanged) {
5814 return NO_ERROR;
5815 }
5816
5817 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5818 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005819
5820 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5821 // that listeners that care about a change in allowed configs can get the notification.
5822 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005823 const nsecs_t vsyncPeriod =
5824 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005825 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005826 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005827
Ana Krulec3f6a2062020-01-23 15:48:01 -08005828 auto configId = mScheduler->getPreferredConfigId();
5829 auto preferredRefreshRate = configId
5830 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5831 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5832 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5833 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5834 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5835
5836 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5837 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5838 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005839 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005840 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005841 }
5842
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005843 return NO_ERROR;
5844}
5845
Ana Krulec0782b882019-10-15 17:34:54 -07005846status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005847 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005848 float maxRefreshRate) {
5849 ATRACE_CALL();
5850
5851 if (!displayToken) {
5852 return BAD_VALUE;
5853 }
5854
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005855 status_t result = NO_ERROR;
5856
Ana Krulec234bb162019-11-10 22:55:55 +01005857 postMessageSync(new LambdaMessage([&]() {
5858 const auto display = getDisplayDeviceLocked(displayToken);
5859 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005860 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005861 ALOGE("Attempt to set desired display configs for invalid display token %p",
5862 displayToken.get());
5863 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005864 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005865 ALOGW("Attempt to set desired display configs for virtual display");
5866 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005867 result =
5868 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5869 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005870 }
5871 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005872
5873 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005874}
5875
5876status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005877 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005878 float* outMinRefreshRate,
5879 float* outMaxRefreshRate) {
5880 ATRACE_CALL();
5881
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005882 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005883 return BAD_VALUE;
5884 }
5885
5886 Mutex::Autolock lock(mStateLock);
5887 const auto display = getDisplayDeviceLocked(displayToken);
5888 if (!display) {
5889 return NAME_NOT_FOUND;
5890 }
5891
5892 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005893 HwcConfigIndexType defaultConfig;
5894 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5895 *outDefaultConfig = defaultConfig.value();
5896 return NO_ERROR;
5897 } else if (display->isVirtual()) {
5898 return BAD_VALUE;
5899 } else {
5900 const auto displayId = display->getId();
5901 if (!displayId) {
5902 return BAD_VALUE;
5903 }
5904 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5905 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5906 *outMinRefreshRate = 1e9f / vsyncPeriod;
5907 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5908 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005909 }
Ana Krulec0782b882019-10-15 17:34:54 -07005910}
5911
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005912void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005913 mFlinger->setInputWindowsFinished();
5914}
5915
Robert Carrc0df3122019-04-11 13:18:21 -07005916sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005917 BBinder* b = nullptr;
5918 if (handle) {
5919 b = handle->localBinder();
5920 }
Robert Carrc0df3122019-04-11 13:18:21 -07005921 if (b == nullptr) {
5922 return nullptr;
5923 }
5924 auto it = mLayersByLocalBinderToken.find(b);
5925 if (it != mLayersByLocalBinderToken.end()) {
5926 return it->second.promote();
5927 }
5928 return nullptr;
5929}
5930
Dominik Laskowski75848362019-11-11 17:57:20 -08005931void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005932 mNumLayers++;
5933 mScheduler->registerLayer(layer);
5934}
5935
5936void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5937 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005938 removeFromOffscreenLayers(layer);
5939}
5940
5941// WARNING: ONLY CALL THIS FROM LAYER DTOR
5942// Here we add children in the current state to offscreen layers and remove the
5943// layer itself from the offscreen layer list. Since
5944// this is the dtor, it is safe to access the current state. This keeps us
5945// from dangling children layers such that they are not reachable from the
5946// Drawing state nor the offscreen layer list
5947// See b/141111965
5948void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5949 for (auto& child : layer->getCurrentChildren()) {
5950 mOffscreenLayers.emplace(child.get());
5951 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005952 mOffscreenLayers.erase(layer);
5953}
5954
Alec Mouri4545a8a2019-08-08 20:05:32 -07005955void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5956 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5957}
5958
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005959status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5960 float lightPosY, float lightPosZ,
5961 float lightRadius) {
5962 Mutex::Autolock _l(mStateLock);
5963 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5964 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5965 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5966 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5967 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5968
5969 // these values are overridden when calculating the shadow settings for a layer.
5970 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5971 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005972 return NO_ERROR;
5973}
5974
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005975const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5976 const {
5977 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5978 // on the work to remove the table in that bug rather than adding more to
5979 // it.
5980 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5981 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5982 // supported, and exposed via the
5983 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5984 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5985 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5986 };
5987 return genericLayerMetadataKeyMap;
5988}
5989
Steven Thomas62a4cf82020-01-31 12:04:03 -08005990status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5991 int8_t compatibility) {
5992 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5993 return BAD_VALUE;
5994 }
5995
5996 Mutex::Autolock lock(mStateLock);
5997 if (authenticateSurfaceTextureLocked(surface)) {
5998 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5999 if (layer->setFrameRate(
6000 Layer::FrameRate(frameRate,
6001 Layer::FrameRate::convertCompatibility(compatibility)))) {
6002 setTransactionFlags(eTraversalNeeded);
6003 }
6004 } else {
6005 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6006 return BAD_VALUE;
6007 }
6008 return NO_ERROR;
6009}
6010
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006011} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006012
Mathias Agopian3f844832013-08-07 21:24:32 -07006013#if defined(__gl_h_)
6014#error "don't include gl/gl.h in this file"
6015#endif
6016
6017#if defined(__gl2_h_)
6018#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006019#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006020
6021// TODO(b/129481165): remove the #pragma below and fix conversion issues
6022#pragma clang diagnostic pop // ignored "-Wconversion"