blob: 8f669281023c1042038179b3db3e83a9ca839a2f [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 Piquede196652020-01-22 17:29:58 -080039#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080040#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070041#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080043#include <configstore/Utils.h>
44#include <cutils/compiler.h>
45#include <cutils/properties.h>
46#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080048#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070049#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070050#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080055#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080056#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080057#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080059#include <layerproto/LayerProtoParser.h>
60#include <log/log.h>
61#include <private/android_filesystem_config.h>
62#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070063#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080064#include <statslog.h>
65#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <ui/ColorSpace.h>
67#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080068#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <ui/DisplayInfo.h>
70#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080071#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <ui/GraphicBufferAllocator.h>
73#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070074#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070076#include <utils/String16.h>
77#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070078#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080079#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070080#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Alec Mouri5f487d42020-02-06 09:26:19 -080082#include <algorithm>
83#include <cinttypes>
84#include <cmath>
85#include <cstdint>
86#include <functional>
87#include <mutex>
88#include <optional>
89#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Robert Carr578038f2018-03-09 12:25:24 -080091#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070092#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070093#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020094#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080096#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070098#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070099#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700100#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700101#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700102#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800103#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700105#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800106#include "Layer.h"
107#include "LayerVector.h"
108#include "MonitoredProducer.h"
109#include "NativeWindowSurface.h"
110#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700111#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700112#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700113#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114#include "Scheduler/EventControlThread.h"
115#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700116#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700117#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700118#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800119#include "StartPropertySetThread.h"
120#include "SurfaceFlingerProperties.h"
121#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800122#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700123#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800124#include "android-base/stringprintf.h"
125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700127
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700128using namespace std::string_literals;
129
Jaesoo Lee43518572017-01-23 19:03:16 +0900130using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900131using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900132using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133
Ady Abraham8532d012019-05-08 14:50:56 -0700134using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800135using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700136using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700137using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800138using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700139using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700140using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900141
Steven Thomasb02664d2017-07-26 18:48:28 -0700142namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700143
144#pragma clang diagnostic push
145#pragma clang diagnostic error "-Wswitch-enum"
146
147bool isWideColorMode(const ColorMode colorMode) {
148 switch (colorMode) {
149 case ColorMode::DISPLAY_P3:
150 case ColorMode::ADOBE_RGB:
151 case ColorMode::DCI_P3:
152 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700153 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700154 case ColorMode::BT2100_PQ:
155 case ColorMode::BT2100_HLG:
156 return true;
157 case ColorMode::NATIVE:
158 case ColorMode::STANDARD_BT601_625:
159 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
160 case ColorMode::STANDARD_BT601_525:
161 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
162 case ColorMode::STANDARD_BT709:
163 case ColorMode::SRGB:
164 return false;
165 }
166 return false;
167}
168
169#pragma clang diagnostic pop
170
Steven Thomasb02664d2017-07-26 18:48:28 -0700171class ConditionalLock {
172public:
173 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
174 if (lock) {
175 mMutex.lock();
176 }
177 }
178 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
179private:
180 Mutex& mMutex;
181 bool mLocked;
182};
Peiyong Linfca547f2018-07-09 13:03:33 -0700183
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800184// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
185constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
186
187float getDensityFromProperty(const char* property, bool required) {
188 char value[PROPERTY_VALUE_MAX];
189 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
190 if (!density && required) {
191 ALOGE("%s must be defined as a build property", property);
192 return FALLBACK_DENSITY;
193 }
194 return density / 160.f;
195}
196
Peiyong Lin9d846a52018-11-05 13:18:20 -0800197// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
198bool validateCompositionDataspace(Dataspace dataspace) {
199 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
200}
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202} // namespace anonymous
203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204// ---------------------------------------------------------------------------
205
Mathias Agopian99b49842011-06-27 16:05:52 -0700206const String16 sHardwareTest("android.permission.HARDWARE_TEST");
207const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
208const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
209const String16 sDump("android.permission.DUMP");
210
211// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800214uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800215bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800216bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800217int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600218bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800219ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700220bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700221bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700222Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
223ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
224Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
225ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800226bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700227
Kalle Raitaa099a242017-01-11 11:17:29 -0800228std::string getHwcServiceName() {
229 char value[PROPERTY_VALUE_MAX] = {};
230 property_get("debug.sf.hwc_service_name", value, "default");
231 ALOGI("Using HWComposer service: '%s'", value);
232 return std::string(value);
233}
234
235bool useTrebleTestingOverride() {
236 char value[PROPERTY_VALUE_MAX] = {};
237 property_get("debug.sf.treble_testing_override", value, "false");
238 ALOGI("Treble testing override: '%s'", value);
239 return std::string(value) == "true";
240}
241
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800242std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
243 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Enhanced");
250 default:
251 return std::string("Unknown ") +
252 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800253 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254}
255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800257
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
259 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700261 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700262 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700264 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800265 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
266 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800267
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700268SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800269 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800278
Steven Thomas050b2c82017-03-06 11:45:16 -0800279 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 mDefaultCompositionDataspace =
289 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700290 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
291 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 defaultCompositionDataspace = mDefaultCompositionDataspace;
293 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
294 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
295 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
296 wideColorGamutCompositionPixelFormat =
297 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700298
Yichi Chenda901bf2019-06-28 14:58:27 +0800299 mColorSpaceAgnosticDataspace =
300 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800303
Dominik Laskowski718f9602019-11-09 20:01:35 -0800304 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
305 switch (primary_display_orientation(Values::ORIENTATION_0)) {
306 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800308 case Values::ORIENTATION_90:
309 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 case Values::ORIENTATION_180:
312 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800314 case Values::ORIENTATION_270:
315 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
317 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahn85131bd2019-02-18 15:51:53 +0900320 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // debugging stuff...
323 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700324
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700326 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327
Alec Mouri5f487d42020-02-06 09:26:19 -0800328 property_get("ro.build.type", value, "user");
329 mIsUserBuild = strcmp(value, "user") == 0;
330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 property_get("debug.sf.showupdates", value, "0");
332 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700333
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700334 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000335
336 // DDMS debugging deprecated (b/120782499)
337 property_get("debug.sf.ddms", value, "0");
338 int debugDdms = atoi(value);
339 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700340
341 property_get("debug.sf.disable_backpressure", value, "0");
342 mPropagateBackpressure = !atoi(value);
343 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700344
Ady Abrahamadb9a992019-09-19 21:21:55 +0000345 property_get("debug.sf.enable_gl_backpressure", value, "0");
346 mPropagateBackpressureClientComposition = atoi(value);
347 ALOGI_IF(mPropagateBackpressureClientComposition,
348 "Enabling backpressure propagation for Client Composition");
349
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800350 property_get("debug.sf.enable_hwc_vds", value, "0");
351 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800352 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800354 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800355 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800356 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700357
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800358 property_get("ro.surface_flinger.supports_background_blur", value, "0");
359 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800360 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800361 bool disableBlurs = atoi(value);
362 mEnableBlurs = supportsBlurs && !disableBlurs;
363 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
364 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800365 property_get("ro.sf.blurs_are_expensive", value, "0");
366 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800367
Yiwei Zhang243b3782018-05-15 17:40:04 -0700368 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700369 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
370 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800371 mGraphicBufferProducerListSizeLogThreshold =
372 std::max(static_cast<int>(0.95 *
373 static_cast<double>(mMaxGraphicBufferProducerListSize)),
374 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375
Dan Stozaec460082018-12-17 15:35:09 -0800376 property_get("debug.sf.luma_sampling", value, "1");
377 mLumaSampling = atoi(value);
378
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800379 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800380 mDisableClientCompositionCache = atoi(value);
381
Romain Guy11d63f42017-07-20 12:47:14 -0700382 // We should be reading 'persist.sys.sf.color_saturation' here
383 // but since /data may be encrypted, we need to wait until after vold
384 // comes online to attempt to read the property. The property is
385 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800386
387 if (useTrebleTestingOverride()) {
388 // Without the override SurfaceFlinger cannot connect to HIDL
389 // services that are not listed in the manifests. Considered
390 // deriving the setting from the set service name, but it
391 // would be brittle if the name that's not 'default' is used
392 // for production purposes later on.
393 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
394 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800395
396 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397}
398
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399void SurfaceFlinger::onFirstRef()
400{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800401 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402}
403
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700404SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405
Dan Stozac7014012014-02-14 15:03:43 -0800406void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407{
408 // the window manager died on us. prepare its eulogy.
409
Andy McFadden13a082e2012-08-24 10:16:42 -0700410 // restore initial conditions (default device unblank, etc)
411 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412
413 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700414 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415}
416
Robert Carr1db73f62016-12-21 12:58:51 -0800417static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700418 status_t err = client->initCheck();
419 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800420 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800421 }
Robert Carr1db73f62016-12-21 12:58:51 -0800422 return nullptr;
423}
424
425sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
426 return initClient(new Client(this));
427}
428
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700429sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
430 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700431{
432 class DisplayToken : public BBinder {
433 sp<SurfaceFlinger> flinger;
434 virtual ~DisplayToken() {
435 // no more references, this display must be terminated
436 Mutex::Autolock _l(flinger->mStateLock);
437 flinger->mCurrentState.displays.removeItem(this);
438 flinger->setTransactionFlags(eDisplayTransactionNeeded);
439 }
440 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700441 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700442 : flinger(flinger) {
443 }
444 };
445
446 sp<BBinder> token = new DisplayToken(this);
447
448 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700449 // Display ID is assigned when virtual display is allocated by HWC.
450 DisplayDeviceState state;
451 state.isSecure = secure;
452 state.displayName = displayName;
453 mCurrentState.displays.add(token, state);
454 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700455 return token;
456}
457
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700458void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700459 Mutex::Autolock _l(mStateLock);
460
Dominik Laskowski075d3172018-05-24 15:50:06 -0700461 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
462 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700463 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700464 return;
465 }
466
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
468 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 ALOGE("destroyDisplay called for non-virtual display");
470 return;
471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 mInterceptor->saveDisplayDeletion(state.sequenceId);
473 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 setTransactionFlags(eDisplayTransactionNeeded);
475}
476
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800477std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
478 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800480 const auto internalDisplayId = getInternalDisplayIdLocked();
481 if (!internalDisplayId) {
482 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483 }
484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485 std::vector<PhysicalDisplayId> displayIds;
486 displayIds.reserve(mPhysicalDisplayTokens.size());
487 displayIds.push_back(internalDisplayId->value);
488
489 for (const auto& [id, token] : mPhysicalDisplayTokens) {
490 if (id != *internalDisplayId) {
491 displayIds.push_back(id.value);
492 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495 return displayIds;
496}
497
498sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
499 Mutex::Autolock lock(mStateLock);
500 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501}
502
Ady Abraham37965d42018-11-01 13:43:32 -0700503status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
504 if (!outGetColorManagement) {
505 return BAD_VALUE;
506 }
507 *outGetColorManagement = useColorManagement;
508 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700509}
510
Lloyd Pique441d5042018-10-18 16:49:51 -0700511HWComposer& SurfaceFlinger::getHwComposer() const {
512 return mCompositionEngine->getHwComposer();
513}
514
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700515renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
516 return mCompositionEngine->getRenderEngine();
517}
518
Lloyd Pique70d91362018-10-18 16:02:55 -0700519compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
520 return *mCompositionEngine.get();
521}
522
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523void SurfaceFlinger::bootFinished()
524{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700525 if (mStartPropertySetThread->join() != NO_ERROR) {
526 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800527 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528 const nsecs_t now = systemTime();
529 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000530 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531
Mikael Pessa90092f42019-08-26 17:22:04 -0700532 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000533 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // wait patiently for the window manager death
536 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700537 mWindowManager = defaultServiceManager()->getService(name);
538 if (mWindowManager != 0) {
539 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540 }
Robert Carr720e5062018-07-30 17:45:14 -0700541 sp<IBinder> input(defaultServiceManager()->getService(
542 String16("inputflinger")));
543 if (input == nullptr) {
544 ALOGE("Failed to link to input service");
545 } else {
546 mInputFlinger = interface_cast<IInputFlinger>(input);
547 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548
Steven Thomas050b2c82017-03-06 11:45:16 -0800549 if (mVrFlinger) {
550 mVrFlinger->OnBootFinished();
551 }
552
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700554 // formerly we would just kill the process, but we now ask it to exit so it
555 // can choose where to stop the animation.
556 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700557
558 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
559 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
560 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700561
Ana Krulecbd6654b2019-02-15 15:18:15 -0800562 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800563 readPersistentProperties();
564 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565
Ady Abraham8a82ba62020-01-17 12:43:17 -0800566 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
567 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
568 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
569 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800571}
572
Dan Stoza436ccf32018-06-21 12:10:12 -0700573uint32_t SurfaceFlinger::getNewTexture() {
574 {
575 std::lock_guard lock(mTexturePoolMutex);
576 if (!mTexturePool.empty()) {
577 uint32_t name = mTexturePool.back();
578 mTexturePool.pop_back();
579 ATRACE_INT("TexturePoolSize", mTexturePool.size());
580 return name;
581 }
582
583 // The pool was too small, so increase it for the future
584 ++mTexturePoolSize;
585 }
586
587 // The pool was empty, so we need to get a new texture name directly using a
588 // blocking call to the main thread
589 uint32_t name = 0;
590 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
591 return name;
592}
593
Mathias Agopian3f844832013-08-07 21:24:32 -0700594void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700595 std::lock_guard lock(mTexturePoolMutex);
596 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
597 // to actually delete this or not based on mTexturePoolSize
598 mTexturePool.push_back(texture);
599 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700600}
601
Wei Wangf9b05ee2017-07-19 20:59:39 -0700602// Do not call property_set on main thread which will be blocked by init
603// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700605 ALOGI( "SurfaceFlinger's main thread ready to run. "
606 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800608
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700610 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800611 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700612 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
613 renderengine::RenderEngineCreationArgs::Builder()
614 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
615 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
616 .setUseColorManagerment(useColorManagement)
617 .setEnableProtectedContext(enable_protected_contents(false))
618 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800619 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700620 .setContextPriority(useContextPriority
621 ? renderengine::RenderEngine::ContextPriority::HIGH
622 : renderengine::RenderEngine::ContextPriority::MEDIUM)
623 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800624 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700625
626 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
627 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700628 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800629 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800630 // Process any initial hotplug and resulting display changes.
631 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700632 const auto display = getDefaultDisplayDeviceLocked();
633 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700634 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700635 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800636
Steven Thomas050b2c82017-03-06 11:45:16 -0800637 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700639 // This callback is called from the vr flinger dispatch thread. We
640 // need to call signalTransaction(), which requires holding
641 // mStateLock when we're not on the main thread. Acquiring
642 // mStateLock from the vr flinger dispatch thread might trigger a
643 // deadlock in surface flinger (see b/66916578), so post a message
644 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700645 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700646 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
647 mVrFlingerRequestsDisplay = requestDisplay;
648 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700649 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800650 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
652 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700653 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 .value_or(0),
655 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 if (!mVrFlinger) {
657 ALOGE("Failed to start vrflinger");
658 }
659 }
660
Mathias Agopian92a979a2012-08-02 18:32:23 -0700661 // initialize our drawing state
662 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700663
Andy McFadden13a082e2012-08-24 10:16:42 -0700664 // set initial conditions (e.g. unblank default device)
665 initializeDisplays();
666
Steven Thomas137d4bc2019-07-25 16:55:14 -0700667 char primeShaderCache[PROPERTY_VALUE_MAX];
668 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
669 if (atoi(primeShaderCache)) {
670 getRenderEngine().primeCache();
671 }
Dan Stoza4e637772016-07-28 13:31:51 -0700672
Wei Wangf9b05ee2017-07-19 20:59:39 -0700673 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700674
675 const bool presentFenceReliable =
676 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
677 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700678
679 if (mStartPropertySetThread->Start() != NO_ERROR) {
680 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800681 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800682
Dan Stoza9e56aa02015-11-02 13:00:03 -0800683 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700684}
685
Romain Guy11d63f42017-07-20 12:47:14 -0700686void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700687 Mutex::Autolock _l(mStateLock);
688
Romain Guy11d63f42017-07-20 12:47:14 -0700689 char value[PROPERTY_VALUE_MAX];
690
691 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800692 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700693 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800694 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100695
696 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700697 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800698
699 property_get("persist.sys.sf.color_mode", value, "0");
700 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700701}
702
Mathias Agopiana67e4182012-06-19 17:26:12 -0700703void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800704 // Start boot animation service by setting a property mailbox
705 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800707 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 if (mStartPropertySetThread->join() != NO_ERROR) {
709 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800710 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700711}
712
Mathias Agopian875d8e12013-06-07 15:35:48 -0700713size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700714 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700715}
716
Mathias Agopian875d8e12013-06-07 15:35:48 -0700717size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700718 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700719}
720
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800722
Jamie Gennis582270d2011-08-17 18:19:00 -0700723bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800724 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800725 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800726 return authenticateSurfaceTextureLocked(bufferProducer);
727}
728
729bool SurfaceFlinger::authenticateSurfaceTextureLocked(
730 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800731 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800732 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800733}
734
Brian Anderson6b376712017-04-04 10:51:39 -0700735status_t SurfaceFlinger::getSupportedFrameTimestamps(
736 std::vector<FrameEvent>* outSupported) const {
737 *outSupported = {
738 FrameEvent::REQUESTED_PRESENT,
739 FrameEvent::ACQUIRE,
740 FrameEvent::LATCH,
741 FrameEvent::FIRST_REFRESH_START,
742 FrameEvent::LAST_REFRESH_START,
743 FrameEvent::GPU_COMPOSITION_DONE,
744 FrameEvent::DEQUEUE_READY,
745 FrameEvent::RELEASE,
746 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700747 ConditionalLock _l(mStateLock,
748 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700749 if (!getHwComposer().hasCapability(
750 HWC2::Capability::PresentFenceIsNotReliable)) {
751 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
752 }
753 return NO_ERROR;
754}
755
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800756status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
757 if (!displayToken || !state) {
758 return BAD_VALUE;
759 }
760
761 Mutex::Autolock lock(mStateLock);
762
763 const auto display = getDisplayDeviceLocked(displayToken);
764 if (!display) {
765 return NAME_NOT_FOUND;
766 }
767
768 state->layerStack = display->getLayerStack();
769 state->orientation = display->getOrientation();
770
771 const Rect viewport = display->getViewport();
772 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
773
774 return NO_ERROR;
775}
776
777status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
778 if (!displayToken || !info) {
779 return BAD_VALUE;
780 }
781
782 Mutex::Autolock lock(mStateLock);
783
784 const auto display = getDisplayDeviceLocked(displayToken);
785 if (!display) {
786 return NAME_NOT_FOUND;
787 }
788
Dominik Laskowski55c85402020-01-21 16:25:47 -0800789 if (const auto connectionType = display->getConnectionType())
790 info->connectionType = *connectionType;
791 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800792 return INVALID_OPERATION;
793 }
794
795 if (mEmulatedDisplayDensity) {
796 info->density = mEmulatedDisplayDensity;
797 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800798 info->density = info->connectionType == DisplayConnectionType::Internal
799 ? mInternalDisplayDensity
800 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800801 }
802
803 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200804 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800805
806 return NO_ERROR;
807}
808
Dominik Laskowski22488f62019-03-28 09:53:04 -0700809status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800810 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700811 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 return BAD_VALUE;
813 }
814
Dominik Laskowski22488f62019-03-28 09:53:04 -0700815 Mutex::Autolock lock(mStateLock);
816
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800817 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700818 if (!displayId) {
819 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700820 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800822 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800827 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700828
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800829 auto width = hwConfig->getWidth();
830 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800832 auto xDpi = hwConfig->getDpiX();
833 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700834
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 if (isInternal &&
836 (internalDisplayOrientation == ui::ROTATION_90 ||
837 internalDisplayOrientation == ui::ROTATION_270)) {
838 std::swap(width, height);
839 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 }
841
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800842 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 if (mEmulatedDisplayDensity) {
845 config.xDpi = mEmulatedDisplayDensity;
846 config.yDpi = mEmulatedDisplayDensity;
847 } else {
848 config.xDpi = xDpi;
849 config.yDpi = yDpi;
850 }
851
852 const nsecs_t period = hwConfig->getVsyncPeriod();
853 config.refreshRate = 1e9f / period;
854
855 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
856 config.appVsyncOffset = offsets.late.app;
857 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858
Andy McFadden91b2ca82014-06-13 14:04:23 -0700859 // This is how far in advance a buffer must be queued for
860 // presentation at a given time. If you want a buffer to appear
861 // on the screen at time N, you must submit the buffer before
862 // (N - presentationDeadline).
863 //
864 // Normally it's one full refresh period (to give SF a chance to
865 // latch the buffer), but this can be reduced by configuring a
866 // DispSync offset. Any additional delays introduced by the hardware
867 // composer or panel must be accounted for here.
868 //
869 // We add an additional 1ms to allow for processing time and
870 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700872
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700874 }
875
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 return NO_ERROR;
877}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700878
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700879status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
880 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700881 return BAD_VALUE;
882 }
883
Ana Krulecc2870422019-01-29 19:00:58 -0800884 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700885 return NO_ERROR;
886}
887
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700888int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
889 const auto display = getDisplayDevice(displayToken);
890 if (!display) {
891 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800892 return BAD_VALUE;
893 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700894
Steven Thomasc9098452019-09-30 17:15:05 -0700895 if (display->isPrimary()) {
896 std::lock_guard<std::mutex> lock(mActiveConfigLock);
897 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800898 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700899 }
Steven Thomasc9098452019-09-30 17:15:05 -0700900 }
Ady Abraham2139f732019-11-13 18:56:40 -0800901
902 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Ady Abraham03b02dd2019-03-21 15:40:11 -0700905void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800906 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800907 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
908 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800909
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800910 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800911 // config twice. However event generation config might have changed so we need to update it
912 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800913 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700914 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
915 mDesiredActiveConfig = info;
916 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800917
918 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800919 // This will trigger HWC refresh without resetting the idle timer.
920 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700921 // Start receiving vsync samples now, so that we can detect a period
922 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800923 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700924 // As we called to set period, we will call to onRefreshRateChangeCompleted once
925 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700926 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800927
Ady Abraham9e16a482019-12-03 17:19:41 -0800928 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
929 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800931 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700932
933 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800934 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700935 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936}
937
938status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
939 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800940
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100941 if (!displayToken) {
942 return BAD_VALUE;
943 }
Ady Abraham838de062019-02-04 10:24:03 -0800944
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100945 status_t result = NO_ERROR;
946
947 postMessageSync(new LambdaMessage([&]() {
948 const auto display = getDisplayDeviceLocked(displayToken);
949 if (!display) {
950 ALOGE("Attempt to set allowed display configs for invalid display token %p",
951 displayToken.get());
952 result = BAD_VALUE;
953 } else if (display->isVirtual()) {
954 ALOGW("Attempt to set allowed display configs for virtual display");
955 result = BAD_VALUE;
956 } else {
957 HwcConfigIndexType config(mode);
958 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
959 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
960 refreshRate.fps);
961 }
962 }));
963
964 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965}
966
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800967void SurfaceFlinger::setActiveConfigInternal() {
968 ATRACE_CALL();
969
Dominik Laskowski22488f62019-03-28 09:53:04 -0700970 const auto display = getDefaultDisplayDeviceLocked();
971 if (!display) {
972 return;
973 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974
Dominik Laskowski22488f62019-03-28 09:53:04 -0700975 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800976 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700977 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 display->setActiveConfig(mUpcomingActiveConfig.configId);
979
Ady Abraham2139f732019-11-13 18:56:40 -0800980 auto refreshRate =
981 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800982 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
983 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800984 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700985
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800986 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700987 const nsecs_t vsyncPeriod =
988 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
989 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800990 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700991 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800992 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993}
994
Ady Abraham53852a52019-05-28 18:07:44 -0700995void SurfaceFlinger::desiredActiveConfigChangeDone() {
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
997 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
998 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700999
Kevin DuBois5988f482020-01-17 09:03:32 -08001000 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001001 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001002 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001003 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1004 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001005}
1006
Dominik Laskowski22488f62019-03-28 09:53:04 -07001007bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001008 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001009 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001011 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001013 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 return true;
1015 }
1016
1017 // We received the present fence from the HWC, so we assume it successfully updated
1018 // the config, hence we update SF.
1019 mCheckPendingFence = false;
1020 setActiveConfigInternal();
1021 }
1022
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023 // Store the local variable to release the lock.
1024 ActiveConfigInfo desiredActiveConfig;
1025 {
1026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001027 if (!mDesiredActiveConfigChanged) {
1028 return false;
1029 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001030 desiredActiveConfig = mDesiredActiveConfig;
1031 }
1032
Ady Abraham2139f732019-11-13 18:56:40 -08001033 auto refreshRate =
1034 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1035 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1036 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001037 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1039 // display is not valid or we are already in the requested mode
1040 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001041 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001042 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044
Ady Abraham838de062019-02-04 10:24:03 -08001045 // Desired active config was set, it is different than the config currently in use, however
1046 // allowed configs might have change by the time we process the refresh.
1047 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001048 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001049 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001050 return false;
1051 }
Alec Mouri7f015182019-07-11 13:56:22 -07001052
Ady Abrahamb838aed2019-02-12 15:30:16 -08001053 mUpcomingActiveConfig = desiredActiveConfig;
1054 const auto displayId = display->getId();
1055 LOG_ALWAYS_FATAL_IF(!displayId);
1056
Ady Abraham2139f732019-11-13 18:56:40 -08001057 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001059 // TODO(b/142753666) use constrains
1060 HWC2::VsyncPeriodChangeConstraints constraints;
1061 constraints.desiredTimeNanos = systemTime();
1062 constraints.seamlessRequired = false;
1063
1064 HWC2::VsyncPeriodChangeTimeline outTimeline;
1065 auto status =
1066 getHwComposer().setActiveConfigWithConstraints(*displayId,
1067 mUpcomingActiveConfig.configId.value(),
1068 constraints, &outTimeline);
1069 if (status != NO_ERROR) {
1070 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1071 return false;
1072 }
1073
1074 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1075 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001076 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1081 Vector<ColorMode>* outColorModes) {
1082 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001083 return BAD_VALUE;
1084 }
1085
Peiyong Lina52f0292018-03-14 17:26:31 -07001086 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001087 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001088 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001089 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1090
1091 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1092 if (!displayId) {
1093 return NAME_NOT_FOUND;
1094 }
1095
Dominik Laskowski075d3172018-05-24 15:50:06 -07001096 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001097 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001098 }
Michael Wright28f24d02016-07-12 13:30:53 -07001099 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001100
1101 // If it's built-in display and the configuration claims it's not wide color capable,
1102 // filter out all wide color modes. The typical reason why this happens is that the
1103 // hardware is not good enough to support GPU composition of wide color, and thus the
1104 // OEMs choose to disable this capability.
1105 if (isInternalDisplay && !hasWideColorDisplay) {
1106 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1107 isWideColorMode);
1108 } else {
1109 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1110 }
Michael Wright28f24d02016-07-12 13:30:53 -07001111
1112 return NO_ERROR;
1113}
1114
Daniel Solomon42d04562019-01-20 21:03:19 -08001115status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1116 ui::DisplayPrimaries &primaries) {
1117 if (!displayToken) {
1118 return BAD_VALUE;
1119 }
1120
1121 // Currently we only support this API for a single internal display.
1122 if (getInternalDisplayToken() != displayToken) {
1123 return BAD_VALUE;
1124 }
1125
1126 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1127 return NO_ERROR;
1128}
1129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1131 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001132 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001133 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001134 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001135}
1136
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001138 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139 Vector<ColorMode> modes;
1140 getDisplayColorModes(displayToken, &modes);
1141 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1142 if (mode < ColorMode::NATIVE || !exists) {
1143 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1144 decodeColorMode(mode).c_str(), mode, displayToken.get());
1145 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001146 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 const auto display = getDisplayDevice(displayToken);
1148 if (!display) {
1149 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1150 decodeColorMode(mode).c_str(), mode, displayToken.get());
1151 } else if (display->isVirtual()) {
1152 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1153 decodeColorMode(mode).c_str(), mode);
1154 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001155 display->getCompositionDisplay()->setColorProfile(
1156 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1157 RenderIntent::COLORIMETRIC,
1158 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 }
1160 }));
1161
Michael Wright28f24d02016-07-12 13:30:53 -07001162 return NO_ERROR;
1163}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001164
Galia Peycheva5492cb52019-10-30 14:13:16 +01001165status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1166 bool* outSupport) const {
1167 Mutex::Autolock _l(mStateLock);
1168
1169 if (!displayToken) {
1170 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1171 return BAD_VALUE;
1172 }
1173 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1174 if (!displayId) {
1175 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1176 displayToken.get());
1177 return NAME_NOT_FOUND;
1178 }
1179 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1180 HWC2::DisplayCapability::AutoLowLatencyMode);
1181 return NO_ERROR;
1182}
1183
1184void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1185 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1186}
1187
1188void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1189 if (!displayToken) {
1190 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1191 return;
1192 }
1193 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1194 if (!displayId) {
1195 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1196 displayToken.get());
1197 return;
1198 }
1199
1200 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1201}
1202
1203status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1204 bool* outSupport) const {
1205 Mutex::Autolock _l(mStateLock);
1206
1207 if (!displayToken) {
1208 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1209 return BAD_VALUE;
1210 }
1211 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1212 if (!displayId) {
1213 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1214 displayToken.get());
1215 return NAME_NOT_FOUND;
1216 }
1217
1218 std::vector<HWC2::ContentType> outSupportedContentTypes;
1219 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1220 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1221 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1222 return NO_ERROR;
1223}
1224
1225void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1226 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1227}
1228
1229void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1230 if (!displayToken) {
1231 ALOGE("setGameContentType() failed. Missing display token.");
1232 return;
1233 }
1234 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1235 if (!displayId) {
1236 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1237 displayToken.get());
1238 return;
1239 }
1240
1241 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1242 getHwComposer().setContentType(*displayId, type);
1243}
1244
Svetoslavd85084b2014-03-20 10:28:31 -07001245status_t SurfaceFlinger::clearAnimationFrameStats() {
1246 Mutex::Autolock _l(mStateLock);
1247 mAnimFrameTracker.clearStats();
1248 return NO_ERROR;
1249}
1250
1251status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1252 Mutex::Autolock _l(mStateLock);
1253 mAnimFrameTracker.getStats(outStats);
1254 return NO_ERROR;
1255}
1256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001257status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1258 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001259 Mutex::Autolock _l(mStateLock);
1260
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001261 const auto display = getDisplayDeviceLocked(displayToken);
1262 if (!display) {
1263 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001264 return BAD_VALUE;
1265 }
1266
Peiyong Linfb069302018-04-25 14:34:31 -07001267 // At this point the DisplayDeivce should already be set up,
1268 // meaning the luminance information is already queried from
1269 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001270 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001271 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1272 capabilities.getDesiredMaxLuminance(),
1273 capabilities.getDesiredMaxAverageLuminance(),
1274 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001275
1276 return NO_ERROR;
1277}
1278
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001279std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1280 const DisplayDevice& display) const {
1281 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1282 // avoid repetitive HAL IPC and EDID parsing.
1283 const auto displayId = display.getId();
1284 LOG_FATAL_IF(!displayId);
1285
1286 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1287 LOG_FATAL_IF(!hwcDisplayId);
1288
1289 uint8_t port;
1290 DisplayIdentificationData data;
1291 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1292 ALOGV("%s: No identification data.", __FUNCTION__);
1293 return {};
1294 }
1295
1296 const auto info = parseDisplayIdentificationData(port, data);
1297 if (!info) {
1298 return {};
1299 }
1300 return info->deviceProductInfo;
1301}
1302
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001303status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1304 ui::PixelFormat* outFormat,
1305 ui::Dataspace* outDataspace,
1306 uint8_t* outComponentMask) const {
1307 if (!outFormat || !outDataspace || !outComponentMask) {
1308 return BAD_VALUE;
1309 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001310 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001311 if (!display || !display->getId()) {
1312 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1313 return BAD_VALUE;
1314 }
1315 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1316 outDataspace, outComponentMask);
1317}
1318
Kevin DuBois74e53772018-11-19 10:52:38 -08001319status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1320 bool enable, uint8_t componentMask,
1321 uint64_t maxFrames) const {
1322 const auto display = getDisplayDevice(displayToken);
1323 if (!display || !display->getId()) {
1324 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1325 return BAD_VALUE;
1326 }
1327
1328 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1329 componentMask, maxFrames);
1330}
1331
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001332status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1333 uint64_t maxFrames, uint64_t timestamp,
1334 DisplayedFrameStats* outStats) const {
1335 const auto display = getDisplayDevice(displayToken);
1336 if (!display || !display->getId()) {
1337 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1338 return BAD_VALUE;
1339 }
1340
1341 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1342 outStats);
1343}
1344
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001345status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1346 if (!outSupported) {
1347 return BAD_VALUE;
1348 }
1349 *outSupported = getRenderEngine().supportsProtectedContent();
1350 return NO_ERROR;
1351}
1352
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001353status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1354 bool* outIsWideColorDisplay) const {
1355 if (!displayToken || !outIsWideColorDisplay) {
1356 return BAD_VALUE;
1357 }
1358 Mutex::Autolock _l(mStateLock);
1359 const auto display = getDisplayDeviceLocked(displayToken);
1360 if (!display) {
1361 return BAD_VALUE;
1362 }
Peiyong Linff84a152019-05-17 18:36:19 -07001363
1364 // Use hasWideColorDisplay to override built-in display.
1365 const auto displayId = display->getId();
1366 if (displayId && displayId == getInternalDisplayIdLocked()) {
1367 *outIsWideColorDisplay = hasWideColorDisplay;
1368 return NO_ERROR;
1369 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001370 *outIsWideColorDisplay = display->hasWideColorGamut();
1371 return NO_ERROR;
1372}
1373
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001374status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001375 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001376 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001377
Dominik Laskowski6505f792019-09-18 11:10:05 -07001378 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1379 mEventQueue->setEventConnection(
1380 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001381 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001382 }));
1383
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001384 return NO_ERROR;
1385}
1386
1387status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001388 Mutex::Autolock lock(mStateLock);
1389 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001390}
1391
Lloyd Pique755e3192018-01-31 16:46:15 -08001392status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1393 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001394 // Try to acquire a lock for 1s, fail gracefully
1395 const status_t err = mStateLock.timedLock(s2ns(1));
1396 const bool locked = (err == NO_ERROR);
1397 if (!locked) {
1398 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1399 return TIMED_OUT;
1400 }
1401
1402 outLayers->clear();
1403 mCurrentState.traverseInZOrder([&](Layer* layer) {
1404 outLayers->push_back(layer->getLayerDebugInfo());
1405 });
1406
1407 mStateLock.unlock();
1408 return NO_ERROR;
1409}
1410
Peiyong Linc6780972018-10-28 15:24:08 -07001411status_t SurfaceFlinger::getCompositionPreference(
1412 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1413 Dataspace* outWideColorGamutDataspace,
1414 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001415 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001416 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001417 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001418 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001419 return NO_ERROR;
1420}
1421
Dan Stozaec460082018-12-17 15:35:09 -08001422status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1423 const sp<IBinder>& stopLayerHandle,
1424 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001425 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001426 return BAD_VALUE;
1427 }
1428 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001429 return NO_ERROR;
1430}
1431
Dan Stozaec460082018-12-17 15:35:09 -08001432status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001433 if (!listener) {
1434 return BAD_VALUE;
1435 }
Dan Stozaec460082018-12-17 15:35:09 -08001436 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001437 return NO_ERROR;
1438}
Dan Gittik57e63c52019-01-18 16:37:54 +00001439
1440status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1441 bool* outSupport) const {
1442 if (!displayToken || !outSupport) {
1443 return BAD_VALUE;
1444 }
1445 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1446 if (!displayId) {
1447 return NAME_NOT_FOUND;
1448 }
1449 *outSupport =
1450 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1451 return NO_ERROR;
1452}
1453
1454status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1455 float brightness) const {
1456 if (!displayToken) {
1457 return BAD_VALUE;
1458 }
1459 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1460 if (!displayId) {
1461 return NAME_NOT_FOUND;
1462 }
1463 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1464}
1465
Ady Abraham8532d012019-05-08 14:50:56 -07001466status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1467 PowerHint powerHint = static_cast<PowerHint>(hintId);
1468
1469 if (powerHint == PowerHint::INTERACTION) {
1470 mScheduler->notifyTouchEvent();
1471 }
1472
1473 return NO_ERROR;
1474}
1475
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001476// ----------------------------------------------------------------------------
1477
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001478sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001479 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001480 const auto& handle =
1481 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001482
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001483 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001484}
1485
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001486// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001487
1488void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001489 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001490}
1491
1492void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001493 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001494 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001495 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496}
1497
1498void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001499 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001500 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001501 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001502}
1503
1504void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001505 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001506 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001507}
1508
1509status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001510 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001511 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001512}
1513
1514status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001515 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001516 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001517 if (res == NO_ERROR) {
1518 msg->wait();
1519 }
1520 return res;
1521}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001522
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001523void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001524 do {
1525 waitForEvent();
1526 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001527}
1528
Dominik Laskowski83b88212018-12-11 13:34:06 -08001529nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001530 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001531 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1532 return 0;
1533 }
1534
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001535 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001536}
1537
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001538void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001539 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001540 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001541 ATRACE_NAME("SF onVsync");
1542
Steven Thomas3cfac282017-02-06 12:29:30 -08001543 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001545 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 return;
1547 }
1548
Dominik Laskowski075d3172018-05-24 15:50:06 -07001549 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001550 return;
1551 }
1552
Dominik Laskowski075d3172018-05-24 15:50:06 -07001553 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001554 // For now, we don't do anything with external display vsyncs.
1555 return;
1556 }
1557
Alec Mourif8e689c2019-05-20 18:32:22 -07001558 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001559 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001560 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001561 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001562 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001563}
1564
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001566 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1567 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568}
1569
Ady Abraham2139f732019-11-13 18:56:40 -08001570bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001571 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001572}
1573
Ady Abraham2139f732019-11-13 18:56:40 -08001574void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1575 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001576 const auto display = getDefaultDisplayDeviceLocked();
1577 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001578 return;
1579 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001580 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001581
Ana Krulec7d1d6832018-12-27 11:10:09 -08001582 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001583 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1584 ALOGV("Skipping config %d as it is not part of allowed configs",
1585 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001586 return;
1587 }
1588
Ady Abraham2139f732019-11-13 18:56:40 -08001589 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001590}
1591
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001592void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001593 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001594 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001595 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001596
Lloyd Piqueba04e622017-12-14 17:11:26 -08001597 // Ignore events that do not have the right sequenceId.
1598 if (sequenceId != getBE().mComposerSequenceId) {
1599 return;
1600 }
1601
Steven Thomasb02664d2017-07-26 18:48:28 -07001602 // Only lock if we're not on the main thread. This function is normally
1603 // called on a hwbinder thread, but for the primary display it's called on
1604 // the main thread with the state lock already held, so don't attempt to
1605 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001606 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001607
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001608 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001609
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001610 if (std::this_thread::get_id() == mMainThreadId) {
1611 // Process all pending hot plug events immediately if we are on the main thread.
1612 processDisplayHotplugEventsLocked();
1613 }
1614
Lloyd Piqueba04e622017-12-14 17:11:26 -08001615 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001616}
1617
Ady Abraham7159f572019-10-11 11:10:18 -07001618void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001619 int32_t sequenceId, hwc2_display_t /*display*/,
1620 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1621 Mutex::Autolock lock(mStateLock);
1622 if (sequenceId != getBE().mComposerSequenceId) {
1623 return;
1624 }
1625 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001626}
1627
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001628void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1629 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1630 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1631}
1632
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001633void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001634 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001635 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001636 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001637 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001638 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001639}
1640
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001641void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001642 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001643
1644 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1645 // display power state.
1646 postMessageAsync(new LambdaMessage(
1647 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1648}
1649
1650void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1651 ATRACE_CALL();
1652
Ady Abraham27c70212019-06-11 10:52:26 -07001653 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1654
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001655 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001656 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1657 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001658 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001659 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001660 }
Mathias Agopian86303202012-07-24 22:46:10 -07001661}
1662
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001663// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001664void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001665 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001666 // Clear the drawing state so that the logic inside of
1667 // handleTransactionLocked will fire. It will determine the delta between
1668 // mCurrentState and mDrawingState and re-apply all changes when we make the
1669 // transition.
1670 mDrawingState.displays.clear();
1671 mDisplays.clear();
1672}
1673
Steven Thomas050b2c82017-03-06 11:45:16 -08001674void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001675 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001676 if (!mVrFlinger)
1677 return;
1678 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001679 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001680 return;
1681 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001682
Lloyd Pique441d5042018-10-18 16:49:51 -07001683 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001684 ALOGE("Vr flinger is only supported for remote hardware composer"
1685 " service connections. Ignoring request to transition to vr"
1686 " flinger.");
1687 mVrFlingerRequestsDisplay = false;
1688 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001689 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001691 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001692
Steven Thomas0123ac62018-07-12 11:32:34 -07001693 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001694 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001695
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001696 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001697
1698 // Clear out all the output layers from the composition engine for all
1699 // displays before destroying the hardware composer interface. This ensures
1700 // any HWC layers are destroyed through that interface before it becomes
1701 // invalid.
1702 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001703 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001704 }
1705
Steven Thomas0123ac62018-07-12 11:32:34 -07001706 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1707 // called below. Clear the reference now so we don't accidentally use it
1708 // later.
1709 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710
Steven Thomasb02664d2017-07-26 18:48:28 -07001711 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001712 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001713 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001714
Steven Thomasb02664d2017-07-26 18:48:28 -07001715 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001716 // Delete the current instance before creating the new one
1717 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1718 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1719 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001720 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001721
Lloyd Pique441d5042018-10-18 16:49:51 -07001722 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001723 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001724
1725 if (vrFlingerRequestsDisplay) {
1726 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001727 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001728
1729 mVisibleRegionsDirty = true;
1730 invalidateHwcGeometry();
1731
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001732 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001733 display = getDefaultDisplayDeviceLocked();
1734 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001735 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001736
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001738 const nsecs_t vsyncPeriod = getVsyncPeriod();
1739 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001740
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001741 // The present fences returned from vr_hwc are not an accurate
1742 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001743 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001744
Steven Thomasb02664d2017-07-26 18:48:28 -07001745 // Use phase of 0 since phase is not known.
1746 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001747 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001748 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001749
Ana Krulecc2870422019-01-29 19:00:58 -08001750 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001751
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001752 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001753 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001754}
1755
Ady Abraham11579302019-09-19 12:35:58 -07001756bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1757 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001758 // We are storing the last 2 present fences. If sf's phase offset is to be
1759 // woken up before the actual vsync but targeting the next vsync, we need to check
1760 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001761 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1762 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001763
Ady Abraham11579302019-09-19 12:35:58 -07001764 if (fence == Fence::NO_FENCE) {
1765 return false;
1766 }
1767
1768 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1769 fence->wait(graceTimeMs);
1770 }
1771
1772 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001773}
1774
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001775void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001776 DisplayStatInfo stats;
1777 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001778 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001779 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001780 mExpectedPresentTime.store(
1781 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001782}
1783
Dominik Laskowski22488f62019-03-28 09:53:04 -07001784void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001785 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001786 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001787 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001788 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001789 // calculate the expected present time once and use the cached
1790 // value throughout this frame to make sure all layers are
1791 // seeing this same value.
1792 populateExpectedPresentTime();
1793
Ady Abraham11579302019-09-19 12:35:58 -07001794 // When Backpressure propagation is enabled we want to give a small grace period
1795 // for the present fence to fire instead of just giving up on this frame to handle cases
1796 // where present fence is just about to get signaled.
1797 const int graceTimeForPresentFenceMs =
1798 (mPropagateBackpressure &&
1799 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1800 ? 1
1801 : 0;
1802 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1803 previousFrameMissed(
1804 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001805 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1806 mHadDeviceComposition && frameMissed};
1807 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1808 mHadClientComposition && frameMissed};
1809
Alec Mouricc0fc602019-02-26 21:45:19 -08001810 if (frameMissed) {
1811 mFrameMissedCount++;
1812 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001813 if (mMissedFrameJankCount == 0) {
1814 mMissedFrameJankStart = systemTime();
1815 }
1816 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001817 }
1818
Alec Mouri40189b02019-03-05 15:07:54 -08001819 if (hwcFrameMissed) {
1820 mHwcFrameMissedCount++;
1821 }
1822
1823 if (gpuFrameMissed) {
1824 mGpuFrameMissedCount++;
1825 }
1826
Ady Abrahamadb9a992019-09-19 21:21:55 +00001827 if (frameMissed && mPropagateBackpressure) {
1828 if ((hwcFrameMissed && !gpuFrameMissed) ||
1829 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001830 signalLayerUpdate();
1831 break;
1832 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001833 }
Dan Stoza50182882016-07-08 12:02:20 -07001834
Alec Mouri5f487d42020-02-06 09:26:19 -08001835 // Our jank window is always at least 100ms since we missed a
1836 // frame...
1837 static constexpr nsecs_t kMinJankyDuration =
1838 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1839 // ...but if it's larger than 1s then we missed the trace cutoff.
1840 static constexpr nsecs_t kMaxJankyDuration =
1841 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1842 // If we're in a user build then don't push any atoms
1843 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1844 const auto displayDevice = getDefaultDisplayDeviceLocked();
1845 // Only report jank when the display is on, as displays in DOZE
1846 // power mode may operate at a different frame rate than is
1847 // reported in their config, which causes noticeable (but less
1848 // severe) jank.
1849 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1850 const nsecs_t currentTime = systemTime();
1851 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1852 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1853 ATRACE_NAME("Jank detected");
1854 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1855 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1856 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1857 jankyDurationMillis, mMissedFrameJankCount);
1858 }
1859
1860 // We either reported a jank event or we missed the trace
1861 // window, so clear counters here.
1862 if (jankDuration > kMinJankyDuration) {
1863 mMissedFrameJankCount = 0;
1864 mMissedFrameJankStart = 0;
1865 }
1866 }
1867 }
1868
Steven Thomas050b2c82017-03-06 11:45:16 -08001869 // Now that we're going to make it to the handleMessageTransaction()
1870 // call below it's safe to call updateVrFlinger(), which will
1871 // potentially trigger a display handoff.
1872 updateVrFlinger();
1873
Dan Stoza6b9454d2014-11-07 16:00:59 -08001874 bool refreshNeeded = handleMessageTransaction();
1875 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001876
Ana Krulecc84d09b2019-11-02 23:10:29 +01001877 // Layers need to get updated (in the previous line) before we can use them for
1878 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001879 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1880 // and may eventually call to ~Layer() if it holds the last reference
1881 {
1882 Mutex::Autolock _l(mStateLock);
1883 mScheduler->chooseRefreshRateForContent();
1884 }
1885
Ana Krulecc84d09b2019-11-02 23:10:29 +01001886 if (performSetActiveConfig()) {
1887 break;
1888 }
1889
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001890 updateCursorAsync();
1891 updateInputFlinger();
1892
Dan Stoza58784442014-12-02 16:58:17 -08001893 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001894 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001895 // Signal a refresh if a transaction modified the window state,
1896 // a new buffer was latched, or if HWC has requested a full
1897 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001898 if (mFrameStartTime <= 0) {
1899 // We should only use the time of the first invalidate
1900 // message that signals a refresh as the beginning of the
1901 // frame. Otherwise the real frame time will be
1902 // underestimated.
1903 mFrameStartTime = frameStart;
1904 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001905 signalRefresh();
1906 }
1907 break;
1908 }
1909 case MessageQueue::REFRESH: {
1910 handleMessageRefresh();
1911 break;
1912 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001913 }
1914}
1915
Dan Stoza6b9454d2014-11-07 16:00:59 -08001916bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001917 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001918 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001919
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001920 bool flushedATransaction = flushTransactionQueues();
1921
1922 bool runHandleTransaction = transactionFlags &&
1923 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1924
1925 if (runHandleTransaction) {
1926 handleTransaction(eTransactionMask);
1927 } else {
1928 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001929 }
1930
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001931 if (transactionFlushNeeded()) {
1932 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001933 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001934
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001935 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001936}
1937
Mathias Agopian4fec8732012-06-29 14:12:52 -07001938void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001940
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001941 mRefreshPending = false;
1942
Lloyd Piqueab039b52019-02-13 14:22:42 -08001943 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001944 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001945 for (const auto& [_, display] : mDisplays) {
1946 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1947 }
1948 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001949 if (auto layerFE = layer->getCompositionEngineLayerFE())
1950 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001951 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001952 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1953 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001954 if (auto layerFE = layer->getCompositionEngineLayerFE())
1955 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001956 }
1957
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001958 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001959 refreshArgs.outputColorSetting = useColorManagement
1960 ? mDisplayColorSetting
1961 : compositionengine::OutputColorSetting::kUnmanaged;
1962 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1963 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001964
1965 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1966 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001967 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001968
1969 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1970 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1971 mDrawingState.colorMatrixChanged = false;
1972 }
1973
1974 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1975
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001976 if (mDebugRegion != 0) {
1977 refreshArgs.devOptFlashDirtyRegionsDelay =
1978 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1979 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001980
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001981 mGeometryInvalid = false;
1982
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001983 // Store the present time just before calling to the composition engine so we could notify
1984 // the scheduler.
1985 const auto presentTime = systemTime();
1986
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001987 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001988 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1989 // Reset the frame start time now that we've recorded this frame.
1990 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001991
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001992 mScheduler->onDisplayRefreshed(presentTime);
1993
David Sodmanfa9b2af2017-12-24 13:28:59 -08001994 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001995 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001996
Lloyd Pique66d68602019-02-13 14:23:31 -08001997 mHadClientComposition =
1998 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1999 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002000 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2001 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002002 });
2003 mHadDeviceComposition =
2004 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2005 auto& displayDevice = tokenDisplayPair.second;
2006 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2007 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002008 mReusedClientComposition =
2009 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2010 auto& displayDevice = tokenDisplayPair.second;
2011 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2012 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002013
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002014 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002015
David Sodman7e4ae112018-02-09 15:02:28 -08002016 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002017 if (mVisibleRegionsDirty) {
2018 mVisibleRegionsDirty = false;
2019 if (mTracingEnabled) {
2020 mTracing.notify("visibleRegionsDirty");
2021 }
2022 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002023
2024 if (mCompositionEngine->needsAnotherUpdate()) {
2025 signalLayerUpdate();
2026 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002028
David Sodmanfa9b2af2017-12-24 13:28:59 -08002029
2030bool SurfaceFlinger::handleMessageInvalidate() {
2031 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002032 bool refreshNeeded = handlePageFlip();
2033
Vishnu Nair4351ad52019-02-11 14:13:02 -08002034 if (mVisibleRegionsDirty) {
2035 computeLayerBounds();
2036 }
2037
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002038 for (auto& layer : mLayersPendingRefresh) {
2039 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002040 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002041 invalidateLayerStack(layer, visibleReg);
2042 }
2043 mLayersPendingRefresh.clear();
2044 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002045}
2046
Ana Krulece588e312018-09-18 12:32:24 -07002047void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2048 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 // Update queue of past composite+present times and determine the
2050 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002051 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002052 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002053 while (!getBE().mCompositePresentTimes.empty()) {
2054 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055 // Cached values should have been updated before calling this method,
2056 // which helps avoid duplicate syscalls.
2057 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2058 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2059 break;
2060 }
2061 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002062 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063 }
2064
2065 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002066 while (getBE().mCompositePresentTimes.size() > 16) {
2067 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002068 }
2069
Ana Krulece588e312018-09-18 12:32:24 -07002070 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002071}
2072
Ana Krulece588e312018-09-18 12:32:24 -07002073void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2074 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075 // Integer division and modulo round toward 0 not -inf, so we need to
2076 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002077 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2078 ? (stats.vsyncPeriod -
2079 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2080 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081
Ady Abraham9e16a482019-12-03 17:19:41 -08002082 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002083 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002084 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002085 }
2086
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002087 // Snap the latency to a value that removes scheduling jitter from the
2088 // composition and present times, which often have >1ms of jitter.
2089 // Reducing jitter is important if an app attempts to extrapolate
2090 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002091 // Snapping also allows an app to precisely calculate
2092 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002093 nsecs_t bias = stats.vsyncPeriod / 2;
2094 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2095 nsecs_t snappedCompositeToPresentLatency =
2096 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002097
David Sodman99974d22017-11-28 12:04:33 -08002098 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002099 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2100 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002101 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002102}
2103
David Sodman2b406362017-12-15 13:33:47 -08002104void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002105{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 ATRACE_CALL();
2107 ALOGV("postComposition");
2108
Brian Andersonf6386862016-10-31 16:34:13 -07002109 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002110 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002111 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002112 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002113 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002114 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002115
David Sodman73beded2017-11-15 11:56:06 -08002116 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002117 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002118 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002119 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002120 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2121 ->getRenderSurface()
2122 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002123 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002124 } else {
2125 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2126 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002127
David Sodman73beded2017-11-15 11:56:06 -08002128 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002129 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2130 mPreviousPresentFences[0] = displayDevice
2131 ? getHwComposer().getPresentFence(*displayDevice->getId())
2132 : Fence::NO_FENCE;
2133 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002134 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002135
Ana Krulece588e312018-09-18 12:32:24 -07002136 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002137 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002138
Lloyd Piqueab039b52019-02-13 14:22:42 -08002139 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2140 // be sampled a little later than when we started doing work for this frame,
2141 // but that should be okay since updateCompositorTiming has snapping logic.
2142 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2143 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002144 CompositorTiming compositorTiming;
2145 {
David Sodman99974d22017-11-28 12:04:33 -08002146 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2147 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002148 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002149
Edgar Arriaga844fa672020-01-16 14:21:42 -08002150 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002151 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2152 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002153 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002154 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002155 }
Robert Carr2047fae2016-11-28 14:09:09 -08002156 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002157
Ady Abraham92fa2f42020-02-11 15:33:56 -08002158 if (displayDevice && displayDevice->isPrimary() &&
2159 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002160 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002161 }
2162
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002163 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002164 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2165 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002166 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002167 }
2168 }
2169
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002170 if (mAnimCompositionPending) {
2171 mAnimCompositionPending = false;
2172
Brian Anderson4e606e32017-03-16 15:34:57 -07002173 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002174 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002175 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002176 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002177 // The HWC doesn't support present fences, so use the refresh
2178 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002179 const nsecs_t presentTime =
2180 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002181 mAnimFrameTracker.setActualPresentTime(presentTime);
2182 }
2183 mAnimFrameTracker.advanceFrame();
2184 }
Dan Stozab90cf072015-03-05 11:05:59 -08002185
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002186 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002187 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002188 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002189 }
2190
Vishnu Nair9b079a22020-01-21 14:36:08 -08002191 if (mReusedClientComposition) {
2192 mTimeStats->incrementClientCompositionReusedFrames();
2193 }
2194
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002195 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002196
Alec Mouri717bcb62020-02-10 17:07:19 -08002197 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2198 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2199 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2200
Lloyd Pique32cbe282018-10-19 13:09:22 -07002201 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2202 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002203 return;
2204 }
2205
2206 nsecs_t currentTime = systemTime();
2207 if (mHasPoweredOff) {
2208 mHasPoweredOff = false;
2209 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002210 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002211 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002212 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2213 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002214 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002215 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002216 }
David Sodman4a36e932017-11-07 14:29:47 -08002217 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002218 }
David Sodman4a36e932017-11-07 14:29:47 -08002219 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002220
2221 {
2222 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002223 if (mTexturePool.size() < mTexturePoolSize) {
2224 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002225 const size_t offset = mTexturePool.size();
2226 mTexturePool.resize(mTexturePoolSize);
2227 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2228 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002229 } else if (mTexturePool.size() > mTexturePoolSize) {
2230 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2231 const size_t offset = mTexturePoolSize;
2232 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2233 mTexturePool.resize(mTexturePoolSize);
2234 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002235 }
2236 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002237
Ady Abrahambe0f9482019-04-24 15:41:53 -07002238 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002239 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002240
Kevin DuBois413287f2019-02-25 08:46:47 -08002241 if (mLumaSampling && mRegionSamplingThread) {
2242 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002243 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002244
2245 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2246 // side-effect of getTotalSize(), so we check that again here
2247 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002248 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002249 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2250 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002251}
2252
Vishnu Nair4351ad52019-02-11 14:13:02 -08002253void SurfaceFlinger::computeLayerBounds() {
2254 for (const auto& pair : mDisplays) {
2255 const auto& displayDevice = pair.second;
2256 const auto display = displayDevice->getCompositionDisplay();
2257 for (const auto& layer : mDrawingState.layersSortedByZ) {
2258 // only consider the layers on the given layer stack
2259 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002260 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002261 }
2262
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002263 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2264 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002265 }
2266 }
2267}
2268
David Sodmanfa9b2af2017-12-24 13:28:59 -08002269void SurfaceFlinger::postFrame()
2270{
2271 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002272 const auto display = getDefaultDisplayDeviceLocked();
2273 if (display && getHwComposer().isConnected(*display->getId())) {
2274 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002275 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2276 logFrameStats();
2277 }
2278 }
2279}
2280
Mathias Agopian87baae12012-07-31 12:38:26 -07002281void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282{
Mathias Agopian841cde52012-03-01 15:44:37 -08002283 ATRACE_CALL();
2284
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002285 // here we keep a copy of the drawing state (that is the state that's
2286 // going to be overwritten by handleTransactionLocked()) outside of
2287 // mStateLock so that the side-effects of the State assignment
2288 // don't happen with mStateLock held (which can cause deadlocks).
2289 State drawingState(mDrawingState);
2290
Mathias Agopianca4d3602011-05-19 15:38:14 -07002291 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002292 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002293
Mathias Agopianca4d3602011-05-19 15:38:14 -07002294 // Here we're guaranteed that some transaction flags are set
2295 // so we can call handleTransactionLocked() unconditionally.
2296 // We call getTransactionFlags(), which will also clear the flags,
2297 // with mStateLock held to guarantee that mCurrentState won't change
2298 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002299
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002300 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002301 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002302 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002303
Mathias Agopianca4d3602011-05-19 15:38:14 -07002304 mDebugInTransaction = 0;
2305 invalidateHwcGeometry();
2306 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002307}
2308
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2310 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002311 const std::optional<DisplayIdentificationInfo> info =
2312 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002313
Dominik Laskowski075d3172018-05-24 15:50:06 -07002314 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315 continue;
2316 }
2317
Dominik Laskowski55c85402020-01-21 16:25:47 -08002318 const DisplayId displayId = info->id;
2319 const auto it = mPhysicalDisplayTokens.find(displayId);
2320
Lloyd Piqueba04e622017-12-14 17:11:26 -08002321 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002322 if (it == mPhysicalDisplayTokens.end()) {
2323 ALOGV("Creating display %s", to_string(displayId).c_str());
2324
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002325 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002326 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002327 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002328
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002330 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002331 state.isSecure = true; // All physical displays are currently considered secure.
2332 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002333
2334 sp<IBinder> token = new BBinder();
2335 mCurrentState.displays.add(token, state);
2336 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2337
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002339 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002341 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002342
Dominik Laskowski55c85402020-01-21 16:25:47 -08002343 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002344 if (index >= 0) {
2345 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2346 mInterceptor->saveDisplayDeletion(state.sequenceId);
2347 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002348 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002349 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350 }
2351
2352 processDisplayChangesLocked();
2353 }
2354
2355 mPendingHotplugEvents.clear();
2356}
2357
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002358void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002359 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2360 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002361}
2362
Lloyd Pique99d3da52018-01-22 17:48:03 -08002363sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002365 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002366 const sp<IGraphicBufferProducer>& producer) {
2367 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002368 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002369 creationArgs.isSecure = state.isSecure;
2370 creationArgs.displaySurface = dispSurface;
2371 creationArgs.hasWideColorGamut = false;
2372 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002373 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002374
Dominik Laskowski55c85402020-01-21 16:25:47 -08002375 if (const auto& physical = state.physical) {
2376 creationArgs.connectionType = physical->type;
2377 }
2378
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002379 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002380 creationArgs.isPrimary = isInternalDisplay;
2381
2382 if (useColorManagement && displayId) {
2383 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002385 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002386 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002387 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002388
Dominik Laskowski7e045462018-05-30 13:02:02 -07002389 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002391 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392 }
tangrobin6753a022018-08-10 10:58:54 +08002393 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 if (displayId) {
2396 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002397 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002399 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400
Lloyd Pique90c115d2018-09-18 21:39:42 -07002401 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002403 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405 // Make sure that composition can never be stalled by a virtual display
2406 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002407 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002408 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2410 }
2411
Dominik Laskowski718f9602019-11-09 20:01:35 -08002412 creationArgs.physicalOrientation =
2413 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002414
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002416 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417
Lloyd Pique90c115d2018-09-18 21:39:42 -07002418 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419
2420 if (maxFrameBufferAcquiredBuffers >= 3) {
2421 nativeWindowSurface->preallocateBuffers();
2422 }
2423
2424 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002425 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002426 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002428 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002430 display->getCompositionDisplay()->setColorProfile(
2431 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2432 RenderIntent::COLORIMETRIC,
2433 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434 if (!state.isVirtual()) {
2435 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002436 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2437 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002438 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 display->setLayerStack(state.layerStack);
2441 display->setProjection(state.orientation, state.viewport, state.frame);
2442 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445}
2446
Lloyd Pique347200f2017-12-14 17:00:15 -08002447void SurfaceFlinger::processDisplayChangesLocked() {
2448 // here we take advantage of Vector's copy-on-write semantics to
2449 // improve performance by skipping the transaction entirely when
2450 // know that the lists are identical
2451 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2452 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2453 if (!curr.isIdenticalTo(draw)) {
2454 mVisibleRegionsDirty = true;
2455 const size_t cc = curr.size();
2456 size_t dc = draw.size();
2457
2458 // find the displays that were removed
2459 // (ie: in drawing state but not in current state)
2460 // also handle displays that changed
2461 // (ie: displays that are in both lists)
2462 for (size_t i = 0; i < dc;) {
2463 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2464 if (j < 0) {
2465 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002466 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002467 // Save display ID before disconnecting.
2468 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002469 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002470
2471 if (!display->isVirtual()) {
2472 LOG_ALWAYS_FATAL_IF(!displayId);
2473 dispatchDisplayHotplugEvent(displayId->value, false);
2474 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002476
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002477 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 } else {
2479 // this display is in both lists. see if something changed.
2480 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002481 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2483 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2484 if (state_binder != draw_binder) {
2485 // changing the surface is like destroying and
2486 // recreating the DisplayDevice, so we just remove it
2487 // from the drawing state, so that it get re-added
2488 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002489 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002490 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002491 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002492 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 mDrawingState.displays.removeItemsAt(i);
2494 dc--;
2495 // at this point we must loop to the next item
2496 continue;
2497 }
2498
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 }
2503 if ((state.orientation != draw[i].orientation) ||
2504 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002505 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 }
2507 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002509 if (display->isPrimary()) {
2510 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2511 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002512 }
2513 }
2514 }
2515 ++i;
2516 }
2517
2518 // find displays that were added
2519 // (ie: in current state but not in drawing state)
2520 for (size_t i = 0; i < cc; i++) {
2521 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2522 const DisplayDeviceState& state(curr[i]);
2523
Lloyd Pique542307f2018-10-19 13:24:08 -07002524 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002525 sp<IGraphicBufferProducer> producer;
2526 sp<IGraphicBufferProducer> bqProducer;
2527 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002528 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002531 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002532 // Virtual displays without a surface are dormant:
2533 // they have external state (layer stack, projection,
2534 // etc.) but no internal state (i.e. a DisplayDevice).
2535 if (state.surface != nullptr) {
2536 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002538 int width = 0;
2539 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2540 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2541 int height = 0;
2542 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2543 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2544 int intFormat = 0;
2545 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2546 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002547 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002548
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 displayId =
2550 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002551 }
2552
2553 // TODO: Plumb requested format back up to consumer
2554
2555 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002557 bqProducer, bqConsumer,
2558 state.displayName);
2559
2560 dispSurface = vds;
2561 producer = vds;
2562 }
2563 } else {
2564 ALOGE_IF(state.surface != nullptr,
2565 "adding a supported display, but rendering "
2566 "surface is provided (%p), ignoring it",
2567 state.surface.get());
2568
Dominik Laskowski55c85402020-01-21 16:25:47 -08002569 LOG_FATAL_IF(!state.physical);
2570 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002572 producer = bqProducer;
2573 }
2574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002575 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002576 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002577 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002578 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002579 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002580 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002582 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002583 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002584
2585 const auto displayDevice = mDisplays[displayToken];
2586 if (displayDevice->isPrimary()) {
2587 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2588 displayDevice->getHeight());
2589 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002590 }
2591 }
2592 }
2593 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002594
2595 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002596}
2597
Mathias Agopian87baae12012-07-31 12:38:26 -07002598void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002599{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002600 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2601
Dan Stoza7dde5992015-05-22 09:51:44 -07002602 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002603 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002604 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002605 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002606
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607 /*
2608 * Traversal of the children
2609 * (perform the transaction for each of them if needed)
2610 */
2611
Marissa Wall06255332019-03-27 13:48:27 -07002612 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002613 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002615 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616
2617 const uint32_t flags = layer->doTransaction(0);
2618 if (flags & Layer::eVisibleRegion)
2619 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002620
2621 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002622 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002623 }
Robert Carr2047fae2016-11-28 14:09:09 -08002624 });
Marissa Wall06255332019-03-27 13:48:27 -07002625 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626 }
2627
2628 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002629 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 */
2631
Mathias Agopiane57f2922012-08-09 16:29:12 -07002632 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002633 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002634 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002635 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002637 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002638 // The transform hint might have changed for some layers
2639 // (either because a display has changed, or because a layer
2640 // as changed).
2641 //
2642 // Walk through all the layers in currentLayers,
2643 // and update their transform hint.
2644 //
2645 // If a layer is visible only on a single display, then that
2646 // display is used to calculate the hint, otherwise we use the
2647 // default display.
2648 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002649 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002650 // the hint is set before we acquire a buffer from the surface texture.
2651 //
2652 // NOTE: layer transactions have taken place already, so we use their
2653 // drawing state. However, SurfaceFlinger's own transaction has not
2654 // happened yet, so we must use the current state layer list
2655 // (soon to become the drawing state list).
2656 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002657 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002658 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002659 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002660 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002661 // NOTE: we rely on the fact that layers are sorted by
2662 // layerStack first (so we don't have to traverse the list
2663 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002665 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002666 currentlayerStack = layerStack;
2667 // figure out if this layerstack is mirrored
2668 // (more than one display) if so, pick the default display,
2669 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 hintDisplay = nullptr;
2671 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002672 if (display->getCompositionDisplay()
2673 ->belongsInOutput(layer->getLayerStack(),
2674 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002675 if (hintDisplay) {
2676 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002677 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002680 }
2681 }
2682 }
2683 }
Chet Haase91d25932013-04-11 15:24:55 -07002684
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002685 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002686 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2687 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002688
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002689 // could be null when this layer is using a layerStack
2690 // that is not visible on any display. Also can occur at
2691 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002692 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002693 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002694
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002695 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002696 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 if (hintDisplay) {
2698 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002699 }
Robert Carr2047fae2016-11-28 14:09:09 -08002700
2701 first = false;
2702 });
Mathias Agopian84300952012-11-21 16:02:13 -08002703 }
2704
2705
Mathias Agopian3559b072012-08-15 13:46:03 -07002706 /*
2707 * Perform our own transaction if needed
2708 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002709
2710 if (mLayersAdded) {
2711 mLayersAdded = false;
2712 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002713 mVisibleRegionsDirty = true;
2714 }
2715
2716 // some layers might have been removed, so
2717 // we need to update the regions they're exposing.
2718 if (mLayersRemoved) {
2719 mLayersRemoved = false;
2720 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002721 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002722 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002723 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002724 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002725 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002726 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002727 }
Robert Carr2047fae2016-11-28 14:09:09 -08002728 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729 }
2730
Vishnu Nairec0ab382019-02-13 15:32:56 -08002731 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002733}
2734
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002735void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002736 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002737 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002738 return;
2739 }
2740
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002741 if (mVisibleRegionsDirty || mInputInfoChanged) {
2742 mInputInfoChanged = false;
2743 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002744 } else if (mInputWindowCommands.syncInputWindows) {
2745 // If the caller requested to sync input windows, but there are no
2746 // changes to input windows, notify immediately.
2747 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002748 }
2749
Arthur Hung6cbb9752019-09-05 16:38:18 +08002750 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002751}
2752
2753void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002754 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002755
2756 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2757 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002758 // When calculating the screen bounds we ignore the transparent region since it may
2759 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002760 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002761 }
2762 });
chaviw291d88a2019-02-14 10:33:58 -08002763
2764 mInputFlinger->setInputWindows(inputHandles,
2765 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2766 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002767}
2768
Vishnu Nairec0ab382019-02-13 15:32:56 -08002769void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002770 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002771 mPendingInputWindowCommands.clear();
2772}
2773
Riley Andrews03414a12014-07-01 14:22:59 -07002774void SurfaceFlinger::updateCursorAsync()
2775{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002776 compositionengine::CompositionRefreshArgs refreshArgs;
2777 for (const auto& [_, display] : mDisplays) {
2778 if (display->getId()) {
2779 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002780 }
2781 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002782
2783 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002784}
2785
Ady Abraham2139f732019-11-13 18:56:40 -08002786void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002787 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2788 // If this is called from the main thread mStateLock must be locked before
2789 // Currently the only way to call this function from the main thread is from
2790 // Sheduler::chooseRefreshRateForContent
2791
2792 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002793 changeRefreshRateLocked(refreshRate, event);
2794}
2795
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002796void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2797 if (mScheduler) {
2798 // In practice it's not allowed to hotplug in/out the primary display once it's been
2799 // connected during startup, but some tests do it, so just warn and return.
2800 ALOGW("Can't re-init scheduler");
2801 return;
2802 }
2803
Ady Abraham2139f732019-11-13 18:56:40 -08002804 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002805 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002806 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002807 primaryDisplayId),
2808 currentConfig);
2809 mRefreshRateStats =
2810 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2811 currentConfig, HWC_POWER_MODE_OFF);
2812 mRefreshRateStats->setConfigMode(currentConfig);
2813
Ady Abraham9e16a482019-12-03 17:19:41 -08002814 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2815
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002816 // start the EventThread
2817 mScheduler =
2818 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002819 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002820 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002821 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002822 impl::EventThread::InterceptVSyncsCallback());
2823 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002824 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002825 [this](nsecs_t timestamp) {
2826 mInterceptor->saveVSyncEvent(timestamp);
2827 });
2828
2829 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2830 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002831 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002832
2833 mRegionSamplingThread =
2834 new RegionSamplingThread(*this, *mScheduler,
2835 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002836 // Dispatch a config change request for the primary display on scheduler
2837 // initialization, so that the EventThreads always contain a reference to a
2838 // prior configuration.
2839 //
2840 // This is a bit hacky, but this avoids a back-pointer into the main SF
2841 // classes from EventThread, and there should be no run-time binder cost
2842 // anyway since there are no connected apps at this point.
2843 const nsecs_t vsyncPeriod =
2844 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2845 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2846 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002847}
2848
Mathias Agopian4fec8732012-06-29 14:12:52 -07002849void SurfaceFlinger::commitTransaction()
2850{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002851 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002852
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002853 mTransactionPending = false;
2854 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856}
2857
Lloyd Pique58e24a32019-08-01 15:50:14 -07002858void SurfaceFlinger::commitTransactionLocked() {
2859 if (!mLayersPendingRemoval.isEmpty()) {
2860 // Notify removed layers now that they can't be drawn from
2861 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002862 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002863
2864 // Ensure any buffers set to display on any children are released.
2865 if (l->isRemovedFromCurrentState()) {
2866 l->latchAndReleaseBuffer();
2867 }
2868
2869 // If the layer has been removed and has no parent, then it will not be reachable
2870 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2871 // ensure we can copy its current to drawing state.
2872 if (!l->getParent()) {
2873 mOffscreenLayers.emplace(l.get());
2874 }
2875 }
2876 mLayersPendingRemoval.clear();
2877 }
2878
2879 // If this transaction is part of a window animation then the next frame
2880 // we composite should be considered an animation as well.
2881 mAnimCompositionPending = mAnimTransactionPending;
2882
2883 mDrawingState = mCurrentState;
2884 // clear the "changed" flags in current state
2885 mCurrentState.colorMatrixChanged = false;
2886
Edgar Arriaga844fa672020-01-16 14:21:42 -08002887 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002888 layer->commitChildList();
2889
2890 // If the layer can be reached when traversing mDrawingState, then the layer is no
2891 // longer offscreen. Remove the layer from the offscreenLayer set.
2892 if (mOffscreenLayers.count(layer)) {
2893 mOffscreenLayers.erase(layer);
2894 }
2895 });
2896
2897 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002898 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002899}
2900
Nataniel Borges2b796da2019-02-15 13:32:18 -08002901void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2902 if (mTracingEnabledChanged) {
2903 mTracingEnabled = mTracing.isEnabled();
2904 mTracingEnabledChanged = false;
2905 }
2906
2907 // Synchronize with Tracing thread
2908 std::unique_lock<std::mutex> lock;
2909 if (mTracingEnabled) {
2910 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2911 }
2912
2913 lockedOperation();
2914
2915 // Synchronize with Tracing thread
2916 if (mTracingEnabled) {
2917 lock.unlock();
2918 }
2919}
2920
chaviw74d90ad2019-04-26 14:45:26 -07002921void SurfaceFlinger::commitOffscreenLayers() {
2922 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002923 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002924 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2925 if (!trFlags) return;
2926
2927 layer->doTransaction(0);
2928 layer->commitChildList();
2929 });
2930 }
2931}
2932
Chia-I Wuab0c3192017-08-01 11:29:00 -07002933void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002934 for (const auto& [token, displayDevice] : mDisplays) {
2935 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002936 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002937 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002938 }
2939 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002940}
2941
Dan Stoza6b9454d2014-11-07 16:00:59 -08002942bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943{
Ady Abraham09bd3922019-04-08 10:44:56 -07002944 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 ALOGV("handlePageFlip");
2946
Brian Andersond6927fb2016-07-23 23:37:30 -07002947 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948
Mathias Agopian4fec8732012-06-29 14:12:52 -07002949 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002950 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002951 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002952
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002953 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2954
Eric Penner51c59cd2014-07-28 19:51:58 -07002955 // Store the set of layers that need updates. This set must not change as
2956 // buffers are being latched, as this could result in a deadlock.
2957 // Example: Two producers share the same command stream and:
2958 // 1.) Layer 0 is latched
2959 // 2.) Layer 0 gets a new frame
2960 // 2.) Layer 1 gets a new frame
2961 // 3.) Layer 1 is latched.
2962 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2963 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002964 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002965 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002966 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002967 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002968 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002969 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002970 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002971 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002972 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002973 } else {
2974 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002975 }
Robert Carr2047fae2016-11-28 14:09:09 -08002976 });
2977
chaviw49a108c2019-08-12 11:23:06 -07002978 // The client can continue submitting buffers for offscreen layers, but they will not
2979 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2980 // layers to ensure dequeueBuffer doesn't block indefinitely.
2981 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002982 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002983 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2984 }
2985
Lloyd Piquef2c79392018-12-20 16:23:33 -08002986 if (!mLayersWithQueuedFrames.empty()) {
2987 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2988 // writes to Layer current state. See also b/119481871
2989 Mutex::Autolock lock(mStateLock);
2990
2991 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002992 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002993 mLayersPendingRefresh.push_back(layer);
2994 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002995 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002996 if (layer->isBufferLatched()) {
2997 newDataLatched = true;
2998 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003001
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003002 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003003
3004 // If we will need to wake up at some time in the future to deal with a
3005 // queued frame that shouldn't be displayed during this vsync period, wake
3006 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003007 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003008 signalLayerUpdate();
3009 }
3010
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003011 // enter boot animation on first buffer latch
3012 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3013 ALOGI("Enter boot animation");
3014 mBootStage = BootStage::BOOTANIMATION;
3015 }
3016
Edgar Arriaga844fa672020-01-16 14:21:42 -08003017 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003018
Dan Stoza6b9454d2014-11-07 16:00:59 -08003019 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003020 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021}
3022
Mathias Agopianad456f92011-01-13 17:53:01 -08003023void SurfaceFlinger::invalidateHwcGeometry()
3024{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003026}
3027
Robert Carrc0df3122019-04-11 13:18:21 -07003028status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3029 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3030 const sp<IBinder>& parentHandle,
3031 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003032 // add this layer to the current state list
3033 {
3034 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003035 sp<Layer> parent;
3036 if (parentHandle != nullptr) {
3037 parent = fromHandle(parentHandle);
3038 if (parent == nullptr) {
3039 return NAME_NOT_FOUND;
3040 }
3041 } else {
3042 parent = parentLayer;
3043 }
3044
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003046 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003047 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003048 return NO_MEMORY;
3049 }
Robert Carrc0df3122019-04-11 13:18:21 -07003050
3051 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3052
Robert Carrb89ea9d2018-12-10 13:01:14 -08003053 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003054 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003055 } else if (parent == nullptr) {
3056 lbc->onRemovedFromCurrentState();
3057 } else if (parent->isRemovedFromCurrentState()) {
3058 parent->addChild(lbc);
3059 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003060 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003061 parent->addChild(lbc);
3062 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003063
Yiwei Zhang243b3782018-05-15 17:40:04 -07003064 if (gbc != nullptr) {
3065 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3066 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3067 mMaxGraphicBufferProducerListSize,
3068 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3069 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003070 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003071 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3072 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3073 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3074 mNumLayers.load());
3075 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003076 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003077 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003078 }
3079
Mathias Agopian96f08192010-06-02 23:28:45 -07003080 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003081 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003082
Dan Stoza7d89d062015-04-30 13:29:25 -07003083 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003084}
3085
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003086uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003087 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003088}
3089
Mathias Agopian3f844832013-08-07 21:24:32 -07003090uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003091 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092}
3093
Mathias Agopian3f844832013-08-07 21:24:32 -07003094uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003095 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003096}
3097
3098uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003099 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003100 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003101 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003103 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 }
3105 return old;
3106}
3107
Marissa Wall713b63f2018-10-17 15:42:43 -07003108bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003109 // to prevent onHandleDestroyed from being called while the lock is held,
3110 // we must keep a copy of the transactions (specifically the composer
3111 // states) around outside the scope of the lock
3112 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003113 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003114 {
3115 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003116
Valerie Haufce31b82019-04-30 16:41:14 -07003117 auto it = mTransactionQueues.begin();
3118 while (it != mTransactionQueues.end()) {
3119 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003120
Valerie Haufce31b82019-04-30 16:41:14 -07003121 while (!transactionQueue.empty()) {
3122 const auto& transaction = transactionQueue.front();
3123 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003124 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003125 transaction.states)) {
3126 setTransactionFlags(eTransactionFlushNeeded);
3127 break;
3128 }
3129 transactions.push_back(transaction);
3130 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3131 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003132 transaction.buffer, transaction.postTime,
3133 transaction.privileged, transaction.hasListenerCallbacks,
3134 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003135 transactionQueue.pop();
3136 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003137 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003138
Valerie Haufce31b82019-04-30 16:41:14 -07003139 if (transactionQueue.empty()) {
3140 it = mTransactionQueues.erase(it);
3141 mTransactionCV.broadcast();
3142 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003143 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003144 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003145 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003146 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003147 return flushedATransaction;
3148}
3149
3150bool SurfaceFlinger::transactionFlushNeeded() {
3151 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003152}
3153
chaviwca27f252018-02-06 16:46:39 -08003154
Marissa Wall17b4e452018-12-26 16:32:34 -08003155bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003156 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003157 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003158 if (!useCachedExpectedPresentTime)
3159 populateExpectedPresentTime();
3160
3161 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003162 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3163 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3164 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3165 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3166 return false;
3167 }
3168
Marissa Wall713b63f2018-10-17 15:42:43 -07003169 for (const ComposerState& state : states) {
3170 const layer_state_t& s = state.state;
3171 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3172 continue;
3173 }
3174 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003175 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003176 }
3177 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003178 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003179}
3180
Valerie Hau9dab9732019-08-20 09:29:25 -07003181void SurfaceFlinger::setTransactionState(
3182 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3183 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3184 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3185 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003186 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003187
Valerie Haubc6ddb12019-03-08 11:10:15 -08003188 const int64_t postTime = systemTime();
3189
Robert Carr14167e02019-02-13 13:50:55 -08003190 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3191
Mathias Agopian698c0872011-06-28 19:09:31 -07003192 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003193
Marissa Wall713b63f2018-10-17 15:42:43 -07003194 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003195 auto itr = mTransactionQueues.find(applyToken);
3196 // if this is an animation frame, wait until prior animation frame has
3197 // been applied by SF
3198 if (flags & eAnimation) {
3199 while (itr != mTransactionQueues.end()) {
3200 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3201 if (CC_UNLIKELY(err != NO_ERROR)) {
3202 ALOGW_IF(err == TIMED_OUT,
3203 "setTransactionState timed out "
3204 "waiting for animation frame to apply");
3205 break;
3206 }
3207 itr = mTransactionQueues.find(applyToken);
3208 }
3209 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003210
3211 // Expected present time is computed and cached on invalidate, so it may be stale.
3212 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3213 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003214 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003215 uncacheBuffer, postTime, privileged,
3216 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003217 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003218 return;
3219 }
3220
Valerie Haubc6ddb12019-03-08 11:10:15 -08003221 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003222 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3223 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003224}
3225
Valerie Hau9dab9732019-08-20 09:29:25 -07003226void SurfaceFlinger::applyTransactionState(
3227 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3228 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3229 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3230 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3231 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003232 uint32_t transactionFlags = 0;
3233
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003234 if (flags & eAnimation) {
3235 // For window updates that are part of an animation we must wait for
3236 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003237 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003238 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003239 if (CC_UNLIKELY(err != NO_ERROR)) {
3240 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003241 // caller after a few seconds.
3242 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3243 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003244 mAnimTransactionPending = false;
3245 break;
3246 }
3247 }
3248 }
3249
chaviwca27f252018-02-06 16:46:39 -08003250 for (const DisplayState& display : displays) {
3251 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003252 }
3253
Valerie Hau9dab9732019-08-20 09:29:25 -07003254 // start and end registration for listeners w/ no surface so they can get their callback. Note
3255 // that listeners with SurfaceControls will start registration during setClientStateLocked
3256 // below.
3257 for (const auto& listener : listenerCallbacks) {
3258 mTransactionCompletedThread.startRegistration(listener);
3259 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003260 }
3261
Valerie Hau9dab9732019-08-20 09:29:25 -07003262 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003263 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003264 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003265 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3266 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003267 }
3268
Valerie Hau9dab9732019-08-20 09:29:25 -07003269 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003270 mTransactionCompletedThread.endRegistration(listenerCallback);
3271 }
3272
Marissa Walle2ffb422018-10-12 11:33:52 -07003273 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003274 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003275 mTransactionCompletedThread.sendCallbacks();
3276 }
3277 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003278
chaviw273171b2018-12-26 11:46:30 -08003279 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3280
Marissa Wall947d34e2019-03-29 14:03:53 -07003281 if (uncacheBuffer.isValid()) {
3282 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003283 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003284 }
3285
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003286 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3287 // anyway. This can be used as a flush mechanism for previous async transactions.
3288 // Empty animation transaction can be used to simulate back-pressure, so also force a
3289 // transaction for empty animation transactions.
3290 if (transactionFlags == 0 &&
3291 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003292 transactionFlags = eTransactionNeeded;
3293 }
3294
Marissa Wall06255332019-03-27 13:48:27 -07003295 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3296 // so we don't have to wake up again next frame to preform an uneeded traversal.
3297 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3298 transactionFlags = transactionFlags & (~eTraversalNeeded);
3299 mTraversalNeededMainThread = true;
3300 }
3301
Mathias Agopian386aa982011-11-07 21:58:03 -08003302 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003303 if (mInterceptor->isEnabled()) {
3304 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003305 }
Irvel468051e2016-06-13 16:44:44 -07003306
Mathias Agopian386aa982011-11-07 21:58:03 -08003307 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003308 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3309 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003310 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003311
3312 // if this is a synchronous transaction, wait for it to take effect
3313 // before returning.
3314 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003315 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003316 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003317 if (flags & eAnimation) {
3318 mAnimTransactionPending = true;
3319 }
chaviw4fe36852019-04-15 16:25:49 -07003320 if (mPendingInputWindowCommands.syncInputWindows) {
3321 mPendingSyncInputWindows = true;
3322 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003323
3324 // applyTransactionState can be called by either the main SF thread or by
3325 // another process through setTransactionState. While a given process may wish
3326 // to wait on synchronous transactions, the main SF thread should never
3327 // be blocked. Therefore, we only wait if isMainThread is false.
3328 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3330 if (CC_UNLIKELY(err != NO_ERROR)) {
3331 // just in case something goes wrong in SF, return to the
3332 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003333 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3334 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003335 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003336 break;
3337 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003338 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339 }
3340}
3341
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003342uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3343 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3344 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003345
Mathias Agopiane57f2922012-08-09 16:29:12 -07003346 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003347 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3348
3349 const uint32_t what = s.what;
3350 if (what & DisplayState::eSurfaceChanged) {
3351 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3352 state.surface = s.surface;
3353 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003354 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003355 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003356 if (what & DisplayState::eLayerStackChanged) {
3357 if (state.layerStack != s.layerStack) {
3358 state.layerStack = s.layerStack;
3359 flags |= eDisplayTransactionNeeded;
3360 }
3361 }
3362 if (what & DisplayState::eDisplayProjectionChanged) {
3363 if (state.orientation != s.orientation) {
3364 state.orientation = s.orientation;
3365 flags |= eDisplayTransactionNeeded;
3366 }
3367 if (state.frame != s.frame) {
3368 state.frame = s.frame;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 if (state.viewport != s.viewport) {
3372 state.viewport = s.viewport;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 }
3376 if (what & DisplayState::eDisplaySizeChanged) {
3377 if (state.width != s.width) {
3378 state.width = s.width;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 if (state.height != s.height) {
3382 state.height = s.height;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 }
3386
Mathias Agopiane57f2922012-08-09 16:29:12 -07003387 return flags;
3388}
3389
Robert Carr14167e02019-02-13 13:50:55 -08003390bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003391 IPCThreadState* ipc = IPCThreadState::self();
3392 const int pid = ipc->getCallingPid();
3393 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003394 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003395 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003396 return false;
3397 }
3398 return true;
3399}
3400
Marissa Wall3dad52d2019-03-22 14:03:19 -07003401uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003402 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3403 bool privileged,
3404 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003405 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003406
Valerie Hau9dab9732019-08-20 09:29:25 -07003407 for (auto& listener : s.listeners) {
3408 // note that startRegistration will not re-register if the listener has
3409 // already be registered for a prior surface control
3410 mTransactionCompletedThread.startRegistration(listener);
3411 listenerCallbacks.insert(listener);
3412 }
3413
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003414 sp<Layer> layer = nullptr;
3415 if (s.surface) {
3416 layer = fromHandle(s.surface);
3417 } else {
3418 // The client may provide us a null handle. Treat it as if the layer was removed.
3419 ALOGW("Attempt to set client state with a null layer handle");
3420 }
chaviw8b3871a2017-11-01 17:41:01 -07003421 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003422 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003423 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003424 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003425 }
chaviw8b3871a2017-11-01 17:41:01 -07003426 return 0;
3427 }
3428
chaviw8b3871a2017-11-01 17:41:01 -07003429 uint32_t flags = 0;
3430
Garfield Tan8a3083e2018-12-03 13:21:07 -08003431 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003432
3433 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3434 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003435 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003436 layer->pushPendingState();
3437 }
3438
Valerie Hau871d6352020-01-29 08:44:02 -08003439 // Only set by BLAST adapter layers
3440 if (what & layer_state_t::eProducerDisconnect) {
3441 layer->onDisconnect();
3442 }
3443
chaviw8b3871a2017-11-01 17:41:01 -07003444 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003445 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003446 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 }
3449 if (what & layer_state_t::eLayerChanged) {
3450 // NOTE: index needs to be calculated before we update the state
3451 const auto& p = layer->getParent();
3452 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003453 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003454 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003455 mCurrentState.layersSortedByZ.removeAt(idx);
3456 mCurrentState.layersSortedByZ.add(layer);
3457 // we need traversal (state changed)
3458 // AND transaction (list changed)
3459 flags |= eTransactionNeeded|eTraversalNeeded;
3460 }
chaviw8b3871a2017-11-01 17:41:01 -07003461 } else {
3462 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003463 flags |= eTransactionNeeded|eTraversalNeeded;
3464 }
3465 }
chaviw8b3871a2017-11-01 17:41:01 -07003466 }
3467 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003468 // NOTE: index needs to be calculated before we update the state
3469 const auto& p = layer->getParent();
3470 if (p == nullptr) {
3471 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3472 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3473 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 }
3479 } else {
3480 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3481 flags |= eTransactionNeeded|eTraversalNeeded;
3482 }
chaviw8b3871a2017-11-01 17:41:01 -07003483 }
3484 }
3485 if (what & layer_state_t::eSizeChanged) {
3486 if (layer->setSize(s.w, s.h)) {
3487 flags |= eTraversalNeeded;
3488 }
3489 }
3490 if (what & layer_state_t::eAlphaChanged) {
3491 if (layer->setAlpha(s.alpha))
3492 flags |= eTraversalNeeded;
3493 }
3494 if (what & layer_state_t::eColorChanged) {
3495 if (layer->setColor(s.color))
3496 flags |= eTraversalNeeded;
3497 }
Peiyong Lind3788632018-09-18 16:01:31 -07003498 if (what & layer_state_t::eColorTransformChanged) {
3499 if (layer->setColorTransform(s.colorTransform)) {
3500 flags |= eTraversalNeeded;
3501 }
3502 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003503 if (what & layer_state_t::eBackgroundColorChanged) {
3504 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3505 flags |= eTraversalNeeded;
3506 }
3507 }
chaviw8b3871a2017-11-01 17:41:01 -07003508 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003509 // TODO: b/109894387
3510 //
3511 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3512 // rotation. To see the problem observe that if we have a square parent, and a child
3513 // of the same size, then we rotate the child 45 degrees around it's center, the child
3514 // must now be cropped to a non rectangular 8 sided region.
3515 //
3516 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3517 // private API, and the WindowManager only uses rotation in one case, which is on a top
3518 // level layer in which cropping is not an issue.
3519 //
3520 // However given that abuse of rotation matrices could lead to surfaces extending outside
3521 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3522 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3523 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003524 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003525 flags |= eTraversalNeeded;
3526 }
3527 if (what & layer_state_t::eTransparentRegionChanged) {
3528 if (layer->setTransparentRegionHint(s.transparentRegion))
3529 flags |= eTraversalNeeded;
3530 }
3531 if (what & layer_state_t::eFlagsChanged) {
3532 if (layer->setFlags(s.flags, s.mask))
3533 flags |= eTraversalNeeded;
3534 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003535 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003536 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003537 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003538 if (what & layer_state_t::eCornerRadiusChanged) {
3539 if (layer->setCornerRadius(s.cornerRadius))
3540 flags |= eTraversalNeeded;
3541 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003542 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3543 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3544 }
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (what & layer_state_t::eLayerStackChanged) {
3546 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3547 // We only allow setting layer stacks for top level layers,
3548 // everything else inherits layer stack from its parent.
3549 if (layer->hasParent()) {
3550 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003551 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003552 } else if (idx < 0) {
3553 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003554 "that also does not appear in the top level layer list. Something"
3555 " has gone wrong.",
3556 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003557 } else if (layer->setLayerStack(s.layerStack)) {
3558 mCurrentState.layersSortedByZ.removeAt(idx);
3559 mCurrentState.layersSortedByZ.add(layer);
3560 // we need traversal (state changed)
3561 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003562 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003563 }
3564 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003565 if (what & layer_state_t::eDeferTransaction_legacy) {
3566 if (s.barrierHandle_legacy != nullptr) {
3567 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3568 } else if (s.barrierGbp_legacy != nullptr) {
3569 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003570 if (authenticateSurfaceTextureLocked(gbp)) {
3571 const auto& otherLayer =
3572 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003573 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003574 } else {
3575 ALOGE("Attempt to defer transaction to to an"
3576 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003577 }
3578 }
chaviw8b3871a2017-11-01 17:41:01 -07003579 // We don't trigger a traversal here because if no other state is
3580 // changed, we don't want this to cause any more work
3581 }
chaviw8b3871a2017-11-01 17:41:01 -07003582 if (what & layer_state_t::eReparentChildren) {
3583 if (layer->reparentChildren(s.reparentHandle)) {
3584 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003585 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586 }
chaviw8b3871a2017-11-01 17:41:01 -07003587 if (what & layer_state_t::eDetachChildren) {
3588 layer->detachChildren();
3589 }
3590 if (what & layer_state_t::eOverrideScalingModeChanged) {
3591 layer->setOverrideScalingMode(s.overrideScalingMode);
3592 // We don't trigger a traversal here because if no other state is
3593 // changed, we don't want this to cause any more work
3594 }
Marissa Wall61c58622018-07-18 10:12:20 -07003595 if (what & layer_state_t::eTransformChanged) {
3596 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3597 }
3598 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3599 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3600 flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eCropChanged) {
3603 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3604 }
Marissa Wall861616d2018-10-22 12:52:23 -07003605 if (what & layer_state_t::eFrameChanged) {
3606 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3607 }
Marissa Wall61c58622018-07-18 10:12:20 -07003608 if (what & layer_state_t::eAcquireFenceChanged) {
3609 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3610 }
3611 if (what & layer_state_t::eDataspaceChanged) {
3612 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3613 }
3614 if (what & layer_state_t::eHdrMetadataChanged) {
3615 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3616 }
3617 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3618 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3619 }
3620 if (what & layer_state_t::eApiChanged) {
3621 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3622 }
3623 if (what & layer_state_t::eSidebandStreamChanged) {
3624 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3625 }
Robert Carr720e5062018-07-30 17:45:14 -07003626 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003627 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003628 layer->setInputInfo(s.inputInfo);
3629 flags |= eTraversalNeeded;
3630 } else {
3631 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3632 }
Robert Carr720e5062018-07-30 17:45:14 -07003633 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003634 if (what & layer_state_t::eMetadataChanged) {
3635 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3636 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003637 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3638 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3639 flags |= eTraversalNeeded;
3640 }
3641 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003642 if (what & layer_state_t::eShadowRadiusChanged) {
3643 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3644 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003645 if (what & layer_state_t::eFrameRateSelectionPriority) {
3646 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3647 flags |= eTraversalNeeded;
3648 }
3649 }
Steven Thomas3172e202020-01-06 19:25:30 -08003650 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003651 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3652 "SurfaceFlinger::setClientStateLocked") &&
3653 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3654 Layer::FrameRate::convertCompatibility(
3655 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003656 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003657 }
Steven Thomas3172e202020-01-06 19:25:30 -08003658 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003659 // This has to happen after we reparent children because when we reparent to null we remove
3660 // child layers from current state and remove its relative z. If the children are reparented in
3661 // the same transaction, then we have to make sure we reparent the children first so we do not
3662 // lose its relative z order.
3663 if (what & layer_state_t::eReparent) {
3664 bool hadParent = layer->hasParent();
3665 if (layer->reparent(s.parentHandleForChild)) {
3666 if (!hadParent) {
3667 mCurrentState.layersSortedByZ.remove(layer);
3668 }
3669 flags |= eTransactionNeeded | eTraversalNeeded;
3670 }
3671 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003672 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003673 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3674 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003675 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3676 }
3677 }
Marissa Wall78b72202019-03-15 14:58:34 -07003678 bool bufferChanged = what & layer_state_t::eBufferChanged;
3679 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3680 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003681 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003682 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003683 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3684 if (success) {
3685 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3686 success = ClientCache::getInstance()
3687 .registerErasedRecipient(s.cachedBuffer,
3688 wp<ClientCache::ErasedRecipient>(this));
3689 if (!success) {
3690 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3691 }
3692 }
Marissa Wall78b72202019-03-15 14:58:34 -07003693 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003694 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003695 } else if (bufferChanged) {
3696 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003697 }
Marissa Wall78b72202019-03-15 14:58:34 -07003698 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003699 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3700 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003701 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003702 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003703 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003704 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3705 // Do not put anything that updates layer state or modifies flags after
3706 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003707 return flags;
3708}
3709
chaviw273171b2018-12-26 11:46:30 -08003710uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3711 uint32_t flags = 0;
3712 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3713 flags |= eTraversalNeeded;
3714 }
3715
chaviwa911b102019-02-14 10:18:33 -08003716 if (inputWindowCommands.syncInputWindows) {
3717 flags |= eTraversalNeeded;
3718 }
3719
Vishnu Nairec0ab382019-02-13 15:32:56 -08003720 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003721 return flags;
3722}
3723
chaviwfe94a222019-08-21 13:52:59 -07003724status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3725 sp<IBinder>* outHandle) {
3726 if (!mirrorFromHandle) {
3727 return NAME_NOT_FOUND;
3728 }
3729
3730 sp<Layer> mirrorLayer;
3731 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003732 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003733
3734 {
3735 Mutex::Autolock _l(mStateLock);
3736 mirrorFrom = fromHandle(mirrorFromHandle);
3737 if (!mirrorFrom) {
3738 return NAME_NOT_FOUND;
3739 }
3740
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003741 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3742 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003743 if (result != NO_ERROR) {
3744 return result;
3745 }
3746
3747 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3748 }
3749
3750 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3751}
3752
Marissa Wall2d814fb2019-04-09 18:52:57 +00003753status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3754 uint32_t h, PixelFormat format, uint32_t flags,
3755 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003756 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003757 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3758 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003759 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003760 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003761 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003762 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003763 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003764
Robert Carrc0df3122019-04-11 13:18:21 -07003765 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3766 "Expected only one of parentLayer or parentHandle to be non-null. "
3767 "Programmer error?");
3768
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003769 status_t result = NO_ERROR;
3770
3771 sp<Layer> layer;
3772
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003773 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003774
Evan Roskya1f1e152019-01-24 16:17:46 -08003775 bool primaryDisplayOnly = false;
3776
3777 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3778 // TODO b/64227542
3779 if (metadata.has(METADATA_WINDOW_TYPE)) {
3780 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3781 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003782 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003783 primaryDisplayOnly = true;
3784 }
3785 }
3786
Mathias Agopian3165cc22012-08-08 19:42:09 -07003787 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003788 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003789 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3790 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003791
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003792 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003793 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003794 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003795 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003796 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003797 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003798 // check if buffer size is set for color layer.
3799 if (w > 0 || h > 0) {
3800 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3801 int(w), int(h));
3802 return BAD_VALUE;
3803 }
3804
Vishnu Nairfa247b12020-02-11 08:58:26 -08003805 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3806 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003807 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003808 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003809 // check if buffer size is set for container layer.
3810 if (w > 0 || h > 0) {
3811 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3812 int(w), int(h));
3813 return BAD_VALUE;
3814 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003815 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3816 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003817 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003818 default:
3819 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820 break;
3821 }
3822
Dan Stoza7d89d062015-04-30 13:29:25 -07003823 if (result != NO_ERROR) {
3824 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003825 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003826
Evan Roskya1f1e152019-01-24 16:17:46 -08003827 if (primaryDisplayOnly) {
3828 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003829 }
3830
Robert Carrb89ea9d2018-12-10 13:01:14 -08003831 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003832 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3833 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003834 if (result != NO_ERROR) {
3835 return result;
3836 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003837 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003838
3839 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003840 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003841}
3842
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003843std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3844 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003845
3846 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003847 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003848
Dan Stoza436ccf32018-06-21 12:10:12 -07003849 // Grab the state lock since we're accessing mCurrentState
3850 Mutex::Autolock lock(mStateLock);
3851
Cody Northropbc755282017-03-31 12:00:08 -06003852 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003853 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003854 while (matchFound) {
3855 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003856 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003857 if (layer->getName() == uniqueName) {
3858 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003859 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003860 }
3861 });
3862 }
3863
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003864 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003865 return uniqueName;
3866}
3867
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003868status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003869 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003870 LayerMetadata metadata, PixelFormat& format,
3871 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003872 sp<IGraphicBufferProducer>* gbp,
3873 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003874 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003875 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003876 case PIXEL_FORMAT_TRANSPARENT:
3877 case PIXEL_FORMAT_TRANSLUCENT:
3878 format = PIXEL_FORMAT_RGBA_8888;
3879 break;
3880 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003881 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 break;
3883 }
3884
chaviwb4c6e582019-08-16 14:35:07 -07003885 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003886 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003887 args.textureName = getNewTexture();
3888 {
3889 // Grab the SF state lock during this since it's the only safe way to access
3890 // RenderEngine when creating a BufferLayerConsumer
3891 // TODO: Check if this lock is still needed here
3892 Mutex::Autolock lock(mStateLock);
3893 layer = getFactory().createBufferQueueLayer(args);
3894 }
3895
Marissa Wallfd668622018-05-10 10:21:13 -07003896 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003897 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003898 *handle = layer->getHandle();
3899 *gbp = layer->getProducer();
3900 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003902
Marissa Wallfd668622018-05-10 10:21:13 -07003903 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003904 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905}
3906
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003907status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003908 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003909 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003910 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003911 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003912 args.displayDevice = getDefaultDisplayDevice();
3913 args.textureName = getNewTexture();
3914 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003915 if (outTransformHint) {
3916 *outTransformHint = layer->getTransformHint();
3917 }
Marissa Wall61c58622018-07-18 10:12:20 -07003918 *handle = layer->getHandle();
3919 *outLayer = layer;
3920
3921 return NO_ERROR;
3922}
3923
Vishnu Nairfa247b12020-02-11 08:58:26 -08003924status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3925 uint32_t h, uint32_t flags, LayerMetadata metadata,
3926 sp<IBinder>* handle, sp<Layer>* outLayer) {
3927 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003928 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003929 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003930 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003931}
3932
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003933status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003934 uint32_t w, uint32_t h, uint32_t flags,
3935 LayerMetadata metadata, sp<IBinder>* handle,
3936 sp<Layer>* outLayer) {
3937 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003938 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003939 *handle = (*outLayer)->getHandle();
3940 return NO_ERROR;
3941}
3942
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003943void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003944 mLayersPendingRemoval.add(layer);
3945 mLayersRemoved = true;
3946 setTransactionFlags(eTransactionNeeded);
3947}
3948
Robert Carr695d5282018-12-18 15:27:58 -08003949void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003950{
Robert Carr2e102c92018-10-23 12:11:15 -07003951 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003952 // If a layer has a parent, we allow it to out-live it's handle
3953 // with the idea that the parent holds a reference and will eventually
3954 // be cleaned up. However no one cleans up the top-level so we do so
3955 // here.
3956 if (layer->getParent() == nullptr) {
3957 mCurrentState.layersSortedByZ.remove(layer);
3958 }
3959 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003960
3961 auto it = mLayersByLocalBinderToken.begin();
3962 while (it != mLayersByLocalBinderToken.end()) {
3963 if (it->second == layer) {
3964 it = mLayersByLocalBinderToken.erase(it);
3965 } else {
3966 it++;
3967 }
3968 }
3969
Robert Carr695d5282018-12-18 15:27:58 -08003970 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003971}
3972
Mathias Agopianb60314a2012-04-10 22:09:54 -07003973// ---------------------------------------------------------------------------
3974
Andy McFadden13a082e2012-08-24 10:16:42 -07003975void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003976 const auto display = getDefaultDisplayDeviceLocked();
3977 if (!display) return;
3978
3979 const sp<IBinder> token = display->getDisplayToken().promote();
3980 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003981
Jesse Hall01e29052013-02-19 16:13:35 -08003982 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003983 Vector<ComposerState> state;
3984 Vector<DisplayState> displays;
3985 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003986 d.what = DisplayState::eDisplayProjectionChanged |
3987 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003988 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003989 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003990 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003991 d.frame.makeInvalid();
3992 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003993 d.width = 0;
3994 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003995 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003996 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3997 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003998
Dominik Laskowskie9774092018-12-11 10:04:24 -08003999 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004000
Dominik Laskowski83b88212018-12-11 13:34:06 -08004001 const nsecs_t vsyncPeriod = getVsyncPeriod();
4002 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004003
Brian Andersond0010582017-03-07 13:20:31 -08004004 // Use phase of 0 since phase is not known.
4005 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004006 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004007 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004008}
4009
4010void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004011 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004012 postMessageAsync(
4013 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004014}
4015
Ady Abraham27c70212019-06-11 10:52:26 -07004016void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4017 if (mHWCVsyncState != enabled) {
4018 getHwComposer().setVsyncEnabled(displayId, enabled);
4019 mHWCVsyncState = enabled;
4020 }
4021}
4022
Dominik Laskowskie9774092018-12-11 10:04:24 -08004023void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004024 if (display->isVirtual()) {
4025 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004026 return;
4027 }
4028
Dominik Laskowski075d3172018-05-24 15:50:06 -07004029 const auto displayId = display->getId();
4030 LOG_ALWAYS_FATAL_IF(!displayId);
4031
Dominik Laskowski34157762018-10-31 13:07:19 -07004032 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004033
4034 int currentMode = display->getPowerMode();
4035 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004036 return;
4037 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004039 display->setPowerMode(mode);
4040
Lloyd Pique4dccc412018-01-22 17:21:36 -08004041 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004042 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004043 }
4044
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004045 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004046 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004047 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004048 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004049 mScheduler->onScreenAcquired(mAppConnectionHandle);
4050 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004051 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004052
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004053 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004054 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004055 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004056
4057 struct sched_param param = {0};
4058 param.sched_priority = 1;
4059 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4060 ALOGW("Couldn't set SCHED_FIFO on display on");
4061 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004062 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004063 // Turn off the display
4064 struct sched_param param = {0};
4065 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4066 ALOGW("Couldn't set SCHED_OTHER on display off");
4067 }
4068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004069 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004070 mScheduler->disableHardwareVsync(true);
4071 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004072 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004073
Ady Abraham27c70212019-06-11 10:52:26 -07004074 // Make sure HWVsync is disabled before turning off the display
4075 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4076
Dominik Laskowski075d3172018-05-24 15:50:06 -07004077 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004078 mVisibleRegionsDirty = true;
4079 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004080 } else if (mode == HWC_POWER_MODE_DOZE ||
4081 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004082 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004083 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004084 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004085 mScheduler->onScreenAcquired(mAppConnectionHandle);
4086 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004087 }
4088 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4089 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004090 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004091 mScheduler->disableHardwareVsync(true);
4092 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004093 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004094 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004095 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004096 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004097 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004098 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004099
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004100 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004101 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004102 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004103 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004104 }
4105
Dominik Laskowski34157762018-10-31 13:07:19 -07004106 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004107}
4108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004109void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004110 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004111 const auto display = getDisplayDevice(displayToken);
4112 if (!display) {
4113 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4114 displayToken.get());
4115 } else if (display->isVirtual()) {
4116 ALOGW("Attempt to set power mode %d for virtual display", mode);
4117 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004118 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004119 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004120 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004121}
4122
4123// ---------------------------------------------------------------------------
4124
Dominik Laskowskic2867142019-01-21 11:33:38 -08004125status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4126 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004127 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004128
Mathias Agopianbd115332013-04-18 16:41:04 -07004129 IPCThreadState* ipc = IPCThreadState::self();
4130 const int pid = ipc->getCallingPid();
4131 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004132
Mathias Agopianbd115332013-04-18 16:41:04 -07004133 if ((uid != AID_SHELL) &&
4134 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004135 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4136 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004138 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004139 // (this would indicate SF is stuck, but we want to be able to
4140 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004141 status_t err = mStateLock.timedLock(s2ns(1));
4142 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004143 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004144 StringAppendF(&result,
4145 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4146 "(no locks held)\n",
4147 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004148 }
4149
Dominik Laskowskic2867142019-01-21 11:33:38 -08004150 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004151 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004152 {"--dispsync"s,
4153 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004154 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004155 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4156 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4157 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4158 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4159 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4160 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004161 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004162 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4163 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004164
Dominik Laskowskic2867142019-01-21 11:33:38 -08004165 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004166
Dominik Laskowski46470112019-08-02 13:13:11 -07004167 const auto it = dumpers.find(flag);
4168 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004169 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004170 } else if (!asProto) {
4171 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004172 }
4173
Mathias Agopian9795c422009-08-26 16:36:26 -07004174 if (locked) {
4175 mStateLock.unlock();
4176 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004177
Dominik Laskowski46470112019-08-02 13:13:11 -07004178 if (it == dumpers.end()) {
4179 const LayersProto layersProto = dumpProtoFromMainThread();
4180 if (asProto) {
4181 result.append(layersProto.SerializeAsString());
4182 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004183 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004184 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4185 result.append(LayerProtoParser::layerTreeToString(layerTree));
4186 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004187 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004188 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004189 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004191 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192 return NO_ERROR;
4193}
4194
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004195status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4196 if (asProto && mTracing.isEnabled()) {
4197 mTracing.writeToFileAsync();
4198 }
4199
4200 return doDump(fd, DumpArgs(), asProto);
4201}
4202
Dominik Laskowskic2867142019-01-21 11:33:38 -08004203void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004204 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004205 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004206}
4207
Dominik Laskowskic2867142019-01-21 11:33:38 -08004208void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004209 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004210
Dominik Laskowskic2867142019-01-21 11:33:38 -08004211 if (args.size() > 1) {
4212 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004213 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004214 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004215 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004216 }
Robert Carr2047fae2016-11-28 14:09:09 -08004217 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004218 } else {
4219 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220 }
4221}
4222
Dominik Laskowskic2867142019-01-21 11:33:38 -08004223void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004224 const bool clearAll = args.size() < 2;
4225 const auto name = clearAll ? String8() : String8(args[1]);
4226
Edgar Arriaga844fa672020-01-16 14:21:42 -08004227 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004228 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004229 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004230 }
Robert Carr2047fae2016-11-28 14:09:09 -08004231 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004232
Svetoslavd85084b2014-03-20 10:28:31 -07004233 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004234}
4235
Dominik Laskowskic2867142019-01-21 11:33:38 -08004236void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4237 mTimeStats->parseArgs(asProto, args, result);
4238}
4239
Jamie Gennis6547ff42013-07-16 20:12:42 -07004240// This should only be called from the main thread. Otherwise it would need
4241// the lock and should use mCurrentState rather than mDrawingState.
4242void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004243 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004244 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004245 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004246
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004247 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004248}
4249
Yiwei Zhang5434a782018-12-05 18:06:32 -08004250void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004251 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004252
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004253 if (isLayerTripleBufferingDisabled())
4254 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004255
Yiwei Zhang5434a782018-12-05 18:06:32 -08004256 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4257 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4258 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4259 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4260 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4261 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004262 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004263}
4264
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004265void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004266 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004267
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004268 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004269 result.append("\n");
4270
Ady Abraham9e16a482019-12-03 17:19:41 -08004271 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004272 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004273 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004274 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004275
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004276 HwcConfigIndexType defaultConfig;
4277 float minFps, maxFps;
4278 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004279 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004280 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004281 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004282 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004283 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4284 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004285
Ana Krulecc2870422019-01-29 19:00:58 -08004286 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004287}
4288
Yiwei Zhang5434a782018-12-05 18:06:32 -08004289void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4290 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004291 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4292 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004293 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004294 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004296 }
David Sodman4a36e932017-11-07 14:29:47 -08004297 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004298 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004299 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4301 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004302}
4303
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004304void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4305 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004306 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4307 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004308 for (const auto& segment : history) {
4309 if (!segment.usedThirdBuffer) {
4310 stats.twoBufferTime += segment.totalTime;
4311 }
4312 if (segment.occupancyAverage < 1.0f) {
4313 stats.doubleBufferedTime += segment.totalTime;
4314 } else if (segment.occupancyAverage < 2.0f) {
4315 stats.tripleBufferedTime += segment.totalTime;
4316 }
4317 ++stats.numSegments;
4318 stats.totalTime += segment.totalTime;
4319 }
4320}
4321
Yiwei Zhang5434a782018-12-05 18:06:32 -08004322void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4323 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004324
4325 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4326 const size_t count = currentLayers.size();
4327 for (size_t i=0 ; i<count ; i++) {
4328 currentLayers[i]->dumpFrameEvents(result);
4329 }
4330}
4331
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004333 result.append("Buffering stats:\n");
4334 result.append(" [Layer name] <Active time> <Two buffer> "
4335 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004336 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004337 typedef std::tuple<std::string, float, float, float> BufferTuple;
4338 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004339 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004340 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004341 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004342 if (stats.numSegments == 0) {
4343 continue;
4344 }
4345 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4346 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4347 stats.totalTime;
4348 float doubleBufferRatio = static_cast<float>(
4349 stats.doubleBufferedTime) / stats.totalTime;
4350 float tripleBufferRatio = static_cast<float>(
4351 stats.tripleBufferedTime) / stats.totalTime;
4352 sorted.insert({activeTime, {name, twoBufferRatio,
4353 doubleBufferRatio, tripleBufferRatio}});
4354 }
4355 for (const auto& sortedPair : sorted) {
4356 float activeTime = sortedPair.first;
4357 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4359 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004360 }
4361 result.append("\n");
4362}
4363
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004365 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004366 const auto displayId = display->getId();
4367 if (!displayId) {
4368 continue;
4369 }
4370 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004371 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004372 continue;
4373 }
4374
Yiwei Zhang5434a782018-12-05 18:06:32 -08004375 StringAppendF(&result,
4376 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4377 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004378 uint8_t port;
4379 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004380 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004381 result.append("no identification data\n");
4382 continue;
4383 }
4384
4385 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004386 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004387 continue;
4388 }
4389
4390 const auto edid = parseEdid(data);
4391 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004392 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004393 continue;
4394 }
4395
Yiwei Zhang5434a782018-12-05 18:06:32 -08004396 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004397 result.append(edid->displayName.data(), edid->displayName.length());
4398 result.append("\"\n");
4399 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004400}
4401
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004402void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4403 std::string& result) const {
4404 hwc2_display_t hwcDisplayId;
4405 uint8_t port;
4406 DisplayIdentificationData data;
4407
4408 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4409 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4410 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4411 }
4412}
4413
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004415 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4417 StringAppendF(&result, "DisplayColorSetting: %s\n",
4418 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004419
4420 // TODO: print out if wide-color mode is active or not
4421
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004422 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004423 const auto displayId = display->getId();
4424 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004425 continue;
4426 }
4427
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004429 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004430 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004432 }
4433
Lloyd Pique32cbe282018-10-19 13:09:22 -07004434 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435 StringAppendF(&result, " Current color mode: %s (%d)\n",
4436 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004437 }
4438 result.append("\n");
4439}
4440
Vishnu Nair8406fd72019-07-30 11:29:31 -07004441LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004442 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004443 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4444 layer->writeToProto(layersProto, traceFlags);
4445 }
chaviw1d044282017-09-27 12:19:28 -07004446 return layersProto;
4447}
4448
Vishnu Nair0f085c62019-08-30 08:49:12 -07004449void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4450 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4451 // it.
4452 LayerProto* rootProto = layersProto.add_layers();
4453 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4454 rootProto->set_id(offscreenRootLayerId);
4455 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004456 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004457
4458 for (Layer* offscreenLayer : mOffscreenLayers) {
4459 // Add layer as child of the fake root
4460 rootProto->add_children(offscreenLayer->sequence);
4461
4462 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004463 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004464 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004465 }
4466}
4467
Vishnu Nair8406fd72019-07-30 11:29:31 -07004468LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4469 LayersProto layersProto;
4470 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4471 return layersProto;
4472}
4473
Vishnu Nair0f085c62019-08-30 08:49:12 -07004474void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4475 result.append("Offscreen Layers:\n");
4476 postMessageSync(new LambdaMessage([&]() {
4477 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004478 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004479 layer->dumpCallingUidPid(result);
4480 });
4481 }
4482 }));
4483}
4484
Dominik Laskowskic2867142019-01-21 11:33:38 -08004485void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4486 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004487 Colorizer colorizer(colorize);
4488
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004489 // figure out if we're stuck somewhere
4490 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004491 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004492 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4493
4494 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004495 * Dump library configuration.
4496 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004497
4498 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004499 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004500 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004501 appendSfConfigString(result);
4502 appendUiConfigString(result);
4503 appendGuiConfigString(result);
4504 result.append("\n");
4505
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004506 result.append("\nDisplay identification data:\n");
4507 dumpDisplayIdentificationData(result);
4508
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004509 result.append("\nWide-Color information:\n");
4510 dumpWideColorInfo(result);
4511
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004512 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004513 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004514 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004515 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004516 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004517
Andy McFadden41d67d72014-04-25 16:58:34 -07004518 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004519 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004520 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004521 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004522 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004523
Dan Stozab90cf072015-03-05 11:05:59 -08004524 dumpStaticScreenStats(result);
4525 result.append("\n");
4526
Alec Mouri40189b02019-03-05 15:07:54 -08004527 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4528 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4529 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004530
Dan Stozae77c7662016-05-13 11:37:28 -07004531 dumpBufferingStats(result);
4532
Andy McFadden4803b742012-09-24 19:07:20 -07004533 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004534 * Dump the visible layer list
4535 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004537 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004538 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4539 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004540 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004541
Chia-I Wu2f884132018-09-13 15:17:58 -07004542 {
Lloyd Pique207def92019-02-28 16:09:52 -08004543 StringAppendF(&result, "Composition layers\n");
4544 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004545 auto* compositionState = layer->getCompositionState();
4546 if (!compositionState) return;
4547
4548 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4549 layer->getDebugName() ? layer->getDebugName()
4550 : "<unknown>");
4551 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004552 });
4553 }
4554
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004555 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004556 * Dump Display state
4557 */
4558
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004561 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004562 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004563 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004564 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004565 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004566
4567 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004568 * Dump CompositionEngine state
4569 */
4570
4571 mCompositionEngine->dump(result);
4572
4573 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004574 * Dump SurfaceFlinger global state
4575 */
4576
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004577 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004578 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004579 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004580
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004581 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004582
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004583 DebugEGLImageTracker::getInstance()->dump(result);
4584
Dominik Laskowski075d3172018-05-24 15:50:06 -07004585 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004586 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4587 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004588 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4589 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004590 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591 StringAppendF(&result,
4592 " transaction-flags : %08x\n"
4593 " gpu_to_cpu_unsupported : %d\n",
4594 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004595
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004596 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004597 displayId && getHwComposer().isConnected(*displayId)) {
4598 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599 StringAppendF(&result,
4600 " refresh-rate : %f fps\n"
4601 " x-dpi : %f\n"
4602 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004603 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4604 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004605 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004608
Dan Stozae22aec72016-08-01 13:20:59 -07004609 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004610 * Tracing state
4611 */
4612 mTracing.dump(result);
4613 result.append("\n");
4614
4615 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004616 * HWC layer minidump
4617 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004618 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004619 const auto displayId = display->getId();
4620 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004621 continue;
4622 }
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004625 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004626 const sp<DisplayDevice> displayDevice = display;
4627 mCurrentState.traverseInZOrder(
4628 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004629 result.append("\n");
4630 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004631
4632 /*
4633 * Dump HWComposer state
4634 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004635 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004636 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004637 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004638 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004640 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641
4642 /*
4643 * Dump gralloc state
4644 */
4645 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4646 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004647
4648 /*
4649 * Dump VrFlinger state if in use.
4650 */
4651 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4652 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004654 result.append("\n");
4655 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004656
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004657 result.append(mTimeStats->miniDump());
4658 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004659}
4660
Chia-I Wu28f320b2018-05-03 11:02:56 -07004661void SurfaceFlinger::updateColorMatrixLocked() {
4662 mat4 colorMatrix;
4663 if (mGlobalSaturationFactor != 1.0f) {
4664 // Rec.709 luma coefficients
4665 float3 luminance{0.213f, 0.715f, 0.072f};
4666 luminance *= 1.0f - mGlobalSaturationFactor;
4667 mat4 saturationMatrix = mat4(
4668 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4669 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4670 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4671 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4672 );
4673 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4674 } else {
4675 colorMatrix = mClientColorMatrix * mDaltonizer();
4676 }
4677
4678 if (mCurrentState.colorMatrix != colorMatrix) {
4679 mCurrentState.colorMatrix = colorMatrix;
4680 mCurrentState.colorMatrixChanged = true;
4681 setTransactionFlags(eTransactionNeeded);
4682 }
4683}
4684
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004685status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004686#pragma clang diagnostic push
4687#pragma clang diagnostic error "-Wswitch-enum"
4688 switch (static_cast<ISurfaceComposerTag>(code)) {
4689 // These methods should at minimum make sure that the client requested
4690 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004691 case BOOT_FINISHED:
4692 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004693 case CREATE_DISPLAY:
4694 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004695 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696 case GET_ANIMATION_FRAME_STATS:
4697 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004698 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004699 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004700 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004701 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4702 case SET_AUTO_LOW_LATENCY_MODE:
4703 case GET_GAME_CONTENT_TYPE_SUPPORT:
4704 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004705 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004706 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004707 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004708 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004709 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004710 case NOTIFY_POWER_HINT:
4711 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004712 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4713 IPCThreadState* ipc = IPCThreadState::self();
4714 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4715 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004716 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004717 }
Robert Carr1db73f62016-12-21 12:58:51 -08004718 return OK;
4719 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004720 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004721 IPCThreadState* ipc = IPCThreadState::self();
4722 const int pid = ipc->getCallingPid();
4723 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004724 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4725 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004726 return PERMISSION_DENIED;
4727 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004729 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004730 // Used by apps to hook Choreographer to SurfaceFlinger.
4731 case CREATE_DISPLAY_EVENT_CONNECTION:
4732 // The following calls are currently used by clients that do not
4733 // request necessary permissions. However, they do not expose any secret
4734 // information, so it is OK to pass them.
4735 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004736 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004738 case GET_PHYSICAL_DISPLAY_IDS:
4739 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004740 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004741 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004742 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004743 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004744 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004745 case GET_DISPLAY_STATS:
4746 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4747 // Calling setTransactionState is safe, because you need to have been
4748 // granted a reference to Client* and Handle* to do anything with it.
4749 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004750 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004751 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004752 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004753 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004754 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004755 // setFrameRate() is deliberately available for apps to call without any
4756 // special permissions.
4757 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004758 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4759 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004760 return OK;
4761 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004762 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004763 case CAPTURE_SCREEN:
4764 case ADD_REGION_SAMPLING_LISTENER:
4765 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004767 IPCThreadState* ipc = IPCThreadState::self();
4768 const int pid = ipc->getCallingPid();
4769 const int uid = ipc->getCallingUid();
4770 if ((uid != AID_GRAPHICS) &&
4771 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4772 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4773 return PERMISSION_DENIED;
4774 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775 return OK;
4776 }
chaviw93df2ea2019-04-30 16:45:12 -07004777 case CAPTURE_SCREEN_BY_ID: {
4778 IPCThreadState* ipc = IPCThreadState::self();
4779 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004780 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004781 return OK;
4782 }
4783 return PERMISSION_DENIED;
4784 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004785 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786
4787 // These codes are used for the IBinder protocol to either interrogate the recipient
4788 // side of the transaction for its canonical interface descriptor or to dump its state.
4789 // We let them pass by default.
4790 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4791 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4792 code == IBinder::SYSPROPS_TRANSACTION) {
4793 return OK;
4794 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004795 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004796 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004797 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4799 return OK;
4800 }
4801 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4802 return PERMISSION_DENIED;
4803#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004804}
4805
Ana Krulec13be8ad2018-08-21 02:43:56 +00004806status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4807 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004808 status_t credentialCheck = CheckTransactCodeCredentials(code);
4809 if (credentialCheck != OK) {
4810 return credentialCheck;
4811 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004812
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004813 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4814 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004815 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004816 IPCThreadState* ipc = IPCThreadState::self();
4817 const int uid = ipc->getCallingUid();
4818 if (CC_UNLIKELY(uid != AID_SYSTEM
4819 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004820 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004821 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004822 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004823 return PERMISSION_DENIED;
4824 }
4825 int n;
4826 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004827 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004828 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004829 return NO_ERROR;
4830 case 1002: // SHOW_UPDATES
4831 n = data.readInt32();
4832 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004833 invalidateHwcGeometry();
4834 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004835 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004837 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004838 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004839 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004840 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004841 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004842 setTransactionFlags(
4843 eTransactionNeeded|
4844 eDisplayTransactionNeeded|
4845 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004846 return NO_ERROR;
4847 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004848 case 1006:{ // send empty update
4849 signalRefresh();
4850 return NO_ERROR;
4851 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004852 case 1008: // toggle use of hw composer
4853 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004854 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004855 invalidateHwcGeometry();
4856 repaintEverything();
4857 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004858 case 1009: // toggle use of transform hint
4859 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004860 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004861 invalidateHwcGeometry();
4862 repaintEverything();
4863 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004864 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004865 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 reply->writeInt32(0);
4867 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004868 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004869 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004870 return NO_ERROR;
4871 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004872 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004873 if (!display) {
4874 return NAME_NOT_FOUND;
4875 }
4876
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004877 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004878 return NO_ERROR;
4879 }
4880 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004881 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004882 // daltonize
4883 n = data.readInt32();
4884 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004885 case 1:
4886 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4887 break;
4888 case 2:
4889 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4890 break;
4891 case 3:
4892 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4893 break;
4894 default:
4895 mDaltonizer.setType(ColorBlindnessType::None);
4896 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004897 }
4898 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004899 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004900 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004901 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004902 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004903
4904 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004905 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004906 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004907 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004909 // apply a color matrix
4910 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004911 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004912 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004913 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004914 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004915 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004916 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004917 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004918 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004919 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004920 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004921
4922 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4923 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004924 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004925 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4926 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4927 }
4928
Chia-I Wu28f320b2018-05-03 11:02:56 -07004929 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004930 return NO_ERROR;
4931 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004932 case 1016: { // Unused.
4933 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004934 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004935 case 1017: {
4936 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004937 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004938 return NO_ERROR;
4939 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004940 case 1018: { // Modify Choreographer's phase offset
4941 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004942 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004943 return NO_ERROR;
4944 }
4945 case 1019: { // Modify SurfaceFlinger's phase offset
4946 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004947 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004948 return NO_ERROR;
4949 }
Irvel468051e2016-06-13 16:44:44 -07004950 case 1020: { // Layer updates interceptor
4951 n = data.readInt32();
4952 if (n) {
4953 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004954 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004955 }
4956 else{
4957 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004958 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004959 }
4960 return NO_ERROR;
4961 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004962 case 1021: { // Disable HWC virtual displays
4963 n = data.readInt32();
4964 mUseHwcVirtualDisplays = !n;
4965 return NO_ERROR;
4966 }
Romain Guy0147a172017-06-01 13:53:56 -07004967 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004969 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004970
Chia-I Wu28f320b2018-05-03 11:02:56 -07004971 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004972 return NO_ERROR;
4973 }
Romain Guy54f154a2017-10-24 21:40:32 +01004974 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004975 int32_t colorMode;
4976
Chia-I Wu0d711262018-05-21 15:19:35 -07004977 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004978 if (data.readInt32(&colorMode) == NO_ERROR) {
4979 mForceColorMode = static_cast<ColorMode>(colorMode);
4980 }
Romain Guy54f154a2017-10-24 21:40:32 +01004981 invalidateHwcGeometry();
4982 repaintEverything();
4983 return NO_ERROR;
4984 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004985 // Deprecate, use 1030 to check whether the device is color managed.
4986 case 1024: {
4987 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004988 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004989 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004990 n = data.readInt32();
4991 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004992 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004993 Mutex::Autolock lock(mStateLock);
4994 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004995 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004996 reply->writeInt32(NO_ERROR);
4997 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004998 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004999 bool writeFile = false;
5000 {
5001 Mutex::Autolock lock(mStateLock);
5002 mTracingEnabledChanged = true;
5003 writeFile = mTracing.disable();
5004 }
5005
5006 if (writeFile) {
5007 reply->writeInt32(mTracing.writeToFile());
5008 } else {
5009 reply->writeInt32(NO_ERROR);
5010 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005011 }
5012 return NO_ERROR;
5013 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005014 case 1026: { // Get layer tracing status
5015 reply->writeBool(mTracing.isEnabled());
5016 return NO_ERROR;
5017 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005018 // Is a DisplayColorSetting supported?
5019 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 const auto display = getDefaultDisplayDevice();
5021 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005022 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005023 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005024
5025 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5026 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005027 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005028 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005029 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005030 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005031 reply->writeBool(true);
5032 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005033 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005034 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005035 break;
5036 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005037 reply->writeBool(
5038 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005039 break;
5040 }
5041 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005042 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005043 // Is VrFlinger active?
5044 case 1028: {
5045 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005046 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005047 return NO_ERROR;
5048 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005049 // Set buffer size for SF tracing (value in KB)
5050 case 1029: {
5051 n = data.readInt32();
5052 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5053 ALOGW("Invalid buffer size: %d KB", n);
5054 reply->writeInt32(BAD_VALUE);
5055 return BAD_VALUE;
5056 }
5057
5058 ALOGD("Updating trace buffer to %d KB", n);
5059 mTracing.setBufferSize(n * 1024);
5060 reply->writeInt32(NO_ERROR);
5061 return NO_ERROR;
5062 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005063 // Is device color managed?
5064 case 1030: {
5065 reply->writeBool(useColorManagement);
5066 return NO_ERROR;
5067 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005068 // Override default composition data space
5069 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5070 // && adb shell stop zygote && adb shell start zygote
5071 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5072 // adb shell stop zygote && adb shell start zygote
5073 case 1031: {
5074 Mutex::Autolock _l(mStateLock);
5075 n = data.readInt32();
5076 if (n) {
5077 n = data.readInt32();
5078 if (n) {
5079 Dataspace dataspace = static_cast<Dataspace>(n);
5080 if (!validateCompositionDataspace(dataspace)) {
5081 return BAD_VALUE;
5082 }
5083 mDefaultCompositionDataspace = dataspace;
5084 }
5085 n = data.readInt32();
5086 if (n) {
5087 Dataspace dataspace = static_cast<Dataspace>(n);
5088 if (!validateCompositionDataspace(dataspace)) {
5089 return BAD_VALUE;
5090 }
5091 mWideColorGamutCompositionDataspace = dataspace;
5092 }
5093 } else {
5094 // restore composition data space.
5095 mDefaultCompositionDataspace = defaultCompositionDataspace;
5096 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5097 }
5098 return NO_ERROR;
5099 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005100 // Set trace flags
5101 case 1033: {
5102 n = data.readUint32();
5103 ALOGD("Updating trace flags to 0x%x", n);
5104 mTracing.setTraceFlags(n);
5105 reply->writeInt32(NO_ERROR);
5106 return NO_ERROR;
5107 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005108 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005109 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005110 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005111 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005112 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5113 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005114 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005115 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005116 } else {
5117 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005118 }
5119 return NO_ERROR;
5120 }
Ady Abraham34392f72019-04-10 11:29:27 -07005121 case 1035: {
5122 n = data.readInt32();
5123 mDebugDisplayConfigSetByBackdoor = false;
5124 if (n >= 0) {
5125 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005126 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005127 if (result != NO_ERROR) {
5128 return result;
5129 }
5130 mDebugDisplayConfigSetByBackdoor = true;
5131 }
5132 return NO_ERROR;
5133 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005134 }
5135 }
5136 return err;
5137}
5138
Steven Thomas6d8110b2017-08-31 18:24:21 -07005139void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005140 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005141 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005142}
5143
Ana Krulec7d1d6832018-12-27 11:10:09 -08005144void SurfaceFlinger::repaintEverythingForHWC() {
5145 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005146 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005147 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005148}
5149
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005150// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5151class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005152public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005153 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5154 ~WindowDisconnector() {
5155 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005156 }
5157
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005158private:
5159 ANativeWindow* mWindow;
5160 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005161};
5162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005164 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005165 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5166 const Rect& sourceCrop, uint32_t reqWidth,
5167 uint32_t reqHeight, bool useIdentityTransform,
5168 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005169 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005171 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005172
Dominik Laskowski718f9602019-11-09 20:01:35 -08005173 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5174 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5175 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5176 renderAreaRotation = ui::Transform::ROT_0;
5177 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005178
Chia-I Wu20261cb2018-08-23 12:55:44 -07005179 sp<DisplayDevice> display;
5180 {
5181 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005182
Chia-I Wu20261cb2018-08-23 12:55:44 -07005183 display = getDisplayDeviceLocked(displayToken);
5184 if (!display) return BAD_VALUE;
5185
Chia-I Wucb023152018-08-28 12:57:23 -07005186 // set the requested width/height to the logical display viewport size
5187 // by default
5188 if (reqWidth == 0 || reqHeight == 0) {
5189 reqWidth = uint32_t(display->getViewport().width());
5190 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005191 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005192 }
5193
Peiyong Lin0e003c92018-09-17 11:09:51 -07005194 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005195 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005196
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005197 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5198 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005199 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005200 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005201}
5202
chaviw93df2ea2019-04-30 16:45:12 -07005203static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5204 switch (colorMode) {
5205 case ColorMode::DISPLAY_P3:
5206 case ColorMode::BT2100_PQ:
5207 case ColorMode::BT2100_HLG:
5208 case ColorMode::DISPLAY_BT2020:
5209 return Dataspace::DISPLAY_P3;
5210 default:
5211 return Dataspace::V0_SRGB;
5212 }
5213}
5214
5215const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5216 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5217 if (displayToken) {
5218 return getDisplayDeviceLocked(displayToken);
5219 }
5220 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5221 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005222 return getDisplayByLayerStack(displayOrLayerStack);
5223}
5224
5225const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005226 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005227 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005228 return display;
5229 }
5230 }
5231 return nullptr;
5232}
5233
5234status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5235 sp<GraphicBuffer>* outBuffer) {
5236 sp<DisplayDevice> display;
5237 uint32_t width;
5238 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005239 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005240 {
5241 Mutex::Autolock _l(mStateLock);
5242 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5243 if (!display) {
5244 return BAD_VALUE;
5245 }
5246
5247 width = uint32_t(display->getViewport().width());
5248 height = uint32_t(display->getViewport().height());
5249
Dominik Laskowski718f9602019-11-09 20:01:35 -08005250 const auto orientation = display->getOrientation();
5251 captureOrientation = ui::Transform::toRotationFlags(orientation);
5252
5253 switch (captureOrientation) {
5254 case ui::Transform::ROT_90:
5255 captureOrientation = ui::Transform::ROT_270;
5256 break;
5257
5258 case ui::Transform::ROT_270:
5259 captureOrientation = ui::Transform::ROT_90;
5260 break;
5261
5262 case ui::Transform::ROT_INVALID:
5263 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5264 captureOrientation = ui::Transform::ROT_0;
5265 break;
5266
5267 default:
5268 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005269 }
chaviw93df2ea2019-04-30 16:45:12 -07005270 *outDataspace =
5271 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5272 }
5273
5274 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5275 false /* captureSecureLayers */);
5276
5277 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5278 std::placeholders::_1);
5279 bool ignored = false;
5280 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5281 false /* useIdentityTransform */,
5282 ignored /* outCapturedSecureLayers */);
5283}
5284
Robert Carr866455f2019-04-02 16:28:26 -07005285status_t SurfaceFlinger::captureLayers(
5286 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5287 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5288 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5289 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005290 ATRACE_CALL();
5291
5292 class LayerRenderArea : public RenderArea {
5293 public:
Robert Carr578038f2018-03-09 12:25:24 -08005294 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005295 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005296 bool childrenOnly, const Rect& displayViewport)
5297 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005298 mLayer(layer),
5299 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005300 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005301 mFlinger(flinger),
5302 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005303 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005304 Rect getBounds() const override {
5305 const Layer::State& layerState(mLayer->getDrawingState());
5306 return mLayer->getBufferSize(layerState);
5307 }
Marissa Wall61c58622018-07-18 10:12:20 -07005308 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005309 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005310 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005311 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005312 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005313 }
chaviwa76b2712017-09-20 12:02:26 -07005314 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005315 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005316 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005317 Rect getSourceCrop() const override {
5318 if (mCrop.isEmpty()) {
5319 return getBounds();
5320 } else {
5321 return mCrop;
5322 }
5323 }
Robert Carr578038f2018-03-09 12:25:24 -08005324 class ReparentForDrawing {
5325 public:
5326 const sp<Layer>& oldParent;
5327 const sp<Layer>& newParent;
5328
Vishnu Nair4351ad52019-02-11 14:13:02 -08005329 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5330 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005331 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005332 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005333 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5334 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005335 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005336 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005337 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005338 };
5339
5340 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005341 const Rect sourceCrop = getSourceCrop();
5342 // no need to check rotation because there is none
5343 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5344 sourceCrop.height() != getReqHeight();
5345
Robert Carr578038f2018-03-09 12:25:24 -08005346 if (!mChildrenOnly) {
5347 mTransform = mLayer->getTransform().inverse();
5348 drawLayers();
5349 } else {
5350 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005351 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5352 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005353 // In the "childrenOnly" case we reparent the children to a screenshot
5354 // layer which has no properties set and which does not draw.
5355 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005356 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5357 "Screenshot Parent"s, w, h, 0,
5358 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005359
Vishnu Nair4351ad52019-02-11 14:13:02 -08005360 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005361 drawLayers();
5362 }
5363 }
chaviwa76b2712017-09-20 12:02:26 -07005364
chaviwa76b2712017-09-20 12:02:26 -07005365 private:
chaviw7206d492017-11-10 16:16:12 -08005366 const sp<Layer> mLayer;
5367 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005368
Peiyong Linefefaac2018-08-17 12:27:51 -07005369 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005370 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005371
5372 SurfaceFlinger* mFlinger;
5373 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005374 };
5375
Robert Carrc0df3122019-04-11 13:18:21 -07005376 int reqWidth = 0;
5377 int reqHeight = 0;
5378 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005379 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005380 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005381 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005382 {
5383 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005384
Robert Carrc0df3122019-04-11 13:18:21 -07005385 parent = fromHandle(layerHandleBinder);
5386 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5387 ALOGE("captureLayers called with an invalid or removed parent");
5388 return NAME_NOT_FOUND;
5389 }
5390
5391 const int uid = IPCThreadState::self()->getCallingUid();
5392 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5393 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5394 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5395 return PERMISSION_DENIED;
5396 }
5397
Vishnu Nairefc42e22019-12-03 17:36:12 -08005398 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005399 if (sourceCrop.width() <= 0) {
5400 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005401 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005402 }
5403
5404 if (sourceCrop.height() <= 0) {
5405 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005406 crop.bottom = parentSourceBounds.getHeight();
5407 }
5408
5409 if (crop.isEmpty() || frameScale <= 0.0f) {
5410 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5411 // crop was not specified, or an invalid frame scale was provided.
5412 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005413 }
5414 reqWidth = crop.width() * frameScale;
5415 reqHeight = crop.height() * frameScale;
5416
5417 for (const auto& handle : excludeHandles) {
5418 sp<Layer> excludeLayer = fromHandle(handle);
5419 if (excludeLayer != nullptr) {
5420 excludeLayers.emplace(excludeLayer);
5421 } else {
5422 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5423 return NAME_NOT_FOUND;
5424 }
5425 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005426
5427 auto display = getDisplayByLayerStack(parent->getLayerStack());
5428 if (!display) {
5429 return BAD_VALUE;
5430 }
5431
5432 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005433 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005434
Chia-I Wu20261cb2018-08-23 12:55:44 -07005435 // really small crop or frameScale
5436 if (reqWidth <= 0) {
5437 reqWidth = 1;
5438 }
5439 if (reqHeight <= 0) {
5440 reqHeight = 1;
5441 }
5442
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005443 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5444 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005445 auto traverseLayers = [parent, childrenOnly,
5446 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005447 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5448 if (!layer->isVisible()) {
5449 return;
Robert Carr578038f2018-03-09 12:25:24 -08005450 } else if (childrenOnly && layer == parent.get()) {
5451 return;
chaviwa76b2712017-09-20 12:02:26 -07005452 }
Robert Carr866455f2019-04-02 16:28:26 -07005453
5454 sp<Layer> p = layer;
5455 while (p != nullptr) {
5456 if (excludeLayers.count(p) != 0) {
5457 return;
5458 }
5459 p = p->getParent();
5460 }
5461
chaviwa76b2712017-09-20 12:02:26 -07005462 visitor(layer);
5463 });
5464 };
Robert Carr108b2c72019-04-02 16:32:58 -07005465
5466 bool outCapturedSecureLayers = false;
5467 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5468 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005469}
5470
5471status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5472 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005473 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005474 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005475 bool useIdentityTransform,
5476 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005477 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005478
Peiyong Lin0e003c92018-09-17 11:09:51 -07005479 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005480 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5481 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005482 *outBuffer =
5483 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5484 static_cast<android_pixel_format>(reqPixelFormat), 1,
5485 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005486
Robert Carr108b2c72019-04-02 16:32:58 -07005487 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5488 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005489}
5490
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005491status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5492 TraverseLayersFunction traverseLayers,
5493 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005494 bool useIdentityTransform,
5495 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 // This mutex protects syncFd and captureResult for communication of the return values from the
5497 // main thread back to this Binder thread
5498 std::mutex captureMutex;
5499 std::condition_variable captureCondition;
5500 std::unique_lock<std::mutex> captureLock(captureMutex);
5501 int syncFd = -1;
5502 std::optional<status_t> captureResult;
5503
Robert Carr03480e22018-01-04 16:02:06 -08005504 const int uid = IPCThreadState::self()->getCallingUid();
5505 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5506
Dominik Laskowski8c001672018-05-30 16:52:06 -07005507 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005508 // If there is a refresh pending, bug out early and tell the binder thread to try again
5509 // after the refresh.
5510 if (mRefreshPending) {
5511 ATRACE_NAME("Skipping screenshot for now");
5512 std::unique_lock<std::mutex> captureLock(captureMutex);
5513 captureResult = std::make_optional<status_t>(EAGAIN);
5514 captureCondition.notify_one();
5515 return;
5516 }
5517
5518 status_t result = NO_ERROR;
5519 int fd = -1;
5520 {
5521 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005522 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005523 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005524 useIdentityTransform, forSystem, &fd,
5525 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005526 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005527 }
5528
5529 {
5530 std::unique_lock<std::mutex> captureLock(captureMutex);
5531 syncFd = fd;
5532 captureResult = std::make_optional<status_t>(result);
5533 captureCondition.notify_one();
5534 }
5535 });
5536
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005537 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005538 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005539 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005540 while (*captureResult == EAGAIN) {
5541 captureResult.reset();
5542 result = postMessageAsync(message);
5543 if (result != NO_ERROR) {
5544 return result;
5545 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005546 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005547 }
5548 result = *captureResult;
5549 }
5550
5551 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005552 sync_wait(syncFd, -1);
5553 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005554 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005555
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005556 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005557}
5558
chaviwa76b2712017-09-20 12:02:26 -07005559void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005560 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005561 const sp<GraphicBuffer>& buffer,
5562 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005563 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005564
chaviwa76b2712017-09-20 12:02:26 -07005565 const auto reqWidth = renderArea.getReqWidth();
5566 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005567 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005568 const auto transform = renderArea.getTransform();
5569 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005570 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005571
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005572 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005573 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005574
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005575 // assume that bounds are never offset, and that they are the same as the
5576 // buffer bounds.
5577 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005578 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005579 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005580
5581 // Now take into account the rotation flag. We append a transform that
5582 // rotates the layer stack about the origin, then translate by buffer
5583 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005584 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005585 int displacementX = 0;
5586 int displacementY = 0;
5587 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5588 switch (rotation) {
5589 case ui::Transform::ROT_90:
5590 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005591 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005592 break;
5593 case ui::Transform::ROT_180:
5594 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005595 displacementY = renderArea.getBounds().getWidth();
5596 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005597 break;
5598 case ui::Transform::ROT_270:
5599 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005600 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005601 break;
5602 default:
5603 break;
5604 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005605
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005606 // We need to transform the clipping window into the right spot.
5607 // First, rotate the clipping rectangle by the rotation hint to get the
5608 // right orientation
5609 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5610 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5611 const vec4 rotClipTL = rotMatrix * clipTL;
5612 const vec4 rotClipBR = rotMatrix * clipBR;
5613 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5614 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5615 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5616 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5617
5618 // Now reposition the clipping rectangle with the displacement vector
5619 // computed above.
5620 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005621 clientCompositionDisplay.clip =
5622 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5623 newClipRight + displacementX, newClipBottom + displacementY);
5624
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005625 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005626 clientCompositionDisplay.globalTransform =
5627 clipTransform * clientCompositionDisplay.globalTransform;
5628
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005629 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5630 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005631
chaviw50da5042018-04-09 13:49:37 -07005632 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005633
Vishnu Nair9b079a22020-01-21 14:36:08 -08005634 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005635 fillLayer.source.buffer.buffer = nullptr;
5636 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5637 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5638 fillLayer.alpha = half(alpha);
5639 clientCompositionLayers.push_back(fillLayer);
5640
5641 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005642 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005643 const bool supportProtectedContent = false;
5644 Region clip(renderArea.getBounds());
5645 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5646 clip,
5647 useIdentityTransform,
5648 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5649 renderArea.isSecure(),
5650 supportProtectedContent,
5651 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005652 displayViewport,
5653 clientCompositionDisplay.outputDataspace,
5654 true, /* realContentIsVisible */
5655 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005656 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005657 std::vector<compositionengine::LayerFE::LayerSettings> results =
5658 layer->prepareClientCompositionList(targetSettings);
5659 clientCompositionLayers.insert(clientCompositionLayers.end(),
5660 std::make_move_iterator(results.begin()),
5661 std::make_move_iterator(results.end()));
5662 results.clear();
5663
chaviwa76b2712017-09-20 12:02:26 -07005664 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005665
Vishnu Nair9b079a22020-01-21 14:36:08 -08005666 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5667 clientCompositionLayers.reserve(clientCompositionLayers.size());
5668 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5669 std::back_inserter(clientCompositionLayerPointers),
5670 [](compositionengine::LayerFE::LayerSettings& settings)
5671 -> renderengine::LayerSettings* { return &settings; });
5672
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005673 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005674 // Use an empty fence for the buffer fence, since we just created the buffer so
5675 // there is no need for synchronization with the GPU.
5676 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005677 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005678 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005679 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005680 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005681
5682 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005683}
5684
chaviwa76b2712017-09-20 12:02:26 -07005685status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5686 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005687 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005688 bool useIdentityTransform, bool forSystem,
5689 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005690 ATRACE_CALL();
5691
chaviwa76b2712017-09-20 12:02:26 -07005692 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005693 outCapturedSecureLayers =
5694 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005695 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005696
Robert Carr03480e22018-01-04 16:02:06 -08005697 // We allow the system server to take screenshots of secure layers for
5698 // use in situations like the Screen-rotation animation and place
5699 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005700 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005701 ALOGW("FB is protected: PERMISSION_DENIED");
5702 return PERMISSION_DENIED;
5703 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005704 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005705 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005706}
5707
chaviw95ef3c42019-02-14 10:55:09 -08005708void SurfaceFlinger::setInputWindowsFinished() {
5709 Mutex::Autolock _l(mStateLock);
5710
5711 mPendingSyncInputWindows = false;
5712 mTransactionCV.broadcast();
5713}
chaviw5f21a5e2019-02-14 10:00:34 -08005714
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005715// ---------------------------------------------------------------------------
5716
Edgar Arriaga844fa672020-01-16 14:21:42 -08005717void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5718 layersSortedByZ.traverse(visitor);
5719}
5720
Dan Stoza412903f2017-04-27 13:42:17 -07005721void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5722 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005723}
5724
Dan Stoza412903f2017-04-27 13:42:17 -07005725void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5726 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005727}
5728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005729void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005730 const LayerVector::Visitor& visitor) {
5731 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005732 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005733 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005734 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005735 continue;
5736 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005737 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005738 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005739 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005740 return;
5741 }
chaviwa76b2712017-09-20 12:02:26 -07005742 if (!layer->isVisible()) {
5743 return;
5744 }
5745 visitor(layer);
5746 });
5747 }
5748}
5749
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005750status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5751 HwcConfigIndexType defaultConfig,
5752 float minRefreshRate,
5753 float maxRefreshRate) {
5754 Mutex::Autolock lock(mStateLock);
5755
Dominik Laskowski22488f62019-03-28 09:53:04 -07005756 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005757 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5758 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5759 // it should go thru setDesiredActiveConfig, similar to primary display.
5760 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5761 const auto displayId = display->getId();
5762 LOG_ALWAYS_FATAL_IF(!displayId);
5763
5764 HWC2::VsyncPeriodChangeConstraints constraints;
5765 constraints.desiredTimeNanos = systemTime();
5766 constraints.seamlessRequired = false;
5767
5768 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005769 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5770 constraints, &timeline) < 0) {
5771 return BAD_VALUE;
5772 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005773 if (timeline.refreshRequired) {
5774 repaintEverythingForHWC();
5775 }
5776
Ady Abrahamdfa37362020-01-21 18:02:39 -08005777 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005778 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005779 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5780 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005781 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005782 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005783 }
5784
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005785 if (mDebugDisplayConfigSetByBackdoor) {
5786 // ignore this request as config is overridden by backdoor
5787 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005788 }
5789
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005790 bool policyChanged;
5791 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5792 &policyChanged) < 0) {
5793 return BAD_VALUE;
5794 }
5795 if (!policyChanged) {
5796 return NO_ERROR;
5797 }
5798
5799 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5800 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005801
5802 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5803 // that listeners that care about a change in allowed configs can get the notification.
5804 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005805 const nsecs_t vsyncPeriod =
5806 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005807 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005808 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005809
Ana Krulec3f6a2062020-01-23 15:48:01 -08005810 auto configId = mScheduler->getPreferredConfigId();
5811 auto preferredRefreshRate = configId
5812 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5813 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5814 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5815 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5816 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5817
5818 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5819 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5820 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005821 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005822 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005823 }
5824
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005825 return NO_ERROR;
5826}
5827
Ana Krulec0782b882019-10-15 17:34:54 -07005828status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005829 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005830 float maxRefreshRate) {
5831 ATRACE_CALL();
5832
5833 if (!displayToken) {
5834 return BAD_VALUE;
5835 }
5836
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005837 status_t result = NO_ERROR;
5838
Ana Krulec234bb162019-11-10 22:55:55 +01005839 postMessageSync(new LambdaMessage([&]() {
5840 const auto display = getDisplayDeviceLocked(displayToken);
5841 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005842 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005843 ALOGE("Attempt to set desired display configs for invalid display token %p",
5844 displayToken.get());
5845 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005846 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005847 ALOGW("Attempt to set desired display configs for virtual display");
5848 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005849 result =
5850 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5851 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005852 }
5853 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005854
5855 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005856}
5857
5858status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005859 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005860 float* outMinRefreshRate,
5861 float* outMaxRefreshRate) {
5862 ATRACE_CALL();
5863
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005864 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005865 return BAD_VALUE;
5866 }
5867
5868 Mutex::Autolock lock(mStateLock);
5869 const auto display = getDisplayDeviceLocked(displayToken);
5870 if (!display) {
5871 return NAME_NOT_FOUND;
5872 }
5873
5874 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005875 HwcConfigIndexType defaultConfig;
5876 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5877 *outDefaultConfig = defaultConfig.value();
5878 return NO_ERROR;
5879 } else if (display->isVirtual()) {
5880 return BAD_VALUE;
5881 } else {
5882 const auto displayId = display->getId();
5883 if (!displayId) {
5884 return BAD_VALUE;
5885 }
5886 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5887 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5888 *outMinRefreshRate = 1e9f / vsyncPeriod;
5889 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5890 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005891 }
Ana Krulec0782b882019-10-15 17:34:54 -07005892}
5893
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005894void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005895 mFlinger->setInputWindowsFinished();
5896}
5897
Robert Carrc0df3122019-04-11 13:18:21 -07005898sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005899 BBinder* b = nullptr;
5900 if (handle) {
5901 b = handle->localBinder();
5902 }
Robert Carrc0df3122019-04-11 13:18:21 -07005903 if (b == nullptr) {
5904 return nullptr;
5905 }
5906 auto it = mLayersByLocalBinderToken.find(b);
5907 if (it != mLayersByLocalBinderToken.end()) {
5908 return it->second.promote();
5909 }
5910 return nullptr;
5911}
5912
Dominik Laskowski75848362019-11-11 17:57:20 -08005913void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005914 mNumLayers++;
5915 mScheduler->registerLayer(layer);
5916}
5917
5918void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5919 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005920 removeFromOffscreenLayers(layer);
5921}
5922
5923// WARNING: ONLY CALL THIS FROM LAYER DTOR
5924// Here we add children in the current state to offscreen layers and remove the
5925// layer itself from the offscreen layer list. Since
5926// this is the dtor, it is safe to access the current state. This keeps us
5927// from dangling children layers such that they are not reachable from the
5928// Drawing state nor the offscreen layer list
5929// See b/141111965
5930void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5931 for (auto& child : layer->getCurrentChildren()) {
5932 mOffscreenLayers.emplace(child.get());
5933 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005934 mOffscreenLayers.erase(layer);
5935}
5936
Alec Mouri4545a8a2019-08-08 20:05:32 -07005937void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5938 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5939}
5940
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005941status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5942 float lightPosY, float lightPosZ,
5943 float lightRadius) {
5944 Mutex::Autolock _l(mStateLock);
5945 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5946 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5947 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5948 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5949 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5950
5951 // these values are overridden when calculating the shadow settings for a layer.
5952 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5953 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005954 return NO_ERROR;
5955}
5956
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005957const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5958 const {
5959 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5960 // on the work to remove the table in that bug rather than adding more to
5961 // it.
5962 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5963 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5964 // supported, and exposed via the
5965 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5966 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5967 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5968 };
5969 return genericLayerMetadataKeyMap;
5970}
5971
Steven Thomas62a4cf82020-01-31 12:04:03 -08005972status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5973 int8_t compatibility) {
5974 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5975 return BAD_VALUE;
5976 }
5977
5978 Mutex::Autolock lock(mStateLock);
5979 if (authenticateSurfaceTextureLocked(surface)) {
5980 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5981 if (layer->setFrameRate(
5982 Layer::FrameRate(frameRate,
5983 Layer::FrameRate::convertCompatibility(compatibility)))) {
5984 setTransactionFlags(eTraversalNeeded);
5985 }
5986 } else {
5987 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5988 return BAD_VALUE;
5989 }
5990 return NO_ERROR;
5991}
5992
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005993} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005994
Mathias Agopian3f844832013-08-07 21:24:32 -07005995#if defined(__gl_h_)
5996#error "don't include gl/gl.h in this file"
5997#endif
5998
5999#if defined(__gl2_h_)
6000#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006001#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006002
6003// TODO(b/129481165): remove the #pragma below and fix conversion issues
6004#pragma clang diagnostic pop // ignored "-Wconversion"