blob: 86f1bc1b27675f58da09d577379f0ab07394d85e [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd 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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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 Mouri989ddbe2020-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;
371
Dan Stozaec460082018-12-17 15:35:09 -0800372 property_get("debug.sf.luma_sampling", value, "1");
373 mLumaSampling = atoi(value);
374
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800375 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800376 mDisableClientCompositionCache = atoi(value);
377
Romain Guy11d63f42017-07-20 12:47:14 -0700378 // We should be reading 'persist.sys.sf.color_saturation' here
379 // but since /data may be encrypted, we need to wait until after vold
380 // comes online to attempt to read the property. The property is
381 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800382
383 if (useTrebleTestingOverride()) {
384 // Without the override SurfaceFlinger cannot connect to HIDL
385 // services that are not listed in the manifests. Considered
386 // deriving the setting from the set service name, but it
387 // would be brittle if the name that's not 'default' is used
388 // for production purposes later on.
389 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
390 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800391
392 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395void SurfaceFlinger::onFirstRef()
396{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800397 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700400SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401
Dan Stozac7014012014-02-14 15:03:43 -0800402void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403{
404 // the window manager died on us. prepare its eulogy.
405
Andy McFadden13a082e2012-08-24 10:16:42 -0700406 // restore initial conditions (default device unblank, etc)
407 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408
409 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700410 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Robert Carr1db73f62016-12-21 12:58:51 -0800413static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700414 status_t err = client->initCheck();
415 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800416 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 }
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return nullptr;
419}
420
421sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
422 return initClient(new Client(this));
423}
424
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700425sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
426 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427{
428 class DisplayToken : public BBinder {
429 sp<SurfaceFlinger> flinger;
430 virtual ~DisplayToken() {
431 // no more references, this display must be terminated
432 Mutex::Autolock _l(flinger->mStateLock);
433 flinger->mCurrentState.displays.removeItem(this);
434 flinger->setTransactionFlags(eDisplayTransactionNeeded);
435 }
436 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700437 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 : flinger(flinger) {
439 }
440 };
441
442 sp<BBinder> token = new DisplayToken(this);
443
444 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 // Display ID is assigned when virtual display is allocated by HWC.
446 DisplayDeviceState state;
447 state.isSecure = secure;
448 state.displayName = displayName;
449 mCurrentState.displays.add(token, state);
450 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 return token;
452}
453
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 Mutex::Autolock _l(mStateLock);
456
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
458 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 return;
461 }
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
464 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 ALOGE("destroyDisplay called for non-virtual display");
466 return;
467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 mInterceptor->saveDisplayDeletion(state.sequenceId);
469 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 setTransactionFlags(eDisplayTransactionNeeded);
471}
472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
474 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800476 const auto internalDisplayId = getInternalDisplayIdLocked();
477 if (!internalDisplayId) {
478 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 }
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 std::vector<PhysicalDisplayId> displayIds;
482 displayIds.reserve(mPhysicalDisplayTokens.size());
483 displayIds.push_back(internalDisplayId->value);
484
485 for (const auto& [id, token] : mPhysicalDisplayTokens) {
486 if (id != *internalDisplayId) {
487 displayIds.push_back(id.value);
488 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 return displayIds;
492}
493
494sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
495 Mutex::Autolock lock(mStateLock);
496 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497}
498
Ady Abraham37965d42018-11-01 13:43:32 -0700499status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
500 if (!outGetColorManagement) {
501 return BAD_VALUE;
502 }
503 *outGetColorManagement = useColorManagement;
504 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700505}
506
Lloyd Pique441d5042018-10-18 16:49:51 -0700507HWComposer& SurfaceFlinger::getHwComposer() const {
508 return mCompositionEngine->getHwComposer();
509}
510
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700511renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
512 return mCompositionEngine->getRenderEngine();
513}
514
Lloyd Pique70d91362018-10-18 16:02:55 -0700515compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
516 return *mCompositionEngine.get();
517}
518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519void SurfaceFlinger::bootFinished()
520{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700521 if (mStartPropertySetThread->join() != NO_ERROR) {
522 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 const nsecs_t now = systemTime();
525 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000526 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527
Mikael Pessa90092f42019-08-26 17:22:04 -0700528 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000529 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700530
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531 // wait patiently for the window manager death
532 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700533 mWindowManager = defaultServiceManager()->getService(name);
534 if (mWindowManager != 0) {
535 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 }
Robert Carr720e5062018-07-30 17:45:14 -0700537 sp<IBinder> input(defaultServiceManager()->getService(
538 String16("inputflinger")));
539 if (input == nullptr) {
540 ALOGE("Failed to link to input service");
541 } else {
542 mInputFlinger = interface_cast<IInputFlinger>(input);
543 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544
Steven Thomas050b2c82017-03-06 11:45:16 -0800545 if (mVrFlinger) {
546 mVrFlinger->OnBootFinished();
547 }
548
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700550 // formerly we would just kill the process, but we now ask it to exit so it
551 // can choose where to stop the animation.
552 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700553
554 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
555 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
556 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700557
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800559 readPersistentProperties();
560 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800561
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
563 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
564 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
565 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800566 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800567}
568
Dan Stoza436ccf32018-06-21 12:10:12 -0700569uint32_t SurfaceFlinger::getNewTexture() {
570 {
571 std::lock_guard lock(mTexturePoolMutex);
572 if (!mTexturePool.empty()) {
573 uint32_t name = mTexturePool.back();
574 mTexturePool.pop_back();
575 ATRACE_INT("TexturePoolSize", mTexturePool.size());
576 return name;
577 }
578
579 // The pool was too small, so increase it for the future
580 ++mTexturePoolSize;
581 }
582
583 // The pool was empty, so we need to get a new texture name directly using a
584 // blocking call to the main thread
585 uint32_t name = 0;
586 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
587 return name;
588}
589
Mathias Agopian3f844832013-08-07 21:24:32 -0700590void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700591 std::lock_guard lock(mTexturePoolMutex);
592 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
593 // to actually delete this or not based on mTexturePoolSize
594 mTexturePool.push_back(texture);
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700596}
597
Wei Wangf9b05ee2017-07-19 20:59:39 -0700598// Do not call property_set on main thread which will be blocked by init
599// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700601 ALOGI( "SurfaceFlinger's main thread ready to run. "
602 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700606 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800607 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d72019-10-09 10:39:09 -0700608 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
609 renderengine::RenderEngineCreationArgs::Builder()
610 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
611 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
612 .setUseColorManagerment(useColorManagement)
613 .setEnableProtectedContext(enable_protected_contents(false))
614 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800615 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d72019-10-09 10:39:09 -0700616 .setContextPriority(useContextPriority
617 ? renderengine::RenderEngine::ContextPriority::HIGH
618 : renderengine::RenderEngine::ContextPriority::MEDIUM)
619 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800620 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700621
622 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
623 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700624 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800625 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800626 // Process any initial hotplug and resulting display changes.
627 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700628 const auto display = getDefaultDisplayDeviceLocked();
629 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700630 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700631 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800632
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700634 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 // This callback is called from the vr flinger dispatch thread. We
636 // need to call signalTransaction(), which requires holding
637 // mStateLock when we're not on the main thread. Acquiring
638 // mStateLock from the vr flinger dispatch thread might trigger a
639 // deadlock in surface flinger (see b/66916578), so post a message
640 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700641 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700642 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
643 mVrFlingerRequestsDisplay = requestDisplay;
644 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700645 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
648 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700649 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700650 .value_or(0),
651 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 if (!mVrFlinger) {
653 ALOGE("Failed to start vrflinger");
654 }
655 }
656
Mathias Agopian92a979a2012-08-02 18:32:23 -0700657 // initialize our drawing state
658 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700659
Andy McFadden13a082e2012-08-24 10:16:42 -0700660 // set initial conditions (e.g. unblank default device)
661 initializeDisplays();
662
Steven Thomas137d4bc2019-07-25 16:55:14 -0700663 char primeShaderCache[PROPERTY_VALUE_MAX];
664 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
665 if (atoi(primeShaderCache)) {
666 getRenderEngine().primeCache();
667 }
Dan Stoza4e637772016-07-28 13:31:51 -0700668
Wei Wangf9b05ee2017-07-19 20:59:39 -0700669 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700670
671 const bool presentFenceReliable =
672 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
673 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700674
675 if (mStartPropertySetThread->Start() != NO_ERROR) {
676 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800677 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800678
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700680}
681
Romain Guy11d63f42017-07-20 12:47:14 -0700682void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700683 Mutex::Autolock _l(mStateLock);
684
Romain Guy11d63f42017-07-20 12:47:14 -0700685 char value[PROPERTY_VALUE_MAX];
686
687 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800688 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700689 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100691
692 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700693 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800694
695 property_get("persist.sys.sf.color_mode", value, "0");
696 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700697}
698
Mathias Agopiana67e4182012-06-19 17:26:12 -0700699void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800700 // Start boot animation service by setting a property mailbox
701 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700702 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800703 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 if (mStartPropertySetThread->join() != NO_ERROR) {
705 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700710 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
Mathias Agopian875d8e12013-06-07 15:35:48 -0700713size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700714 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700715}
716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800718
Jamie Gennis582270d2011-08-17 18:19:00 -0700719bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800721 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800722 return authenticateSurfaceTextureLocked(bufferProducer);
723}
724
725bool SurfaceFlinger::authenticateSurfaceTextureLocked(
726 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800727 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800728 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800729}
730
Brian Anderson6b376712017-04-04 10:51:39 -0700731status_t SurfaceFlinger::getSupportedFrameTimestamps(
732 std::vector<FrameEvent>* outSupported) const {
733 *outSupported = {
734 FrameEvent::REQUESTED_PRESENT,
735 FrameEvent::ACQUIRE,
736 FrameEvent::LATCH,
737 FrameEvent::FIRST_REFRESH_START,
738 FrameEvent::LAST_REFRESH_START,
739 FrameEvent::GPU_COMPOSITION_DONE,
740 FrameEvent::DEQUEUE_READY,
741 FrameEvent::RELEASE,
742 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700743 ConditionalLock _l(mStateLock,
744 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700745 if (!getHwComposer().hasCapability(
746 HWC2::Capability::PresentFenceIsNotReliable)) {
747 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
748 }
749 return NO_ERROR;
750}
751
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800752status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
753 if (!displayToken || !state) {
754 return BAD_VALUE;
755 }
756
757 Mutex::Autolock lock(mStateLock);
758
759 const auto display = getDisplayDeviceLocked(displayToken);
760 if (!display) {
761 return NAME_NOT_FOUND;
762 }
763
764 state->layerStack = display->getLayerStack();
765 state->orientation = display->getOrientation();
766
767 const Rect viewport = display->getViewport();
768 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
769
770 return NO_ERROR;
771}
772
773status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
774 if (!displayToken || !info) {
775 return BAD_VALUE;
776 }
777
778 Mutex::Autolock lock(mStateLock);
779
780 const auto display = getDisplayDeviceLocked(displayToken);
781 if (!display) {
782 return NAME_NOT_FOUND;
783 }
784
Dominik Laskowski55c85402020-01-21 16:25:47 -0800785 if (const auto connectionType = display->getConnectionType())
786 info->connectionType = *connectionType;
787 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800788 return INVALID_OPERATION;
789 }
790
791 if (mEmulatedDisplayDensity) {
792 info->density = mEmulatedDisplayDensity;
793 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800794 info->density = info->connectionType == DisplayConnectionType::Internal
795 ? mInternalDisplayDensity
796 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800797 }
798
799 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200800 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800801
802 return NO_ERROR;
803}
804
Dominik Laskowski22488f62019-03-28 09:53:04 -0700805status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800806 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 return BAD_VALUE;
809 }
810
Dominik Laskowski22488f62019-03-28 09:53:04 -0700811 Mutex::Autolock lock(mStateLock);
812
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800813 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800818 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700819
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dominik Laskowski075d3172018-05-24 15:50:06 -0700822 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700824
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 auto width = hwConfig->getWidth();
826 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800828 auto xDpi = hwConfig->getDpiX();
829 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 if (isInternal &&
832 (internalDisplayOrientation == ui::ROTATION_90 ||
833 internalDisplayOrientation == ui::ROTATION_270)) {
834 std::swap(width, height);
835 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 }
837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800839
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 if (mEmulatedDisplayDensity) {
841 config.xDpi = mEmulatedDisplayDensity;
842 config.yDpi = mEmulatedDisplayDensity;
843 } else {
844 config.xDpi = xDpi;
845 config.yDpi = yDpi;
846 }
847
848 const nsecs_t period = hwConfig->getVsyncPeriod();
849 config.refreshRate = 1e9f / period;
850
851 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
852 config.appVsyncOffset = offsets.late.app;
853 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854
Andy McFadden91b2ca82014-06-13 14:04:23 -0700855 // This is how far in advance a buffer must be queued for
856 // presentation at a given time. If you want a buffer to appear
857 // on the screen at time N, you must submit the buffer before
858 // (N - presentationDeadline).
859 //
860 // Normally it's one full refresh period (to give SF a chance to
861 // latch the buffer), but this can be reduced by configuring a
862 // DispSync offset. Any additional delays introduced by the hardware
863 // composer or panel must be accounted for here.
864 //
865 // We add an additional 1ms to allow for processing time and
866 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800867 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700868
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800869 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700870 }
871
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 return NO_ERROR;
873}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700874
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700875status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
876 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700877 return BAD_VALUE;
878 }
879
Ana Krulecc2870422019-01-29 19:00:58 -0800880 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700881 return NO_ERROR;
882}
883
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700884int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
885 const auto display = getDisplayDevice(displayToken);
886 if (!display) {
887 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800888 return BAD_VALUE;
889 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700890
Steven Thomasc9098452019-09-30 17:15:05 -0700891 if (display->isPrimary()) {
892 std::lock_guard<std::mutex> lock(mActiveConfigLock);
893 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800894 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700895 }
Steven Thomasc9098452019-09-30 17:15:05 -0700896 }
Ady Abraham2139f732019-11-13 18:56:40 -0800897
898 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700899}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700900
Ady Abraham03b02dd2019-03-21 15:40:11 -0700901void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800902 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800903 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
904 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800905
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800906 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800907 // config twice. However event generation config might have changed so we need to update it
908 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800909 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700910 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
911 mDesiredActiveConfig = info;
912 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800913
914 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800915 // This will trigger HWC refresh without resetting the idle timer.
916 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700917 // Start receiving vsync samples now, so that we can detect a period
918 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800919 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700920 // As we called to set period, we will call to onRefreshRateChangeCompleted once
921 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700922 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800923
Ady Abraham9e16a482019-12-03 17:19:41 -0800924 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
925 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700928
929 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800930 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700931 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932}
933
934status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
935 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800936
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100937 if (!displayToken) {
938 return BAD_VALUE;
939 }
Ady Abraham838de062019-02-04 10:24:03 -0800940
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100941 status_t result = NO_ERROR;
942
943 postMessageSync(new LambdaMessage([&]() {
944 const auto display = getDisplayDeviceLocked(displayToken);
945 if (!display) {
946 ALOGE("Attempt to set allowed display configs for invalid display token %p",
947 displayToken.get());
948 result = BAD_VALUE;
949 } else if (display->isVirtual()) {
950 ALOGW("Attempt to set allowed display configs for virtual display");
951 result = BAD_VALUE;
952 } else {
953 HwcConfigIndexType config(mode);
954 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
955 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
956 refreshRate.fps);
957 }
958 }));
959
960 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961}
962
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963void SurfaceFlinger::setActiveConfigInternal() {
964 ATRACE_CALL();
965
Dominik Laskowski22488f62019-03-28 09:53:04 -0700966 const auto display = getDefaultDisplayDeviceLocked();
967 if (!display) {
968 return;
969 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970
Dominik Laskowski22488f62019-03-28 09:53:04 -0700971 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800972 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700973 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 display->setActiveConfig(mUpcomingActiveConfig.configId);
975
Ady Abraham2139f732019-11-13 18:56:40 -0800976 auto refreshRate =
977 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800978 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
979 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800980 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700981
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800982 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700983 const nsecs_t vsyncPeriod =
984 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
985 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800986 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700987 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800988 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
Ady Abraham53852a52019-05-28 18:07:44 -0700991void SurfaceFlinger::desiredActiveConfigChangeDone() {
992 std::lock_guard<std::mutex> lock(mActiveConfigLock);
993 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
994 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700995
Kevin DuBois5988f482020-01-17 09:03:32 -0800996 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800997 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800998 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800999 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1000 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001001}
1002
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001004 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001005 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001007 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001009 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 return true;
1011 }
1012
1013 // We received the present fence from the HWC, so we assume it successfully updated
1014 // the config, hence we update SF.
1015 mCheckPendingFence = false;
1016 setActiveConfigInternal();
1017 }
1018
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 // Store the local variable to release the lock.
1020 ActiveConfigInfo desiredActiveConfig;
1021 {
1022 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001023 if (!mDesiredActiveConfigChanged) {
1024 return false;
1025 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026 desiredActiveConfig = mDesiredActiveConfig;
1027 }
1028
Ady Abraham2139f732019-11-13 18:56:40 -08001029 auto refreshRate =
1030 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1031 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1032 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001033 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1035 // display is not valid or we are already in the requested mode
1036 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001037 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040
Ady Abraham838de062019-02-04 10:24:03 -08001041 // Desired active config was set, it is different than the config currently in use, however
1042 // allowed configs might have change by the time we process the refresh.
1043 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001044 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001045 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001046 return false;
1047 }
Alec Mouri7f015182019-07-11 13:56:22 -07001048
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049 mUpcomingActiveConfig = desiredActiveConfig;
1050 const auto displayId = display->getId();
1051 LOG_ALWAYS_FATAL_IF(!displayId);
1052
Ady Abraham2139f732019-11-13 18:56:40 -08001053 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001055 // TODO(b/142753666) use constrains
1056 HWC2::VsyncPeriodChangeConstraints constraints;
1057 constraints.desiredTimeNanos = systemTime();
1058 constraints.seamlessRequired = false;
1059
1060 HWC2::VsyncPeriodChangeTimeline outTimeline;
1061 auto status =
1062 getHwComposer().setActiveConfigWithConstraints(*displayId,
1063 mUpcomingActiveConfig.configId.value(),
1064 constraints, &outTimeline);
1065 if (status != NO_ERROR) {
1066 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1067 return false;
1068 }
1069
1070 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1071 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001072 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001073 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001074}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1077 Vector<ColorMode>* outColorModes) {
1078 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001079 return BAD_VALUE;
1080 }
1081
Peiyong Lina52f0292018-03-14 17:26:31 -07001082 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001083 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001084 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001085 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1086
1087 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1088 if (!displayId) {
1089 return NAME_NOT_FOUND;
1090 }
1091
Dominik Laskowski075d3172018-05-24 15:50:06 -07001092 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001093 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001094 }
Michael Wright28f24d02016-07-12 13:30:53 -07001095 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001096
1097 // If it's built-in display and the configuration claims it's not wide color capable,
1098 // filter out all wide color modes. The typical reason why this happens is that the
1099 // hardware is not good enough to support GPU composition of wide color, and thus the
1100 // OEMs choose to disable this capability.
1101 if (isInternalDisplay && !hasWideColorDisplay) {
1102 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1103 isWideColorMode);
1104 } else {
1105 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1106 }
Michael Wright28f24d02016-07-12 13:30:53 -07001107
1108 return NO_ERROR;
1109}
1110
Daniel Solomon42d04562019-01-20 21:03:19 -08001111status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1112 ui::DisplayPrimaries &primaries) {
1113 if (!displayToken) {
1114 return BAD_VALUE;
1115 }
1116
1117 // Currently we only support this API for a single internal display.
1118 if (getInternalDisplayToken() != displayToken) {
1119 return BAD_VALUE;
1120 }
1121
1122 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1123 return NO_ERROR;
1124}
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1127 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001128 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001129 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001130 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001131}
1132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001134 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 Vector<ColorMode> modes;
1136 getDisplayColorModes(displayToken, &modes);
1137 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1138 if (mode < ColorMode::NATIVE || !exists) {
1139 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1140 decodeColorMode(mode).c_str(), mode, displayToken.get());
1141 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001142 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143 const auto display = getDisplayDevice(displayToken);
1144 if (!display) {
1145 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1146 decodeColorMode(mode).c_str(), mode, displayToken.get());
1147 } else if (display->isVirtual()) {
1148 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1149 decodeColorMode(mode).c_str(), mode);
1150 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001151 display->getCompositionDisplay()->setColorProfile(
1152 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1153 RenderIntent::COLORIMETRIC,
1154 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 }
1156 }));
1157
Michael Wright28f24d02016-07-12 13:30:53 -07001158 return NO_ERROR;
1159}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001160
Galia Peycheva5492cb52019-10-30 14:13:16 +01001161status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1162 bool* outSupport) const {
1163 Mutex::Autolock _l(mStateLock);
1164
1165 if (!displayToken) {
1166 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1167 return BAD_VALUE;
1168 }
1169 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1170 if (!displayId) {
1171 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1172 displayToken.get());
1173 return NAME_NOT_FOUND;
1174 }
1175 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1176 HWC2::DisplayCapability::AutoLowLatencyMode);
1177 return NO_ERROR;
1178}
1179
1180void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1181 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1182}
1183
1184void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1185 if (!displayToken) {
1186 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1187 return;
1188 }
1189 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1190 if (!displayId) {
1191 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1192 displayToken.get());
1193 return;
1194 }
1195
1196 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1197}
1198
1199status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1200 bool* outSupport) const {
1201 Mutex::Autolock _l(mStateLock);
1202
1203 if (!displayToken) {
1204 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1205 return BAD_VALUE;
1206 }
1207 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1208 if (!displayId) {
1209 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1210 displayToken.get());
1211 return NAME_NOT_FOUND;
1212 }
1213
1214 std::vector<HWC2::ContentType> outSupportedContentTypes;
1215 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1216 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1217 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1218 return NO_ERROR;
1219}
1220
1221void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1222 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1223}
1224
1225void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1226 if (!displayToken) {
1227 ALOGE("setGameContentType() failed. Missing display token.");
1228 return;
1229 }
1230 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1231 if (!displayId) {
1232 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1233 displayToken.get());
1234 return;
1235 }
1236
1237 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1238 getHwComposer().setContentType(*displayId, type);
1239}
1240
Svetoslavd85084b2014-03-20 10:28:31 -07001241status_t SurfaceFlinger::clearAnimationFrameStats() {
1242 Mutex::Autolock _l(mStateLock);
1243 mAnimFrameTracker.clearStats();
1244 return NO_ERROR;
1245}
1246
1247status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1248 Mutex::Autolock _l(mStateLock);
1249 mAnimFrameTracker.getStats(outStats);
1250 return NO_ERROR;
1251}
1252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001253status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1254 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001255 Mutex::Autolock _l(mStateLock);
1256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001257 const auto display = getDisplayDeviceLocked(displayToken);
1258 if (!display) {
1259 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001260 return BAD_VALUE;
1261 }
1262
Peiyong Linfb069302018-04-25 14:34:31 -07001263 // At this point the DisplayDeivce should already be set up,
1264 // meaning the luminance information is already queried from
1265 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001266 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001267 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1268 capabilities.getDesiredMaxLuminance(),
1269 capabilities.getDesiredMaxAverageLuminance(),
1270 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001271
1272 return NO_ERROR;
1273}
1274
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001275std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1276 const DisplayDevice& display) const {
1277 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1278 // avoid repetitive HAL IPC and EDID parsing.
1279 const auto displayId = display.getId();
1280 LOG_FATAL_IF(!displayId);
1281
1282 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1283 LOG_FATAL_IF(!hwcDisplayId);
1284
1285 uint8_t port;
1286 DisplayIdentificationData data;
1287 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1288 ALOGV("%s: No identification data.", __FUNCTION__);
1289 return {};
1290 }
1291
1292 const auto info = parseDisplayIdentificationData(port, data);
1293 if (!info) {
1294 return {};
1295 }
1296 return info->deviceProductInfo;
1297}
1298
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001299status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1300 ui::PixelFormat* outFormat,
1301 ui::Dataspace* outDataspace,
1302 uint8_t* outComponentMask) const {
1303 if (!outFormat || !outDataspace || !outComponentMask) {
1304 return BAD_VALUE;
1305 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001306 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001307 if (!display || !display->getId()) {
1308 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1309 return BAD_VALUE;
1310 }
1311 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1312 outDataspace, outComponentMask);
1313}
1314
Kevin DuBois74e53772018-11-19 10:52:38 -08001315status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1316 bool enable, uint8_t componentMask,
1317 uint64_t maxFrames) const {
1318 const auto display = getDisplayDevice(displayToken);
1319 if (!display || !display->getId()) {
1320 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1321 return BAD_VALUE;
1322 }
1323
1324 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1325 componentMask, maxFrames);
1326}
1327
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001328status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1329 uint64_t maxFrames, uint64_t timestamp,
1330 DisplayedFrameStats* outStats) const {
1331 const auto display = getDisplayDevice(displayToken);
1332 if (!display || !display->getId()) {
1333 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1334 return BAD_VALUE;
1335 }
1336
1337 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1338 outStats);
1339}
1340
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001341status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1342 if (!outSupported) {
1343 return BAD_VALUE;
1344 }
1345 *outSupported = getRenderEngine().supportsProtectedContent();
1346 return NO_ERROR;
1347}
1348
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001349status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1350 bool* outIsWideColorDisplay) const {
1351 if (!displayToken || !outIsWideColorDisplay) {
1352 return BAD_VALUE;
1353 }
1354 Mutex::Autolock _l(mStateLock);
1355 const auto display = getDisplayDeviceLocked(displayToken);
1356 if (!display) {
1357 return BAD_VALUE;
1358 }
Peiyong Linff84a152019-05-17 18:36:19 -07001359
1360 // Use hasWideColorDisplay to override built-in display.
1361 const auto displayId = display->getId();
1362 if (displayId && displayId == getInternalDisplayIdLocked()) {
1363 *outIsWideColorDisplay = hasWideColorDisplay;
1364 return NO_ERROR;
1365 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001366 *outIsWideColorDisplay = display->hasWideColorGamut();
1367 return NO_ERROR;
1368}
1369
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001370status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001371 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001372 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001373
Dominik Laskowski6505f792019-09-18 11:10:05 -07001374 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1375 mEventQueue->setEventConnection(
1376 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001377 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001378 }));
1379
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001380 return NO_ERROR;
1381}
1382
1383status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001384 Mutex::Autolock lock(mStateLock);
1385 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001386}
1387
Lloyd Pique755e3192018-01-31 16:46:15 -08001388status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1389 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001390 // Try to acquire a lock for 1s, fail gracefully
1391 const status_t err = mStateLock.timedLock(s2ns(1));
1392 const bool locked = (err == NO_ERROR);
1393 if (!locked) {
1394 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1395 return TIMED_OUT;
1396 }
1397
1398 outLayers->clear();
1399 mCurrentState.traverseInZOrder([&](Layer* layer) {
1400 outLayers->push_back(layer->getLayerDebugInfo());
1401 });
1402
1403 mStateLock.unlock();
1404 return NO_ERROR;
1405}
1406
Peiyong Linc6780972018-10-28 15:24:08 -07001407status_t SurfaceFlinger::getCompositionPreference(
1408 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1409 Dataspace* outWideColorGamutDataspace,
1410 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001411 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001412 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001413 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001414 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001415 return NO_ERROR;
1416}
1417
Dan Stozaec460082018-12-17 15:35:09 -08001418status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1419 const sp<IBinder>& stopLayerHandle,
1420 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001421 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001422 return BAD_VALUE;
1423 }
1424 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001425 return NO_ERROR;
1426}
1427
Dan Stozaec460082018-12-17 15:35:09 -08001428status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001429 if (!listener) {
1430 return BAD_VALUE;
1431 }
Dan Stozaec460082018-12-17 15:35:09 -08001432 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001433 return NO_ERROR;
1434}
Dan Gittik57e63c52019-01-18 16:37:54 +00001435
1436status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1437 bool* outSupport) const {
1438 if (!displayToken || !outSupport) {
1439 return BAD_VALUE;
1440 }
1441 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1442 if (!displayId) {
1443 return NAME_NOT_FOUND;
1444 }
1445 *outSupport =
1446 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1447 return NO_ERROR;
1448}
1449
1450status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1451 float brightness) const {
1452 if (!displayToken) {
1453 return BAD_VALUE;
1454 }
1455 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1456 if (!displayId) {
1457 return NAME_NOT_FOUND;
1458 }
1459 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1460}
1461
Ady Abraham8532d012019-05-08 14:50:56 -07001462status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1463 PowerHint powerHint = static_cast<PowerHint>(hintId);
1464
1465 if (powerHint == PowerHint::INTERACTION) {
1466 mScheduler->notifyTouchEvent();
1467 }
1468
1469 return NO_ERROR;
1470}
1471
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001472// ----------------------------------------------------------------------------
1473
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001474sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001475 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001476 const auto& handle =
1477 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001478
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001479 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001480}
1481
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001482// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001483
1484void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001485 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001486}
1487
1488void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001489 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001490 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001491 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001492}
1493
1494void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001495 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001496 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001497 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001498}
1499
1500void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001501 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001502 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001503}
1504
1505status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001506 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001507 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001508}
1509
1510status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001511 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001512 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513 if (res == NO_ERROR) {
1514 msg->wait();
1515 }
1516 return res;
1517}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001518
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001519void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001520 do {
1521 waitForEvent();
1522 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001523}
1524
Dominik Laskowski83b88212018-12-11 13:34:06 -08001525nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001526 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001527 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1528 return 0;
1529 }
1530
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001531 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001532}
1533
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001534void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001535 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001536 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001537 ATRACE_NAME("SF onVsync");
1538
Steven Thomas3cfac282017-02-06 12:29:30 -08001539 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001540 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001541 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001542 return;
1543 }
1544
Dominik Laskowski075d3172018-05-24 15:50:06 -07001545 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001546 return;
1547 }
1548
Dominik Laskowski075d3172018-05-24 15:50:06 -07001549 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001550 // For now, we don't do anything with external display vsyncs.
1551 return;
1552 }
1553
Alec Mourif8e689c2019-05-20 18:32:22 -07001554 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001555 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001556 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001557 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001558 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001559}
1560
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001562 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1563 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564}
1565
Ady Abraham2139f732019-11-13 18:56:40 -08001566bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001567 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001568}
1569
Ady Abraham2139f732019-11-13 18:56:40 -08001570void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1571 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001572 const auto display = getDefaultDisplayDeviceLocked();
1573 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001574 return;
1575 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001576 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001577
Ana Krulec7d1d6832018-12-27 11:10:09 -08001578 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001579 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1580 ALOGV("Skipping config %d as it is not part of allowed configs",
1581 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001582 return;
1583 }
1584
Ady Abraham2139f732019-11-13 18:56:40 -08001585 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001586}
1587
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001588void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001589 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001590 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001591 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592
Lloyd Piqueba04e622017-12-14 17:11:26 -08001593 // Ignore events that do not have the right sequenceId.
1594 if (sequenceId != getBE().mComposerSequenceId) {
1595 return;
1596 }
1597
Steven Thomasb02664d2017-07-26 18:48:28 -07001598 // Only lock if we're not on the main thread. This function is normally
1599 // called on a hwbinder thread, but for the primary display it's called on
1600 // the main thread with the state lock already held, so don't attempt to
1601 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001602 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001603
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001604 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001605
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001606 if (std::this_thread::get_id() == mMainThreadId) {
1607 // Process all pending hot plug events immediately if we are on the main thread.
1608 processDisplayHotplugEventsLocked();
1609 }
1610
Lloyd Piqueba04e622017-12-14 17:11:26 -08001611 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001612}
1613
Ady Abraham7159f572019-10-11 11:10:18 -07001614void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001615 int32_t sequenceId, hwc2_display_t /*display*/,
1616 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1617 Mutex::Autolock lock(mStateLock);
1618 if (sequenceId != getBE().mComposerSequenceId) {
1619 return;
1620 }
1621 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001622}
1623
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001624void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1625 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1626 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1627}
1628
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001629void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001630 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001631 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001632 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001633 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001634 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001635}
1636
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001637void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001638 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001639
1640 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1641 // display power state.
1642 postMessageAsync(new LambdaMessage(
1643 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1644}
1645
1646void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1647 ATRACE_CALL();
1648
Ady Abraham27c70212019-06-11 10:52:26 -07001649 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1650
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001651 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001652 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1653 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001654 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001655 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001656 }
Mathias Agopian86303202012-07-24 22:46:10 -07001657}
1658
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001659// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001660void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001661 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001662 // Clear the drawing state so that the logic inside of
1663 // handleTransactionLocked will fire. It will determine the delta between
1664 // mCurrentState and mDrawingState and re-apply all changes when we make the
1665 // transition.
1666 mDrawingState.displays.clear();
1667 mDisplays.clear();
1668}
1669
Steven Thomas050b2c82017-03-06 11:45:16 -08001670void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001671 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001672 if (!mVrFlinger)
1673 return;
1674 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001675 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001676 return;
1677 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001678
Lloyd Pique441d5042018-10-18 16:49:51 -07001679 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001680 ALOGE("Vr flinger is only supported for remote hardware composer"
1681 " service connections. Ignoring request to transition to vr"
1682 " flinger.");
1683 mVrFlingerRequestsDisplay = false;
1684 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001685 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001686
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001687 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001688
Steven Thomas0123ac62018-07-12 11:32:34 -07001689 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001690 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001691
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001692 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001693
1694 // Clear out all the output layers from the composition engine for all
1695 // displays before destroying the hardware composer interface. This ensures
1696 // any HWC layers are destroyed through that interface before it becomes
1697 // invalid.
1698 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001699 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001700 }
1701
Steven Thomas0123ac62018-07-12 11:32:34 -07001702 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1703 // called below. Clear the reference now so we don't accidentally use it
1704 // later.
1705 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001706
Steven Thomasb02664d2017-07-26 18:48:28 -07001707 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001708 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001709 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710
Steven Thomasb02664d2017-07-26 18:48:28 -07001711 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001712 // Delete the current instance before creating the new one
1713 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1714 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1715 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001716 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001719 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001720
1721 if (vrFlingerRequestsDisplay) {
1722 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001723 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001724
1725 mVisibleRegionsDirty = true;
1726 invalidateHwcGeometry();
1727
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001728 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001729 display = getDefaultDisplayDeviceLocked();
1730 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001731 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001732
Steven Thomasb02664d2017-07-26 18:48:28 -07001733 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001734 const nsecs_t vsyncPeriod = getVsyncPeriod();
1735 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001736
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001737 // The present fences returned from vr_hwc are not an accurate
1738 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001739 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001740
Steven Thomasb02664d2017-07-26 18:48:28 -07001741 // Use phase of 0 since phase is not known.
1742 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001743 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001744 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001745
Ana Krulecc2870422019-01-29 19:00:58 -08001746 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001747
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001748 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001749 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001750}
1751
Ady Abraham11579302019-09-19 12:35:58 -07001752bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1753 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001754 // We are storing the last 2 present fences. If sf's phase offset is to be
1755 // woken up before the actual vsync but targeting the next vsync, we need to check
1756 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001757 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1758 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001759
Ady Abraham11579302019-09-19 12:35:58 -07001760 if (fence == Fence::NO_FENCE) {
1761 return false;
1762 }
1763
1764 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1765 fence->wait(graceTimeMs);
1766 }
1767
1768 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001769}
1770
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001771void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001772 DisplayStatInfo stats;
1773 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001774 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001775 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001776 mExpectedPresentTime.store(
1777 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001778}
1779
Dominik Laskowski22488f62019-03-28 09:53:04 -07001780void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001781 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001782 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001783 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001784 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001785 // calculate the expected present time once and use the cached
1786 // value throughout this frame to make sure all layers are
1787 // seeing this same value.
1788 populateExpectedPresentTime();
1789
Ady Abraham11579302019-09-19 12:35:58 -07001790 // When Backpressure propagation is enabled we want to give a small grace period
1791 // for the present fence to fire instead of just giving up on this frame to handle cases
1792 // where present fence is just about to get signaled.
1793 const int graceTimeForPresentFenceMs =
1794 (mPropagateBackpressure &&
1795 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1796 ? 1
1797 : 0;
1798 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1799 previousFrameMissed(
1800 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001801 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1802 mHadDeviceComposition && frameMissed};
1803 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1804 mHadClientComposition && frameMissed};
1805
Alec Mouricc0fc602019-02-26 21:45:19 -08001806 if (frameMissed) {
1807 mFrameMissedCount++;
1808 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001809 if (mMissedFrameJankCount == 0) {
1810 mMissedFrameJankStart = systemTime();
1811 }
1812 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001813 }
1814
Alec Mouri40189b02019-03-05 15:07:54 -08001815 if (hwcFrameMissed) {
1816 mHwcFrameMissedCount++;
1817 }
1818
1819 if (gpuFrameMissed) {
1820 mGpuFrameMissedCount++;
1821 }
1822
Ady Abrahamadb9a992019-09-19 21:21:55 +00001823 if (frameMissed && mPropagateBackpressure) {
1824 if ((hwcFrameMissed && !gpuFrameMissed) ||
1825 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001826 signalLayerUpdate();
1827 break;
1828 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001829 }
Dan Stoza50182882016-07-08 12:02:20 -07001830
Alec Mouri989ddbe2020-02-06 09:26:19 -08001831 // Our jank window is always at least 100ms since we missed a
1832 // frame...
1833 static constexpr nsecs_t kMinJankyDuration =
1834 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1835 // ...but if it's larger than 1s then we missed the trace cutoff.
1836 static constexpr nsecs_t kMaxJankyDuration =
1837 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1838 // If we're in a user build then don't push any atoms
1839 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1840 const auto displayDevice = getDefaultDisplayDeviceLocked();
1841 // Only report jank when the display is on, as displays in DOZE
1842 // power mode may operate at a different frame rate than is
1843 // reported in their config, which causes noticeable (but less
1844 // severe) jank.
1845 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1846 const nsecs_t currentTime = systemTime();
1847 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1848 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1849 ATRACE_NAME("Jank detected");
1850 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1851 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1852 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1853 jankyDurationMillis, mMissedFrameJankCount);
1854 }
1855
1856 // We either reported a jank event or we missed the trace
1857 // window, so clear counters here.
1858 if (jankDuration > kMinJankyDuration) {
1859 mMissedFrameJankCount = 0;
1860 mMissedFrameJankStart = 0;
1861 }
1862 }
1863 }
1864
Steven Thomas050b2c82017-03-06 11:45:16 -08001865 // Now that we're going to make it to the handleMessageTransaction()
1866 // call below it's safe to call updateVrFlinger(), which will
1867 // potentially trigger a display handoff.
1868 updateVrFlinger();
1869
Dan Stoza6b9454d2014-11-07 16:00:59 -08001870 bool refreshNeeded = handleMessageTransaction();
1871 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001872
Ana Krulecc84d09b2019-11-02 23:10:29 +01001873 // Layers need to get updated (in the previous line) before we can use them for
1874 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001875 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1876 // and may eventually call to ~Layer() if it holds the last reference
1877 {
1878 Mutex::Autolock _l(mStateLock);
1879 mScheduler->chooseRefreshRateForContent();
1880 }
1881
Ana Krulecc84d09b2019-11-02 23:10:29 +01001882 if (performSetActiveConfig()) {
1883 break;
1884 }
1885
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001886 updateCursorAsync();
1887 updateInputFlinger();
1888
Dan Stoza58784442014-12-02 16:58:17 -08001889 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001890 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001891 // Signal a refresh if a transaction modified the window state,
1892 // a new buffer was latched, or if HWC has requested a full
1893 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001894 if (mFrameStartTime <= 0) {
1895 // We should only use the time of the first invalidate
1896 // message that signals a refresh as the beginning of the
1897 // frame. Otherwise the real frame time will be
1898 // underestimated.
1899 mFrameStartTime = frameStart;
1900 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001901 signalRefresh();
1902 }
1903 break;
1904 }
1905 case MessageQueue::REFRESH: {
1906 handleMessageRefresh();
1907 break;
1908 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001909 }
1910}
1911
Dan Stoza6b9454d2014-11-07 16:00:59 -08001912bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001913 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001914 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001915
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001916 bool flushedATransaction = flushTransactionQueues();
1917
1918 bool runHandleTransaction = transactionFlags &&
1919 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1920
1921 if (runHandleTransaction) {
1922 handleTransaction(eTransactionMask);
1923 } else {
1924 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001925 }
1926
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001927 if (transactionFlushNeeded()) {
1928 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001929 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001930
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001931 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001932}
1933
Mathias Agopian4fec8732012-06-29 14:12:52 -07001934void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001936
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001937 mRefreshPending = false;
1938
Lloyd Piqueab039b52019-02-13 14:22:42 -08001939 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001940 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001941 for (const auto& [_, display] : mDisplays) {
1942 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1943 }
1944 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001945 if (auto layerFE = layer->getCompositionEngineLayerFE())
1946 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001947 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001948 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1949 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001950 if (auto layerFE = layer->getCompositionEngineLayerFE())
1951 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001952 }
1953
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001954 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001955 refreshArgs.outputColorSetting = useColorManagement
1956 ? mDisplayColorSetting
1957 : compositionengine::OutputColorSetting::kUnmanaged;
1958 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1959 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001960
1961 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1962 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001963 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001964
1965 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1966 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1967 mDrawingState.colorMatrixChanged = false;
1968 }
1969
1970 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1971
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001972 if (mDebugRegion != 0) {
1973 refreshArgs.devOptFlashDirtyRegionsDelay =
1974 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1975 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001976
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001977 mGeometryInvalid = false;
1978
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001979 // Store the present time just before calling to the composition engine so we could notify
1980 // the scheduler.
1981 const auto presentTime = systemTime();
1982
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001983 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001984 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1985 // Reset the frame start time now that we've recorded this frame.
1986 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001987
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001988 mScheduler->onDisplayRefreshed(presentTime);
1989
David Sodmanfa9b2af2017-12-24 13:28:59 -08001990 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001991 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001992
Lloyd Pique66d68602019-02-13 14:23:31 -08001993 mHadClientComposition =
1994 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1995 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001996 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1997 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001998 });
1999 mHadDeviceComposition =
2000 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2001 auto& displayDevice = tokenDisplayPair.second;
2002 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2003 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002004 mReusedClientComposition =
2005 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2006 auto& displayDevice = tokenDisplayPair.second;
2007 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2008 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002009
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002010 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002011
David Sodman7e4ae112018-02-09 15:02:28 -08002012 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002013 if (mVisibleRegionsDirty) {
2014 mVisibleRegionsDirty = false;
2015 if (mTracingEnabled) {
2016 mTracing.notify("visibleRegionsDirty");
2017 }
2018 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002019
2020 if (mCompositionEngine->needsAnotherUpdate()) {
2021 signalLayerUpdate();
2022 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002024
David Sodmanfa9b2af2017-12-24 13:28:59 -08002025
2026bool SurfaceFlinger::handleMessageInvalidate() {
2027 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002028 bool refreshNeeded = handlePageFlip();
2029
Vishnu Nair4351ad52019-02-11 14:13:02 -08002030 if (mVisibleRegionsDirty) {
2031 computeLayerBounds();
2032 }
2033
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002034 for (auto& layer : mLayersPendingRefresh) {
2035 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002036 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002037 invalidateLayerStack(layer, visibleReg);
2038 }
2039 mLayersPendingRefresh.clear();
2040 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041}
2042
Ana Krulece588e312018-09-18 12:32:24 -07002043void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2044 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002045 // Update queue of past composite+present times and determine the
2046 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002047 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002049 while (!getBE().mCompositePresentTimes.empty()) {
2050 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 // Cached values should have been updated before calling this method,
2052 // which helps avoid duplicate syscalls.
2053 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2054 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2055 break;
2056 }
2057 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002058 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059 }
2060
2061 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002062 while (getBE().mCompositePresentTimes.size() > 16) {
2063 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064 }
2065
Ana Krulece588e312018-09-18 12:32:24 -07002066 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002067}
2068
Ana Krulece588e312018-09-18 12:32:24 -07002069void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2070 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002071 // Integer division and modulo round toward 0 not -inf, so we need to
2072 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002073 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2074 ? (stats.vsyncPeriod -
2075 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2076 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077
Ady Abraham9e16a482019-12-03 17:19:41 -08002078 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002079 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002080 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002081 }
2082
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002083 // Snap the latency to a value that removes scheduling jitter from the
2084 // composition and present times, which often have >1ms of jitter.
2085 // Reducing jitter is important if an app attempts to extrapolate
2086 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002087 // Snapping also allows an app to precisely calculate
2088 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002089 nsecs_t bias = stats.vsyncPeriod / 2;
2090 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2091 nsecs_t snappedCompositeToPresentLatency =
2092 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002093
David Sodman99974d22017-11-28 12:04:33 -08002094 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002095 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2096 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002097 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098}
2099
David Sodman2b406362017-12-15 13:33:47 -08002100void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002101{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 ATRACE_CALL();
2103 ALOGV("postComposition");
2104
Brian Andersonf6386862016-10-31 16:34:13 -07002105 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002106 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002107 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002108 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002109 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002110 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002111
David Sodman73beded2017-11-15 11:56:06 -08002112 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002114 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002115 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002116 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2117 ->getRenderSurface()
2118 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002119 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 } else {
2121 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2122 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002123
David Sodman73beded2017-11-15 11:56:06 -08002124 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002125 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2126 mPreviousPresentFences[0] = displayDevice
2127 ? getHwComposer().getPresentFence(*displayDevice->getId())
2128 : Fence::NO_FENCE;
2129 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002130 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002131
Ana Krulece588e312018-09-18 12:32:24 -07002132 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002133 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002134
Lloyd Piqueab039b52019-02-13 14:22:42 -08002135 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2136 // be sampled a little later than when we started doing work for this frame,
2137 // but that should be okay since updateCompositorTiming has snapping logic.
2138 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2139 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002140 CompositorTiming compositorTiming;
2141 {
David Sodman99974d22017-11-28 12:04:33 -08002142 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2143 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002144 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002145
Edgar Arriaga844fa672020-01-16 14:21:42 -08002146 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002147 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2148 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002149 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002150 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002151 }
Robert Carr2047fae2016-11-28 14:09:09 -08002152 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002153
Ady Abraham92fa2f42020-02-11 15:33:56 -08002154 if (displayDevice && displayDevice->isPrimary() &&
2155 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002156 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002157 }
2158
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002159 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002160 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2161 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002162 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002163 }
2164 }
2165
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002166 if (mAnimCompositionPending) {
2167 mAnimCompositionPending = false;
2168
Brian Anderson4e606e32017-03-16 15:34:57 -07002169 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002170 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002171 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002172 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002173 // The HWC doesn't support present fences, so use the refresh
2174 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002175 const nsecs_t presentTime =
2176 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002177 mAnimFrameTracker.setActualPresentTime(presentTime);
2178 }
2179 mAnimFrameTracker.advanceFrame();
2180 }
Dan Stozab90cf072015-03-05 11:05:59 -08002181
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002183 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002184 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002185 }
2186
Vishnu Nair9b079a22020-01-21 14:36:08 -08002187 if (mReusedClientComposition) {
2188 mTimeStats->incrementClientCompositionReusedFrames();
2189 }
2190
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002191 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002192
Alec Mouri717bcb62020-02-10 17:07:19 -08002193 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2194 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2195 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2196
Lloyd Pique32cbe282018-10-19 13:09:22 -07002197 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2198 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002199 return;
2200 }
2201
2202 nsecs_t currentTime = systemTime();
2203 if (mHasPoweredOff) {
2204 mHasPoweredOff = false;
2205 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002206 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002207 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002208 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2209 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002210 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002211 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002212 }
David Sodman4a36e932017-11-07 14:29:47 -08002213 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002214 }
David Sodman4a36e932017-11-07 14:29:47 -08002215 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002216
2217 {
2218 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002219 if (mTexturePool.size() < mTexturePoolSize) {
2220 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002221 const size_t offset = mTexturePool.size();
2222 mTexturePool.resize(mTexturePoolSize);
2223 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2224 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002225 } else if (mTexturePool.size() > mTexturePoolSize) {
2226 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2227 const size_t offset = mTexturePoolSize;
2228 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2229 mTexturePool.resize(mTexturePoolSize);
2230 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002231 }
2232 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002233
Ady Abrahambe0f9482019-04-24 15:41:53 -07002234 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002235 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002236
Kevin DuBois413287f2019-02-25 08:46:47 -08002237 if (mLumaSampling && mRegionSamplingThread) {
2238 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002239 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002240
2241 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2242 // side-effect of getTotalSize(), so we check that again here
2243 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002244 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002245 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2246 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002247}
2248
Vishnu Nair4351ad52019-02-11 14:13:02 -08002249void SurfaceFlinger::computeLayerBounds() {
2250 for (const auto& pair : mDisplays) {
2251 const auto& displayDevice = pair.second;
2252 const auto display = displayDevice->getCompositionDisplay();
2253 for (const auto& layer : mDrawingState.layersSortedByZ) {
2254 // only consider the layers on the given layer stack
2255 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002256 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002257 }
2258
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002259 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2260 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002261 }
2262 }
2263}
2264
David Sodmanfa9b2af2017-12-24 13:28:59 -08002265void SurfaceFlinger::postFrame()
2266{
2267 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002268 const auto display = getDefaultDisplayDeviceLocked();
2269 if (display && getHwComposer().isConnected(*display->getId())) {
2270 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002271 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2272 logFrameStats();
2273 }
2274 }
2275}
2276
Mathias Agopian87baae12012-07-31 12:38:26 -07002277void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002278{
Mathias Agopian841cde52012-03-01 15:44:37 -08002279 ATRACE_CALL();
2280
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002281 // here we keep a copy of the drawing state (that is the state that's
2282 // going to be overwritten by handleTransactionLocked()) outside of
2283 // mStateLock so that the side-effects of the State assignment
2284 // don't happen with mStateLock held (which can cause deadlocks).
2285 State drawingState(mDrawingState);
2286
Mathias Agopianca4d3602011-05-19 15:38:14 -07002287 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002288 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289
Mathias Agopianca4d3602011-05-19 15:38:14 -07002290 // Here we're guaranteed that some transaction flags are set
2291 // so we can call handleTransactionLocked() unconditionally.
2292 // We call getTransactionFlags(), which will also clear the flags,
2293 // with mStateLock held to guarantee that mCurrentState won't change
2294 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002295
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002296 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002297 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002298 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002299
Mathias Agopianca4d3602011-05-19 15:38:14 -07002300 mDebugInTransaction = 0;
2301 invalidateHwcGeometry();
2302 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002303}
2304
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2306 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002307 const std::optional<DisplayIdentificationInfo> info =
2308 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309
Dominik Laskowski075d3172018-05-24 15:50:06 -07002310 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002311 continue;
2312 }
2313
Dominik Laskowski55c85402020-01-21 16:25:47 -08002314 const DisplayId displayId = info->id;
2315 const auto it = mPhysicalDisplayTokens.find(displayId);
2316
Lloyd Piqueba04e622017-12-14 17:11:26 -08002317 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002318 if (it == mPhysicalDisplayTokens.end()) {
2319 ALOGV("Creating display %s", to_string(displayId).c_str());
2320
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002321 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002322 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002323 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002324
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002326 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002327 state.isSecure = true; // All physical displays are currently considered secure.
2328 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002329
2330 sp<IBinder> token = new BBinder();
2331 mCurrentState.displays.add(token, state);
2332 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2333
Dominik Laskowski075d3172018-05-24 15:50:06 -07002334 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002335 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002336 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002337 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002338
Dominik Laskowski55c85402020-01-21 16:25:47 -08002339 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 if (index >= 0) {
2341 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2342 mInterceptor->saveDisplayDeletion(state.sequenceId);
2343 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002344 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002345 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002346 }
2347
2348 processDisplayChangesLocked();
2349 }
2350
2351 mPendingHotplugEvents.clear();
2352}
2353
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002354void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002355 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2356 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002357}
2358
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002360 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002361 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002362 const sp<IGraphicBufferProducer>& producer) {
2363 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002364 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002365 creationArgs.isSecure = state.isSecure;
2366 creationArgs.displaySurface = dispSurface;
2367 creationArgs.hasWideColorGamut = false;
2368 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002369 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002370
Dominik Laskowski55c85402020-01-21 16:25:47 -08002371 if (const auto& physical = state.physical) {
2372 creationArgs.connectionType = physical->type;
2373 }
2374
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002375 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 creationArgs.isPrimary = isInternalDisplay;
2377
2378 if (useColorManagement && displayId) {
2379 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002381 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002382 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002384
Dominik Laskowski7e045462018-05-30 13:02:02 -07002385 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002386 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002387 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388 }
tangrobin6753a022018-08-10 10:58:54 +08002389 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 if (displayId) {
2392 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002393 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002395 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396
Lloyd Pique90c115d2018-09-18 21:39:42 -07002397 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002399 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401 // Make sure that composition can never be stalled by a virtual display
2402 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002403 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002404 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002405 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2406 }
2407
Dominik Laskowski718f9602019-11-09 20:01:35 -08002408 creationArgs.physicalOrientation =
2409 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002410
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002412 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413
Lloyd Pique90c115d2018-09-18 21:39:42 -07002414 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415
2416 if (maxFrameBufferAcquiredBuffers >= 3) {
2417 nativeWindowSurface->preallocateBuffers();
2418 }
2419
2420 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002421 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002422 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002423 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002424 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002426 display->getCompositionDisplay()->setColorProfile(
2427 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2428 RenderIntent::COLORIMETRIC,
2429 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 if (!state.isVirtual()) {
2431 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002432 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2433 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002434 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002436 display->setLayerStack(state.layerStack);
2437 display->setProjection(state.orientation, state.viewport, state.frame);
2438 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441}
2442
Lloyd Pique347200f2017-12-14 17:00:15 -08002443void SurfaceFlinger::processDisplayChangesLocked() {
2444 // here we take advantage of Vector's copy-on-write semantics to
2445 // improve performance by skipping the transaction entirely when
2446 // know that the lists are identical
2447 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2448 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2449 if (!curr.isIdenticalTo(draw)) {
2450 mVisibleRegionsDirty = true;
2451 const size_t cc = curr.size();
2452 size_t dc = draw.size();
2453
2454 // find the displays that were removed
2455 // (ie: in drawing state but not in current state)
2456 // also handle displays that changed
2457 // (ie: displays that are in both lists)
2458 for (size_t i = 0; i < dc;) {
2459 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2460 if (j < 0) {
2461 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002462 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002463 // Save display ID before disconnecting.
2464 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002465 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002466
2467 if (!display->isVirtual()) {
2468 LOG_ALWAYS_FATAL_IF(!displayId);
2469 dispatchDisplayHotplugEvent(displayId->value, false);
2470 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002471 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002472
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002473 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002474 } else {
2475 // this display is in both lists. see if something changed.
2476 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002477 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2479 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2480 if (state_binder != draw_binder) {
2481 // changing the surface is like destroying and
2482 // recreating the DisplayDevice, so we just remove it
2483 // from the drawing state, so that it get re-added
2484 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002486 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002488 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002489 mDrawingState.displays.removeItemsAt(i);
2490 dc--;
2491 // at this point we must loop to the next item
2492 continue;
2493 }
2494
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002497 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 }
2499 if ((state.orientation != draw[i].orientation) ||
2500 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002502 }
2503 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002505 if (display->isPrimary()) {
2506 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2507 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 }
2509 }
2510 }
2511 ++i;
2512 }
2513
2514 // find displays that were added
2515 // (ie: in current state but not in drawing state)
2516 for (size_t i = 0; i < cc; i++) {
2517 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2518 const DisplayDeviceState& state(curr[i]);
2519
Lloyd Pique542307f2018-10-19 13:24:08 -07002520 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 sp<IGraphicBufferProducer> producer;
2522 sp<IGraphicBufferProducer> bqProducer;
2523 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002524 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002527 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002528 // Virtual displays without a surface are dormant:
2529 // they have external state (layer stack, projection,
2530 // etc.) but no internal state (i.e. a DisplayDevice).
2531 if (state.surface != nullptr) {
2532 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002534 int width = 0;
2535 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2536 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2537 int height = 0;
2538 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2539 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2540 int intFormat = 0;
2541 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2542 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002543 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 displayId =
2546 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 }
2548
2549 // TODO: Plumb requested format back up to consumer
2550
2551 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 bqProducer, bqConsumer,
2554 state.displayName);
2555
2556 dispSurface = vds;
2557 producer = vds;
2558 }
2559 } else {
2560 ALOGE_IF(state.surface != nullptr,
2561 "adding a supported display, but rendering "
2562 "surface is provided (%p), ignoring it",
2563 state.surface.get());
2564
Dominik Laskowski55c85402020-01-21 16:25:47 -08002565 LOG_FATAL_IF(!state.physical);
2566 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002568 producer = bqProducer;
2569 }
2570
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002571 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002572 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002573 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002574 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002575 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002576 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002578 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002579 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002580
2581 const auto displayDevice = mDisplays[displayToken];
2582 if (displayDevice->isPrimary()) {
2583 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2584 displayDevice->getHeight());
2585 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002586 }
2587 }
2588 }
2589 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590
2591 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002592}
2593
Mathias Agopian87baae12012-07-31 12:38:26 -07002594void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002595{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002596 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2597
Dan Stoza7dde5992015-05-22 09:51:44 -07002598 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002599 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002600 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002601 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002602
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 /*
2604 * Traversal of the children
2605 * (perform the transaction for each of them if needed)
2606 */
2607
Marissa Wall06255332019-03-27 13:48:27 -07002608 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002609 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002611 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612
2613 const uint32_t flags = layer->doTransaction(0);
2614 if (flags & Layer::eVisibleRegion)
2615 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002616
2617 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002618 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002619 }
Robert Carr2047fae2016-11-28 14:09:09 -08002620 });
Marissa Wall06255332019-03-27 13:48:27 -07002621 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 }
2623
2624 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002625 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626 */
2627
Mathias Agopiane57f2922012-08-09 16:29:12 -07002628 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002629 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002630 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002631 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002633 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002634 // The transform hint might have changed for some layers
2635 // (either because a display has changed, or because a layer
2636 // as changed).
2637 //
2638 // Walk through all the layers in currentLayers,
2639 // and update their transform hint.
2640 //
2641 // If a layer is visible only on a single display, then that
2642 // display is used to calculate the hint, otherwise we use the
2643 // default display.
2644 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002645 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002646 // the hint is set before we acquire a buffer from the surface texture.
2647 //
2648 // NOTE: layer transactions have taken place already, so we use their
2649 // drawing state. However, SurfaceFlinger's own transaction has not
2650 // happened yet, so we must use the current state layer list
2651 // (soon to become the drawing state list).
2652 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002653 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002654 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002655 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002656 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002657 // NOTE: we rely on the fact that layers are sorted by
2658 // layerStack first (so we don't have to traverse the list
2659 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002660 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002661 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002662 currentlayerStack = layerStack;
2663 // figure out if this layerstack is mirrored
2664 // (more than one display) if so, pick the default display,
2665 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002666 hintDisplay = nullptr;
2667 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002668 if (display->getCompositionDisplay()
2669 ->belongsInOutput(layer->getLayerStack(),
2670 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002671 if (hintDisplay) {
2672 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002673 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002675 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002676 }
2677 }
2678 }
2679 }
Chet Haase91d25932013-04-11 15:24:55 -07002680
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002681 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002682 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2683 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002684
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002685 // could be null when this layer is using a layerStack
2686 // that is not visible on any display. Also can occur at
2687 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002688 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002689 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002690
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002692 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002693 if (hintDisplay) {
2694 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002695 }
Robert Carr2047fae2016-11-28 14:09:09 -08002696
2697 first = false;
2698 });
Mathias Agopian84300952012-11-21 16:02:13 -08002699 }
2700
2701
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 /*
2703 * Perform our own transaction if needed
2704 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002705
2706 if (mLayersAdded) {
2707 mLayersAdded = false;
2708 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002709 mVisibleRegionsDirty = true;
2710 }
2711
2712 // some layers might have been removed, so
2713 // we need to update the regions they're exposing.
2714 if (mLayersRemoved) {
2715 mLayersRemoved = false;
2716 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002717 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002719 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002721 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002722 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002723 }
Robert Carr2047fae2016-11-28 14:09:09 -08002724 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 }
2726
Vishnu Nairec0ab382019-02-13 15:32:56 -08002727 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002729}
2730
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002731void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002732 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002733 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002734 return;
2735 }
2736
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002737 if (mVisibleRegionsDirty || mInputInfoChanged) {
2738 mInputInfoChanged = false;
2739 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002740 } else if (mInputWindowCommands.syncInputWindows) {
2741 // If the caller requested to sync input windows, but there are no
2742 // changes to input windows, notify immediately.
2743 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002744 }
2745
Arthur Hung6cbb9752019-09-05 16:38:18 +08002746 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002747}
2748
2749void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002750 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002751
2752 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2753 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002754 // When calculating the screen bounds we ignore the transparent region since it may
2755 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002756 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002757 }
2758 });
chaviw291d88a2019-02-14 10:33:58 -08002759
2760 mInputFlinger->setInputWindows(inputHandles,
2761 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2762 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002763}
2764
Vishnu Nairec0ab382019-02-13 15:32:56 -08002765void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002766 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002767 mPendingInputWindowCommands.clear();
2768}
2769
Riley Andrews03414a12014-07-01 14:22:59 -07002770void SurfaceFlinger::updateCursorAsync()
2771{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002772 compositionengine::CompositionRefreshArgs refreshArgs;
2773 for (const auto& [_, display] : mDisplays) {
2774 if (display->getId()) {
2775 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002776 }
2777 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002778
2779 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002780}
2781
Ady Abraham2139f732019-11-13 18:56:40 -08002782void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002783 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2784 // If this is called from the main thread mStateLock must be locked before
2785 // Currently the only way to call this function from the main thread is from
2786 // Sheduler::chooseRefreshRateForContent
2787
2788 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002789 changeRefreshRateLocked(refreshRate, event);
2790}
2791
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002792void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2793 if (mScheduler) {
2794 // In practice it's not allowed to hotplug in/out the primary display once it's been
2795 // connected during startup, but some tests do it, so just warn and return.
2796 ALOGW("Can't re-init scheduler");
2797 return;
2798 }
2799
Ady Abraham2139f732019-11-13 18:56:40 -08002800 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002801 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002802 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002803 primaryDisplayId),
2804 currentConfig);
2805 mRefreshRateStats =
2806 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2807 currentConfig, HWC_POWER_MODE_OFF);
2808 mRefreshRateStats->setConfigMode(currentConfig);
2809
Ady Abraham9e16a482019-12-03 17:19:41 -08002810 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2811
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002812 // start the EventThread
2813 mScheduler =
2814 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002815 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002816 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002817 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002818 impl::EventThread::InterceptVSyncsCallback());
2819 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002820 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002821 [this](nsecs_t timestamp) {
2822 mInterceptor->saveVSyncEvent(timestamp);
2823 });
2824
2825 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2826 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002827 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002828
2829 mRegionSamplingThread =
2830 new RegionSamplingThread(*this, *mScheduler,
2831 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002832 // Dispatch a config change request for the primary display on scheduler
2833 // initialization, so that the EventThreads always contain a reference to a
2834 // prior configuration.
2835 //
2836 // This is a bit hacky, but this avoids a back-pointer into the main SF
2837 // classes from EventThread, and there should be no run-time binder cost
2838 // anyway since there are no connected apps at this point.
2839 const nsecs_t vsyncPeriod =
2840 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2841 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2842 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002843}
2844
Mathias Agopian4fec8732012-06-29 14:12:52 -07002845void SurfaceFlinger::commitTransaction()
2846{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002847 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002848
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002849 mTransactionPending = false;
2850 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002851 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852}
2853
Lloyd Pique58e24a32019-08-01 15:50:14 -07002854void SurfaceFlinger::commitTransactionLocked() {
2855 if (!mLayersPendingRemoval.isEmpty()) {
2856 // Notify removed layers now that they can't be drawn from
2857 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002858 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002859
2860 // Ensure any buffers set to display on any children are released.
2861 if (l->isRemovedFromCurrentState()) {
2862 l->latchAndReleaseBuffer();
2863 }
2864
2865 // If the layer has been removed and has no parent, then it will not be reachable
2866 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2867 // ensure we can copy its current to drawing state.
2868 if (!l->getParent()) {
2869 mOffscreenLayers.emplace(l.get());
2870 }
2871 }
2872 mLayersPendingRemoval.clear();
2873 }
2874
2875 // If this transaction is part of a window animation then the next frame
2876 // we composite should be considered an animation as well.
2877 mAnimCompositionPending = mAnimTransactionPending;
2878
2879 mDrawingState = mCurrentState;
2880 // clear the "changed" flags in current state
2881 mCurrentState.colorMatrixChanged = false;
2882
Edgar Arriaga844fa672020-01-16 14:21:42 -08002883 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002884 layer->commitChildList();
2885
2886 // If the layer can be reached when traversing mDrawingState, then the layer is no
2887 // longer offscreen. Remove the layer from the offscreenLayer set.
2888 if (mOffscreenLayers.count(layer)) {
2889 mOffscreenLayers.erase(layer);
2890 }
2891 });
2892
2893 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002894 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002895}
2896
Nataniel Borges2b796da2019-02-15 13:32:18 -08002897void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2898 if (mTracingEnabledChanged) {
2899 mTracingEnabled = mTracing.isEnabled();
2900 mTracingEnabledChanged = false;
2901 }
2902
2903 // Synchronize with Tracing thread
2904 std::unique_lock<std::mutex> lock;
2905 if (mTracingEnabled) {
2906 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2907 }
2908
2909 lockedOperation();
2910
2911 // Synchronize with Tracing thread
2912 if (mTracingEnabled) {
2913 lock.unlock();
2914 }
2915}
2916
chaviw74d90ad2019-04-26 14:45:26 -07002917void SurfaceFlinger::commitOffscreenLayers() {
2918 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002919 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002920 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2921 if (!trFlags) return;
2922
2923 layer->doTransaction(0);
2924 layer->commitChildList();
2925 });
2926 }
2927}
2928
Chia-I Wuab0c3192017-08-01 11:29:00 -07002929void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002930 for (const auto& [token, displayDevice] : mDisplays) {
2931 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002932 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002933 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002934 }
2935 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002936}
2937
Dan Stoza6b9454d2014-11-07 16:00:59 -08002938bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939{
Ady Abraham09bd3922019-04-08 10:44:56 -07002940 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002941 ALOGV("handlePageFlip");
2942
Brian Andersond6927fb2016-07-23 23:37:30 -07002943 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002944
Mathias Agopian4fec8732012-06-29 14:12:52 -07002945 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002946 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002947 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002948
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002949 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2950
Eric Penner51c59cd2014-07-28 19:51:58 -07002951 // Store the set of layers that need updates. This set must not change as
2952 // buffers are being latched, as this could result in a deadlock.
2953 // Example: Two producers share the same command stream and:
2954 // 1.) Layer 0 is latched
2955 // 2.) Layer 0 gets a new frame
2956 // 2.) Layer 1 gets a new frame
2957 // 3.) Layer 1 is latched.
2958 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2959 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002960 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002961 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002962 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002963 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002964 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002965 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002966 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002967 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002968 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002969 } else {
2970 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002971 }
Robert Carr2047fae2016-11-28 14:09:09 -08002972 });
2973
chaviw49a108c2019-08-12 11:23:06 -07002974 // The client can continue submitting buffers for offscreen layers, but they will not
2975 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2976 // layers to ensure dequeueBuffer doesn't block indefinitely.
2977 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002978 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002979 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2980 }
2981
Lloyd Piquef2c79392018-12-20 16:23:33 -08002982 if (!mLayersWithQueuedFrames.empty()) {
2983 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2984 // writes to Layer current state. See also b/119481871
2985 Mutex::Autolock lock(mStateLock);
2986
2987 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002988 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002989 mLayersPendingRefresh.push_back(layer);
2990 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002991 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002992 if (layer->isBufferLatched()) {
2993 newDataLatched = true;
2994 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002995 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002997
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002998 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002999
3000 // If we will need to wake up at some time in the future to deal with a
3001 // queued frame that shouldn't be displayed during this vsync period, wake
3002 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003003 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003004 signalLayerUpdate();
3005 }
3006
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003007 // enter boot animation on first buffer latch
3008 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3009 ALOGI("Enter boot animation");
3010 mBootStage = BootStage::BOOTANIMATION;
3011 }
3012
Edgar Arriaga844fa672020-01-16 14:21:42 -08003013 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003014
Dan Stoza6b9454d2014-11-07 16:00:59 -08003015 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003016 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017}
3018
Mathias Agopianad456f92011-01-13 17:53:01 -08003019void SurfaceFlinger::invalidateHwcGeometry()
3020{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003022}
3023
Robert Carrc0df3122019-04-11 13:18:21 -07003024status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3025 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3026 const sp<IBinder>& parentHandle,
3027 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003028 // add this layer to the current state list
3029 {
3030 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003031 sp<Layer> parent;
3032 if (parentHandle != nullptr) {
3033 parent = fromHandle(parentHandle);
3034 if (parent == nullptr) {
3035 return NAME_NOT_FOUND;
3036 }
3037 } else {
3038 parent = parentLayer;
3039 }
3040
Robert Carr1f0a16a2016-10-24 16:27:39 -07003041 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003042 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003043 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003044 return NO_MEMORY;
3045 }
Robert Carrc0df3122019-04-11 13:18:21 -07003046
3047 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3048
Robert Carrb89ea9d2018-12-10 13:01:14 -08003049 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003050 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003051 } else if (parent == nullptr) {
3052 lbc->onRemovedFromCurrentState();
3053 } else if (parent->isRemovedFromCurrentState()) {
3054 parent->addChild(lbc);
3055 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003056 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057 parent->addChild(lbc);
3058 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003059
Yiwei Zhang243b3782018-05-15 17:40:04 -07003060 if (gbc != nullptr) {
3061 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3062 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3063 mMaxGraphicBufferProducerListSize,
3064 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3065 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003066 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003067 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003068 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003069 }
3070
Mathias Agopian96f08192010-06-02 23:28:45 -07003071 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003072 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003073
Dan Stoza7d89d062015-04-30 13:29:25 -07003074 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003075}
3076
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003077uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003078 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003079}
3080
Mathias Agopian3f844832013-08-07 21:24:32 -07003081uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003082 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083}
3084
Mathias Agopian3f844832013-08-07 21:24:32 -07003085uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003086 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003087}
3088
3089uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003090 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003091 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003092 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003094 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095 }
3096 return old;
3097}
3098
Marissa Wall713b63f2018-10-17 15:42:43 -07003099bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003100 // to prevent onHandleDestroyed from being called while the lock is held,
3101 // we must keep a copy of the transactions (specifically the composer
3102 // states) around outside the scope of the lock
3103 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003104 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003105 {
3106 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003107
Valerie Haufce31b82019-04-30 16:41:14 -07003108 auto it = mTransactionQueues.begin();
3109 while (it != mTransactionQueues.end()) {
3110 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003111
Valerie Haufce31b82019-04-30 16:41:14 -07003112 while (!transactionQueue.empty()) {
3113 const auto& transaction = transactionQueue.front();
3114 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003115 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003116 transaction.states)) {
3117 setTransactionFlags(eTransactionFlushNeeded);
3118 break;
3119 }
3120 transactions.push_back(transaction);
3121 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3122 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003123 transaction.buffer, transaction.postTime,
3124 transaction.privileged, transaction.hasListenerCallbacks,
3125 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003126 transactionQueue.pop();
3127 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003128 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003129
Valerie Haufce31b82019-04-30 16:41:14 -07003130 if (transactionQueue.empty()) {
3131 it = mTransactionQueues.erase(it);
3132 mTransactionCV.broadcast();
3133 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003134 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003135 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003136 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003137 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003138 return flushedATransaction;
3139}
3140
3141bool SurfaceFlinger::transactionFlushNeeded() {
3142 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003143}
3144
chaviwca27f252018-02-06 16:46:39 -08003145
Marissa Wall17b4e452018-12-26 16:32:34 -08003146bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003147 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003148 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003149 if (!useCachedExpectedPresentTime)
3150 populateExpectedPresentTime();
3151
3152 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003153 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3154 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3155 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3156 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3157 return false;
3158 }
3159
Marissa Wall713b63f2018-10-17 15:42:43 -07003160 for (const ComposerState& state : states) {
3161 const layer_state_t& s = state.state;
3162 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3163 continue;
3164 }
3165 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003166 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003167 }
3168 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003169 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003170}
3171
Valerie Hau9dab9732019-08-20 09:29:25 -07003172void SurfaceFlinger::setTransactionState(
3173 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3174 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3175 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3176 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003177 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003178
Valerie Haubc6ddb12019-03-08 11:10:15 -08003179 const int64_t postTime = systemTime();
3180
Robert Carr14167e02019-02-13 13:50:55 -08003181 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3182
Mathias Agopian698c0872011-06-28 19:09:31 -07003183 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003184
Marissa Wall713b63f2018-10-17 15:42:43 -07003185 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003186 auto itr = mTransactionQueues.find(applyToken);
3187 // if this is an animation frame, wait until prior animation frame has
3188 // been applied by SF
3189 if (flags & eAnimation) {
3190 while (itr != mTransactionQueues.end()) {
3191 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3192 if (CC_UNLIKELY(err != NO_ERROR)) {
3193 ALOGW_IF(err == TIMED_OUT,
3194 "setTransactionState timed out "
3195 "waiting for animation frame to apply");
3196 break;
3197 }
3198 itr = mTransactionQueues.find(applyToken);
3199 }
3200 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003201
3202 // Expected present time is computed and cached on invalidate, so it may be stale.
3203 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3204 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003205 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003206 uncacheBuffer, postTime, privileged,
3207 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003208 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003209 return;
3210 }
3211
Valerie Haubc6ddb12019-03-08 11:10:15 -08003212 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003213 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3214 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003215}
3216
Valerie Hau9dab9732019-08-20 09:29:25 -07003217void SurfaceFlinger::applyTransactionState(
3218 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3219 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3220 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3221 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3222 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003223 uint32_t transactionFlags = 0;
3224
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003225 if (flags & eAnimation) {
3226 // For window updates that are part of an animation we must wait for
3227 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003228 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003229 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003230 if (CC_UNLIKELY(err != NO_ERROR)) {
3231 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003232 // caller after a few seconds.
3233 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3234 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003235 mAnimTransactionPending = false;
3236 break;
3237 }
3238 }
3239 }
3240
chaviwca27f252018-02-06 16:46:39 -08003241 for (const DisplayState& display : displays) {
3242 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003243 }
3244
Valerie Hau9dab9732019-08-20 09:29:25 -07003245 // start and end registration for listeners w/ no surface so they can get their callback. Note
3246 // that listeners with SurfaceControls will start registration during setClientStateLocked
3247 // below.
3248 for (const auto& listener : listenerCallbacks) {
3249 mTransactionCompletedThread.startRegistration(listener);
3250 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003251 }
3252
Valerie Hau9dab9732019-08-20 09:29:25 -07003253 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003254 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003255 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003256 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3257 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003258 }
3259
Valerie Hau9dab9732019-08-20 09:29:25 -07003260 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003261 mTransactionCompletedThread.endRegistration(listenerCallback);
3262 }
3263
Marissa Walle2ffb422018-10-12 11:33:52 -07003264 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003265 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003266 mTransactionCompletedThread.sendCallbacks();
3267 }
3268 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003269
chaviw273171b2018-12-26 11:46:30 -08003270 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3271
Marissa Wall947d34e2019-03-29 14:03:53 -07003272 if (uncacheBuffer.isValid()) {
3273 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003274 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003275 }
3276
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003277 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3278 // anyway. This can be used as a flush mechanism for previous async transactions.
3279 // Empty animation transaction can be used to simulate back-pressure, so also force a
3280 // transaction for empty animation transactions.
3281 if (transactionFlags == 0 &&
3282 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003283 transactionFlags = eTransactionNeeded;
3284 }
3285
Marissa Wall06255332019-03-27 13:48:27 -07003286 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3287 // so we don't have to wake up again next frame to preform an uneeded traversal.
3288 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3289 transactionFlags = transactionFlags & (~eTraversalNeeded);
3290 mTraversalNeededMainThread = true;
3291 }
3292
Mathias Agopian386aa982011-11-07 21:58:03 -08003293 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003294 if (mInterceptor->isEnabled()) {
3295 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003296 }
Irvel468051e2016-06-13 16:44:44 -07003297
Mathias Agopian386aa982011-11-07 21:58:03 -08003298 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003299 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3300 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003301 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003302
3303 // if this is a synchronous transaction, wait for it to take effect
3304 // before returning.
3305 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003306 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003307 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003308 if (flags & eAnimation) {
3309 mAnimTransactionPending = true;
3310 }
chaviw4fe36852019-04-15 16:25:49 -07003311 if (mPendingInputWindowCommands.syncInputWindows) {
3312 mPendingSyncInputWindows = true;
3313 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003314
3315 // applyTransactionState can be called by either the main SF thread or by
3316 // another process through setTransactionState. While a given process may wish
3317 // to wait on synchronous transactions, the main SF thread should never
3318 // be blocked. Therefore, we only wait if isMainThread is false.
3319 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003320 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3321 if (CC_UNLIKELY(err != NO_ERROR)) {
3322 // just in case something goes wrong in SF, return to the
3323 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003324 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3325 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003326 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 break;
3328 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003329 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003330 }
3331}
3332
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003333uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3334 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3335 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003336
Mathias Agopiane57f2922012-08-09 16:29:12 -07003337 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003338 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3339
3340 const uint32_t what = s.what;
3341 if (what & DisplayState::eSurfaceChanged) {
3342 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3343 state.surface = s.surface;
3344 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003345 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003346 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003347 if (what & DisplayState::eLayerStackChanged) {
3348 if (state.layerStack != s.layerStack) {
3349 state.layerStack = s.layerStack;
3350 flags |= eDisplayTransactionNeeded;
3351 }
3352 }
3353 if (what & DisplayState::eDisplayProjectionChanged) {
3354 if (state.orientation != s.orientation) {
3355 state.orientation = s.orientation;
3356 flags |= eDisplayTransactionNeeded;
3357 }
3358 if (state.frame != s.frame) {
3359 state.frame = s.frame;
3360 flags |= eDisplayTransactionNeeded;
3361 }
3362 if (state.viewport != s.viewport) {
3363 state.viewport = s.viewport;
3364 flags |= eDisplayTransactionNeeded;
3365 }
3366 }
3367 if (what & DisplayState::eDisplaySizeChanged) {
3368 if (state.width != s.width) {
3369 state.width = s.width;
3370 flags |= eDisplayTransactionNeeded;
3371 }
3372 if (state.height != s.height) {
3373 state.height = s.height;
3374 flags |= eDisplayTransactionNeeded;
3375 }
3376 }
3377
Mathias Agopiane57f2922012-08-09 16:29:12 -07003378 return flags;
3379}
3380
Robert Carr14167e02019-02-13 13:50:55 -08003381bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003382 IPCThreadState* ipc = IPCThreadState::self();
3383 const int pid = ipc->getCallingPid();
3384 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003385 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003386 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003387 return false;
3388 }
3389 return true;
3390}
3391
Marissa Wall3dad52d2019-03-22 14:03:19 -07003392uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003393 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3394 bool privileged,
3395 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003396 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003397
Valerie Hau9dab9732019-08-20 09:29:25 -07003398 for (auto& listener : s.listeners) {
3399 // note that startRegistration will not re-register if the listener has
3400 // already be registered for a prior surface control
3401 mTransactionCompletedThread.startRegistration(listener);
3402 listenerCallbacks.insert(listener);
3403 }
3404
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003405 sp<Layer> layer = nullptr;
3406 if (s.surface) {
3407 layer = fromHandle(s.surface);
3408 } else {
3409 // The client may provide us a null handle. Treat it as if the layer was removed.
3410 ALOGW("Attempt to set client state with a null layer handle");
3411 }
chaviw8b3871a2017-11-01 17:41:01 -07003412 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003413 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003414 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003415 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 return 0;
3418 }
3419
chaviw8b3871a2017-11-01 17:41:01 -07003420 uint32_t flags = 0;
3421
Garfield Tan8a3083e2018-12-03 13:21:07 -08003422 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003423
3424 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3425 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003426 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003427 layer->pushPendingState();
3428 }
3429
Valerie Hau871d6352020-01-29 08:44:02 -08003430 // Only set by BLAST adapter layers
3431 if (what & layer_state_t::eProducerDisconnect) {
3432 layer->onDisconnect();
3433 }
3434
chaviw8b3871a2017-11-01 17:41:01 -07003435 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003436 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003437 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003438 }
chaviw8b3871a2017-11-01 17:41:01 -07003439 }
3440 if (what & layer_state_t::eLayerChanged) {
3441 // NOTE: index needs to be calculated before we update the state
3442 const auto& p = layer->getParent();
3443 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003444 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003445 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003446 mCurrentState.layersSortedByZ.removeAt(idx);
3447 mCurrentState.layersSortedByZ.add(layer);
3448 // we need traversal (state changed)
3449 // AND transaction (list changed)
3450 flags |= eTransactionNeeded|eTraversalNeeded;
3451 }
chaviw8b3871a2017-11-01 17:41:01 -07003452 } else {
3453 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003454 flags |= eTransactionNeeded|eTraversalNeeded;
3455 }
3456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 }
3458 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003459 // NOTE: index needs to be calculated before we update the state
3460 const auto& p = layer->getParent();
3461 if (p == nullptr) {
3462 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3463 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3464 mCurrentState.layersSortedByZ.removeAt(idx);
3465 mCurrentState.layersSortedByZ.add(layer);
3466 // we need traversal (state changed)
3467 // AND transaction (list changed)
3468 flags |= eTransactionNeeded|eTraversalNeeded;
3469 }
3470 } else {
3471 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3472 flags |= eTransactionNeeded|eTraversalNeeded;
3473 }
chaviw8b3871a2017-11-01 17:41:01 -07003474 }
3475 }
3476 if (what & layer_state_t::eSizeChanged) {
3477 if (layer->setSize(s.w, s.h)) {
3478 flags |= eTraversalNeeded;
3479 }
3480 }
3481 if (what & layer_state_t::eAlphaChanged) {
3482 if (layer->setAlpha(s.alpha))
3483 flags |= eTraversalNeeded;
3484 }
3485 if (what & layer_state_t::eColorChanged) {
3486 if (layer->setColor(s.color))
3487 flags |= eTraversalNeeded;
3488 }
Peiyong Lind3788632018-09-18 16:01:31 -07003489 if (what & layer_state_t::eColorTransformChanged) {
3490 if (layer->setColorTransform(s.colorTransform)) {
3491 flags |= eTraversalNeeded;
3492 }
3493 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003494 if (what & layer_state_t::eBackgroundColorChanged) {
3495 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3496 flags |= eTraversalNeeded;
3497 }
3498 }
chaviw8b3871a2017-11-01 17:41:01 -07003499 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003500 // TODO: b/109894387
3501 //
3502 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3503 // rotation. To see the problem observe that if we have a square parent, and a child
3504 // of the same size, then we rotate the child 45 degrees around it's center, the child
3505 // must now be cropped to a non rectangular 8 sided region.
3506 //
3507 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3508 // private API, and the WindowManager only uses rotation in one case, which is on a top
3509 // level layer in which cropping is not an issue.
3510 //
3511 // However given that abuse of rotation matrices could lead to surfaces extending outside
3512 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3513 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3514 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003515 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003516 flags |= eTraversalNeeded;
3517 }
3518 if (what & layer_state_t::eTransparentRegionChanged) {
3519 if (layer->setTransparentRegionHint(s.transparentRegion))
3520 flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eFlagsChanged) {
3523 if (layer->setFlags(s.flags, s.mask))
3524 flags |= eTraversalNeeded;
3525 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003526 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003527 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003528 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003529 if (what & layer_state_t::eCornerRadiusChanged) {
3530 if (layer->setCornerRadius(s.cornerRadius))
3531 flags |= eTraversalNeeded;
3532 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003533 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3534 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3535 }
chaviw8b3871a2017-11-01 17:41:01 -07003536 if (what & layer_state_t::eLayerStackChanged) {
3537 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3538 // We only allow setting layer stacks for top level layers,
3539 // everything else inherits layer stack from its parent.
3540 if (layer->hasParent()) {
3541 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003542 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003543 } else if (idx < 0) {
3544 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003545 "that also does not appear in the top level layer list. Something"
3546 " has gone wrong.",
3547 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003548 } else if (layer->setLayerStack(s.layerStack)) {
3549 mCurrentState.layersSortedByZ.removeAt(idx);
3550 mCurrentState.layersSortedByZ.add(layer);
3551 // we need traversal (state changed)
3552 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003553 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003554 }
3555 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003556 if (what & layer_state_t::eDeferTransaction_legacy) {
3557 if (s.barrierHandle_legacy != nullptr) {
3558 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3559 } else if (s.barrierGbp_legacy != nullptr) {
3560 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003561 if (authenticateSurfaceTextureLocked(gbp)) {
3562 const auto& otherLayer =
3563 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003564 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003565 } else {
3566 ALOGE("Attempt to defer transaction to to an"
3567 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003568 }
3569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 // We don't trigger a traversal here because if no other state is
3571 // changed, we don't want this to cause any more work
3572 }
chaviw8b3871a2017-11-01 17:41:01 -07003573 if (what & layer_state_t::eReparentChildren) {
3574 if (layer->reparentChildren(s.reparentHandle)) {
3575 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003576 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 if (what & layer_state_t::eDetachChildren) {
3579 layer->detachChildren();
3580 }
3581 if (what & layer_state_t::eOverrideScalingModeChanged) {
3582 layer->setOverrideScalingMode(s.overrideScalingMode);
3583 // We don't trigger a traversal here because if no other state is
3584 // changed, we don't want this to cause any more work
3585 }
Marissa Wall61c58622018-07-18 10:12:20 -07003586 if (what & layer_state_t::eTransformChanged) {
3587 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3590 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3591 flags |= eTraversalNeeded;
3592 }
3593 if (what & layer_state_t::eCropChanged) {
3594 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3595 }
Marissa Wall861616d2018-10-22 12:52:23 -07003596 if (what & layer_state_t::eFrameChanged) {
3597 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3598 }
Marissa Wall61c58622018-07-18 10:12:20 -07003599 if (what & layer_state_t::eAcquireFenceChanged) {
3600 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3601 }
3602 if (what & layer_state_t::eDataspaceChanged) {
3603 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3604 }
3605 if (what & layer_state_t::eHdrMetadataChanged) {
3606 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3607 }
3608 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3609 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3610 }
3611 if (what & layer_state_t::eApiChanged) {
3612 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3613 }
3614 if (what & layer_state_t::eSidebandStreamChanged) {
3615 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3616 }
Robert Carr720e5062018-07-30 17:45:14 -07003617 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003618 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003619 layer->setInputInfo(s.inputInfo);
3620 flags |= eTraversalNeeded;
3621 } else {
3622 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3623 }
Robert Carr720e5062018-07-30 17:45:14 -07003624 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003625 if (what & layer_state_t::eMetadataChanged) {
3626 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3627 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003628 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3629 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3630 flags |= eTraversalNeeded;
3631 }
3632 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003633 if (what & layer_state_t::eShadowRadiusChanged) {
3634 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3635 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003636 if (what & layer_state_t::eFrameRateSelectionPriority) {
3637 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3638 flags |= eTraversalNeeded;
3639 }
3640 }
Steven Thomas3172e202020-01-06 19:25:30 -08003641 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003642 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3643 "SurfaceFlinger::setClientStateLocked") &&
3644 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3645 Layer::FrameRate::convertCompatibility(
3646 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003647 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003648 }
Steven Thomas3172e202020-01-06 19:25:30 -08003649 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003650 // This has to happen after we reparent children because when we reparent to null we remove
3651 // child layers from current state and remove its relative z. If the children are reparented in
3652 // the same transaction, then we have to make sure we reparent the children first so we do not
3653 // lose its relative z order.
3654 if (what & layer_state_t::eReparent) {
3655 bool hadParent = layer->hasParent();
3656 if (layer->reparent(s.parentHandleForChild)) {
3657 if (!hadParent) {
3658 mCurrentState.layersSortedByZ.remove(layer);
3659 }
3660 flags |= eTransactionNeeded | eTraversalNeeded;
3661 }
3662 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003663 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003664 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3665 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003666 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3667 }
3668 }
Marissa Wall78b72202019-03-15 14:58:34 -07003669 bool bufferChanged = what & layer_state_t::eBufferChanged;
3670 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3671 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003672 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003673 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003674 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3675 if (success) {
3676 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3677 success = ClientCache::getInstance()
3678 .registerErasedRecipient(s.cachedBuffer,
3679 wp<ClientCache::ErasedRecipient>(this));
3680 if (!success) {
3681 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3682 }
3683 }
Marissa Wall78b72202019-03-15 14:58:34 -07003684 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003685 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003686 } else if (bufferChanged) {
3687 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003688 }
Marissa Wall78b72202019-03-15 14:58:34 -07003689 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003690 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3691 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003692 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003693 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003694 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003695 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3696 // Do not put anything that updates layer state or modifies flags after
3697 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003698 return flags;
3699}
3700
chaviw273171b2018-12-26 11:46:30 -08003701uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3702 uint32_t flags = 0;
3703 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3704 flags |= eTraversalNeeded;
3705 }
3706
chaviwa911b102019-02-14 10:18:33 -08003707 if (inputWindowCommands.syncInputWindows) {
3708 flags |= eTraversalNeeded;
3709 }
3710
Vishnu Nairec0ab382019-02-13 15:32:56 -08003711 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003712 return flags;
3713}
3714
chaviwfe94a222019-08-21 13:52:59 -07003715status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3716 sp<IBinder>* outHandle) {
3717 if (!mirrorFromHandle) {
3718 return NAME_NOT_FOUND;
3719 }
3720
3721 sp<Layer> mirrorLayer;
3722 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003723 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003724
3725 {
3726 Mutex::Autolock _l(mStateLock);
3727 mirrorFrom = fromHandle(mirrorFromHandle);
3728 if (!mirrorFrom) {
3729 return NAME_NOT_FOUND;
3730 }
3731
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003732 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3733 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003734 if (result != NO_ERROR) {
3735 return result;
3736 }
3737
3738 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3739 }
3740
3741 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3742}
3743
Marissa Wall2d814fb2019-04-09 18:52:57 +00003744status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3745 uint32_t h, PixelFormat format, uint32_t flags,
3746 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003747 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003748 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3749 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003750 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003751 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003752 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003753 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003754 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003755
Robert Carrc0df3122019-04-11 13:18:21 -07003756 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3757 "Expected only one of parentLayer or parentHandle to be non-null. "
3758 "Programmer error?");
3759
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003760 status_t result = NO_ERROR;
3761
3762 sp<Layer> layer;
3763
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003764 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003765
Evan Roskya1f1e152019-01-24 16:17:46 -08003766 bool primaryDisplayOnly = false;
3767
3768 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3769 // TODO b/64227542
3770 if (metadata.has(METADATA_WINDOW_TYPE)) {
3771 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3772 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003773 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003774 primaryDisplayOnly = true;
3775 }
3776 }
3777
Mathias Agopian3165cc22012-08-08 19:42:09 -07003778 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003779 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003780 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3781 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003782
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003784 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003785 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003786 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003787 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003788 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003789 // check if buffer size is set for color layer.
3790 if (w > 0 || h > 0) {
3791 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3792 int(w), int(h));
3793 return BAD_VALUE;
3794 }
3795
Vishnu Nairfa247b12020-02-11 08:58:26 -08003796 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3797 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003798 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003799 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003800 // check if buffer size is set for container layer.
3801 if (w > 0 || h > 0) {
3802 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3803 int(w), int(h));
3804 return BAD_VALUE;
3805 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003806 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3807 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003808 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003809 default:
3810 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 break;
3812 }
3813
Dan Stoza7d89d062015-04-30 13:29:25 -07003814 if (result != NO_ERROR) {
3815 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003816 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003817
Evan Roskya1f1e152019-01-24 16:17:46 -08003818 if (primaryDisplayOnly) {
3819 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003820 }
3821
Robert Carrb89ea9d2018-12-10 13:01:14 -08003822 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003823 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3824 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003825 if (result != NO_ERROR) {
3826 return result;
3827 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003828 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003829
3830 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003831 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832}
3833
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003834std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3835 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003836
3837 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003838 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003839
Dan Stoza436ccf32018-06-21 12:10:12 -07003840 // Grab the state lock since we're accessing mCurrentState
3841 Mutex::Autolock lock(mStateLock);
3842
Cody Northropbc755282017-03-31 12:00:08 -06003843 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003844 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003845 while (matchFound) {
3846 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003847 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003848 if (layer->getName() == uniqueName) {
3849 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003850 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003851 }
3852 });
3853 }
3854
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003855 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003856 return uniqueName;
3857}
3858
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003859status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003860 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003861 LayerMetadata metadata, PixelFormat& format,
3862 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003863 sp<IGraphicBufferProducer>* gbp,
3864 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003866 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 case PIXEL_FORMAT_TRANSPARENT:
3868 case PIXEL_FORMAT_TRANSLUCENT:
3869 format = PIXEL_FORMAT_RGBA_8888;
3870 break;
3871 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003872 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873 break;
3874 }
3875
chaviwb4c6e582019-08-16 14:35:07 -07003876 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003877 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003878 args.textureName = getNewTexture();
3879 {
3880 // Grab the SF state lock during this since it's the only safe way to access
3881 // RenderEngine when creating a BufferLayerConsumer
3882 // TODO: Check if this lock is still needed here
3883 Mutex::Autolock lock(mStateLock);
3884 layer = getFactory().createBufferQueueLayer(args);
3885 }
3886
Marissa Wallfd668622018-05-10 10:21:13 -07003887 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003888 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003889 *handle = layer->getHandle();
3890 *gbp = layer->getProducer();
3891 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003893
Marissa Wallfd668622018-05-10 10:21:13 -07003894 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896}
3897
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003898status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003899 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003900 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003901 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003902 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003903 args.displayDevice = getDefaultDisplayDevice();
3904 args.textureName = getNewTexture();
3905 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003906 if (outTransformHint) {
3907 *outTransformHint = layer->getTransformHint();
3908 }
Marissa Wall61c58622018-07-18 10:12:20 -07003909 *handle = layer->getHandle();
3910 *outLayer = layer;
3911
3912 return NO_ERROR;
3913}
3914
Vishnu Nairfa247b12020-02-11 08:58:26 -08003915status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3916 uint32_t h, uint32_t flags, LayerMetadata metadata,
3917 sp<IBinder>* handle, sp<Layer>* outLayer) {
3918 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003919 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003920 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003921 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003922}
3923
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003924status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003925 uint32_t w, uint32_t h, uint32_t flags,
3926 LayerMetadata metadata, sp<IBinder>* handle,
3927 sp<Layer>* outLayer) {
3928 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003929 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003930 *handle = (*outLayer)->getHandle();
3931 return NO_ERROR;
3932}
3933
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003934void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003935 mLayersPendingRemoval.add(layer);
3936 mLayersRemoved = true;
3937 setTransactionFlags(eTransactionNeeded);
3938}
3939
Robert Carr695d5282018-12-18 15:27:58 -08003940void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003941{
Robert Carr2e102c92018-10-23 12:11:15 -07003942 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003943 // If a layer has a parent, we allow it to out-live it's handle
3944 // with the idea that the parent holds a reference and will eventually
3945 // be cleaned up. However no one cleans up the top-level so we do so
3946 // here.
3947 if (layer->getParent() == nullptr) {
3948 mCurrentState.layersSortedByZ.remove(layer);
3949 }
3950 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003951
3952 auto it = mLayersByLocalBinderToken.begin();
3953 while (it != mLayersByLocalBinderToken.end()) {
3954 if (it->second == layer) {
3955 it = mLayersByLocalBinderToken.erase(it);
3956 } else {
3957 it++;
3958 }
3959 }
3960
Robert Carr695d5282018-12-18 15:27:58 -08003961 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003962}
3963
Mathias Agopianb60314a2012-04-10 22:09:54 -07003964// ---------------------------------------------------------------------------
3965
Andy McFadden13a082e2012-08-24 10:16:42 -07003966void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003967 const auto display = getDefaultDisplayDeviceLocked();
3968 if (!display) return;
3969
3970 const sp<IBinder> token = display->getDisplayToken().promote();
3971 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003972
Jesse Hall01e29052013-02-19 16:13:35 -08003973 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003974 Vector<ComposerState> state;
3975 Vector<DisplayState> displays;
3976 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003977 d.what = DisplayState::eDisplayProjectionChanged |
3978 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003979 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003980 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003981 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003982 d.frame.makeInvalid();
3983 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003984 d.width = 0;
3985 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003986 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003987 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3988 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003989
Dominik Laskowskie9774092018-12-11 10:04:24 -08003990 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003991
Dominik Laskowski83b88212018-12-11 13:34:06 -08003992 const nsecs_t vsyncPeriod = getVsyncPeriod();
3993 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003994
Brian Andersond0010582017-03-07 13:20:31 -08003995 // Use phase of 0 since phase is not known.
3996 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003997 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003998 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003999}
4000
4001void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004002 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004003 postMessageAsync(
4004 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004005}
4006
Ady Abraham27c70212019-06-11 10:52:26 -07004007void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4008 if (mHWCVsyncState != enabled) {
4009 getHwComposer().setVsyncEnabled(displayId, enabled);
4010 mHWCVsyncState = enabled;
4011 }
4012}
4013
Dominik Laskowskie9774092018-12-11 10:04:24 -08004014void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004015 if (display->isVirtual()) {
4016 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004017 return;
4018 }
4019
Dominik Laskowski075d3172018-05-24 15:50:06 -07004020 const auto displayId = display->getId();
4021 LOG_ALWAYS_FATAL_IF(!displayId);
4022
Dominik Laskowski34157762018-10-31 13:07:19 -07004023 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004024
4025 int currentMode = display->getPowerMode();
4026 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004027 return;
4028 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004030 display->setPowerMode(mode);
4031
Lloyd Pique4dccc412018-01-22 17:21:36 -08004032 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004033 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004034 }
4035
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004036 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004037 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004038 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004039 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004040 mScheduler->onScreenAcquired(mAppConnectionHandle);
4041 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004042 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004043
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004044 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004045 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004046 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004047
4048 struct sched_param param = {0};
4049 param.sched_priority = 1;
4050 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4051 ALOGW("Couldn't set SCHED_FIFO on display on");
4052 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004053 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004054 // Turn off the display
4055 struct sched_param param = {0};
4056 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4057 ALOGW("Couldn't set SCHED_OTHER on display off");
4058 }
4059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004060 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004061 mScheduler->disableHardwareVsync(true);
4062 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004063 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004064
Ady Abraham27c70212019-06-11 10:52:26 -07004065 // Make sure HWVsync is disabled before turning off the display
4066 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4067
Dominik Laskowski075d3172018-05-24 15:50:06 -07004068 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004069 mVisibleRegionsDirty = true;
4070 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004071 } else if (mode == HWC_POWER_MODE_DOZE ||
4072 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004073 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004074 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004075 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004076 mScheduler->onScreenAcquired(mAppConnectionHandle);
4077 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004078 }
4079 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4080 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004081 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004082 mScheduler->disableHardwareVsync(true);
4083 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004084 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004085 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004086 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004087 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004088 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004089 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004090
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004091 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004092 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004093 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004094 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004095 }
4096
Dominik Laskowski34157762018-10-31 13:07:19 -07004097 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004098}
4099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004100void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004101 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102 const auto display = getDisplayDevice(displayToken);
4103 if (!display) {
4104 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4105 displayToken.get());
4106 } else if (display->isVirtual()) {
4107 ALOGW("Attempt to set power mode %d for virtual display", mode);
4108 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004109 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004110 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004111 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004112}
4113
4114// ---------------------------------------------------------------------------
4115
Dominik Laskowskic2867142019-01-21 11:33:38 -08004116status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4117 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004118 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004119
Mathias Agopianbd115332013-04-18 16:41:04 -07004120 IPCThreadState* ipc = IPCThreadState::self();
4121 const int pid = ipc->getCallingPid();
4122 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004123
Mathias Agopianbd115332013-04-18 16:41:04 -07004124 if ((uid != AID_SHELL) &&
4125 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004126 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4127 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004129 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004130 // (this would indicate SF is stuck, but we want to be able to
4131 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004132 status_t err = mStateLock.timedLock(s2ns(1));
4133 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004134 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004135 StringAppendF(&result,
4136 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4137 "(no locks held)\n",
4138 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004139 }
4140
Dominik Laskowskic2867142019-01-21 11:33:38 -08004141 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004142 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004143 {"--dispsync"s,
4144 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004145 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004146 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4147 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4148 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4149 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4150 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4151 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004152 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004153 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4154 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155
Dominik Laskowskic2867142019-01-21 11:33:38 -08004156 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004157
Dominik Laskowski46470112019-08-02 13:13:11 -07004158 const auto it = dumpers.find(flag);
4159 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004160 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004161 } else if (!asProto) {
4162 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004163 }
4164
Mathias Agopian9795c422009-08-26 16:36:26 -07004165 if (locked) {
4166 mStateLock.unlock();
4167 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004168
Dominik Laskowski46470112019-08-02 13:13:11 -07004169 if (it == dumpers.end()) {
4170 const LayersProto layersProto = dumpProtoFromMainThread();
4171 if (asProto) {
4172 result.append(layersProto.SerializeAsString());
4173 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004174 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004175 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4176 result.append(LayerProtoParser::layerTreeToString(layerTree));
4177 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004178 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004179 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004182 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004183 return NO_ERROR;
4184}
4185
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004186status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4187 if (asProto && mTracing.isEnabled()) {
4188 mTracing.writeToFileAsync();
4189 }
4190
4191 return doDump(fd, DumpArgs(), asProto);
4192}
4193
Dominik Laskowskic2867142019-01-21 11:33:38 -08004194void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004195 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004196 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004197}
4198
Dominik Laskowskic2867142019-01-21 11:33:38 -08004199void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004200 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004201
Dominik Laskowskic2867142019-01-21 11:33:38 -08004202 if (args.size() > 1) {
4203 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004204 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004205 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004206 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004207 }
Robert Carr2047fae2016-11-28 14:09:09 -08004208 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004209 } else {
4210 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004211 }
4212}
4213
Dominik Laskowskic2867142019-01-21 11:33:38 -08004214void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004215 const bool clearAll = args.size() < 2;
4216 const auto name = clearAll ? String8() : String8(args[1]);
4217
Edgar Arriaga844fa672020-01-16 14:21:42 -08004218 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004219 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004220 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004221 }
Robert Carr2047fae2016-11-28 14:09:09 -08004222 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004223
Svetoslavd85084b2014-03-20 10:28:31 -07004224 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004225}
4226
Dominik Laskowskic2867142019-01-21 11:33:38 -08004227void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4228 mTimeStats->parseArgs(asProto, args, result);
4229}
4230
Jamie Gennis6547ff42013-07-16 20:12:42 -07004231// This should only be called from the main thread. Otherwise it would need
4232// the lock and should use mCurrentState rather than mDrawingState.
4233void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004234 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004235 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004236 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004237
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004238 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004239}
4240
Yiwei Zhang5434a782018-12-05 18:06:32 -08004241void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004242 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004243
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004244 if (isLayerTripleBufferingDisabled())
4245 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004246
Yiwei Zhang5434a782018-12-05 18:06:32 -08004247 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4248 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4249 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4250 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4251 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4252 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004253 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004254}
4255
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004256void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004257 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004258
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004259 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004260 result.append("\n");
4261
Ady Abraham9e16a482019-12-03 17:19:41 -08004262 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004263 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004264 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004265 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004266
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004267 HwcConfigIndexType defaultConfig;
4268 float minFps, maxFps;
4269 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004270 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004271 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004272 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004273 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004274 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4275 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004276
Ana Krulecc2870422019-01-29 19:00:58 -08004277 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004278}
4279
Yiwei Zhang5434a782018-12-05 18:06:32 -08004280void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4281 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004282 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4283 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004284 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004285 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004286 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004287 }
David Sodman4a36e932017-11-07 14:29:47 -08004288 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004289 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004290 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004291 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4292 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004293}
4294
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004295void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4296 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004297 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4298 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004299 for (const auto& segment : history) {
4300 if (!segment.usedThirdBuffer) {
4301 stats.twoBufferTime += segment.totalTime;
4302 }
4303 if (segment.occupancyAverage < 1.0f) {
4304 stats.doubleBufferedTime += segment.totalTime;
4305 } else if (segment.occupancyAverage < 2.0f) {
4306 stats.tripleBufferedTime += segment.totalTime;
4307 }
4308 ++stats.numSegments;
4309 stats.totalTime += segment.totalTime;
4310 }
4311}
4312
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4314 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004315
4316 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4317 const size_t count = currentLayers.size();
4318 for (size_t i=0 ; i<count ; i++) {
4319 currentLayers[i]->dumpFrameEvents(result);
4320 }
4321}
4322
Yiwei Zhang5434a782018-12-05 18:06:32 -08004323void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004324 result.append("Buffering stats:\n");
4325 result.append(" [Layer name] <Active time> <Two buffer> "
4326 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004327 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004328 typedef std::tuple<std::string, float, float, float> BufferTuple;
4329 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004330 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004331 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004332 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004333 if (stats.numSegments == 0) {
4334 continue;
4335 }
4336 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4337 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4338 stats.totalTime;
4339 float doubleBufferRatio = static_cast<float>(
4340 stats.doubleBufferedTime) / stats.totalTime;
4341 float tripleBufferRatio = static_cast<float>(
4342 stats.tripleBufferedTime) / stats.totalTime;
4343 sorted.insert({activeTime, {name, twoBufferRatio,
4344 doubleBufferRatio, tripleBufferRatio}});
4345 }
4346 for (const auto& sortedPair : sorted) {
4347 float activeTime = sortedPair.first;
4348 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4350 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004351 }
4352 result.append("\n");
4353}
4354
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004356 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004357 const auto displayId = display->getId();
4358 if (!displayId) {
4359 continue;
4360 }
4361 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004362 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004363 continue;
4364 }
4365
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366 StringAppendF(&result,
4367 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4368 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004369 uint8_t port;
4370 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004371 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004372 result.append("no identification data\n");
4373 continue;
4374 }
4375
4376 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004377 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004378 continue;
4379 }
4380
4381 const auto edid = parseEdid(data);
4382 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004383 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004384 continue;
4385 }
4386
Yiwei Zhang5434a782018-12-05 18:06:32 -08004387 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004388 result.append(edid->displayName.data(), edid->displayName.length());
4389 result.append("\"\n");
4390 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004391}
4392
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004393void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4394 std::string& result) const {
4395 hwc2_display_t hwcDisplayId;
4396 uint8_t port;
4397 DisplayIdentificationData data;
4398
4399 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4400 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4401 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4402 }
4403}
4404
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004406 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004407 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4408 StringAppendF(&result, "DisplayColorSetting: %s\n",
4409 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004410
4411 // TODO: print out if wide-color mode is active or not
4412
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004413 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004414 const auto displayId = display->getId();
4415 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004416 continue;
4417 }
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004420 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004421 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004422 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004423 }
4424
Lloyd Pique32cbe282018-10-19 13:09:22 -07004425 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004426 StringAppendF(&result, " Current color mode: %s (%d)\n",
4427 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004428 }
4429 result.append("\n");
4430}
4431
Vishnu Nair8406fd72019-07-30 11:29:31 -07004432LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004433 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004434 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4435 layer->writeToProto(layersProto, traceFlags);
4436 }
chaviw1d044282017-09-27 12:19:28 -07004437 return layersProto;
4438}
4439
Vishnu Nair0f085c62019-08-30 08:49:12 -07004440void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4441 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4442 // it.
4443 LayerProto* rootProto = layersProto.add_layers();
4444 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4445 rootProto->set_id(offscreenRootLayerId);
4446 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004447 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004448
4449 for (Layer* offscreenLayer : mOffscreenLayers) {
4450 // Add layer as child of the fake root
4451 rootProto->add_children(offscreenLayer->sequence);
4452
4453 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004454 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004455 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004456 }
4457}
4458
Vishnu Nair8406fd72019-07-30 11:29:31 -07004459LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4460 LayersProto layersProto;
4461 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4462 return layersProto;
4463}
4464
Vishnu Nair0f085c62019-08-30 08:49:12 -07004465void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4466 result.append("Offscreen Layers:\n");
4467 postMessageSync(new LambdaMessage([&]() {
4468 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004469 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004470 layer->dumpCallingUidPid(result);
4471 });
4472 }
4473 }));
4474}
4475
Dominik Laskowskic2867142019-01-21 11:33:38 -08004476void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4477 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004478 Colorizer colorizer(colorize);
4479
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004480 // figure out if we're stuck somewhere
4481 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004482 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004483 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4484
4485 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004486 * Dump library configuration.
4487 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488
4489 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004490 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004491 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004492 appendSfConfigString(result);
4493 appendUiConfigString(result);
4494 appendGuiConfigString(result);
4495 result.append("\n");
4496
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004497 result.append("\nDisplay identification data:\n");
4498 dumpDisplayIdentificationData(result);
4499
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004500 result.append("\nWide-Color information:\n");
4501 dumpWideColorInfo(result);
4502
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004503 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004504 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004505 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004506 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004507 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004508
Andy McFadden41d67d72014-04-25 16:58:34 -07004509 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004510 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004511 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004512 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004513 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004514
Dan Stozab90cf072015-03-05 11:05:59 -08004515 dumpStaticScreenStats(result);
4516 result.append("\n");
4517
Alec Mouri40189b02019-03-05 15:07:54 -08004518 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4519 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4520 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004521
Dan Stozae77c7662016-05-13 11:37:28 -07004522 dumpBufferingStats(result);
4523
Andy McFadden4803b742012-09-24 19:07:20 -07004524 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004525 * Dump the visible layer list
4526 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004528 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4530 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004531 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004532
Chia-I Wu2f884132018-09-13 15:17:58 -07004533 {
Lloyd Pique207def92019-02-28 16:09:52 -08004534 StringAppendF(&result, "Composition layers\n");
4535 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004536 auto* compositionState = layer->getCompositionState();
4537 if (!compositionState) return;
4538
4539 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4540 layer->getDebugName() ? layer->getDebugName()
4541 : "<unknown>");
4542 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004543 });
4544 }
4545
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004546 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004547 * Dump Display state
4548 */
4549
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004550 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004552 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004553 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004554 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004555 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004556 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004557
4558 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004559 * Dump CompositionEngine state
4560 */
4561
4562 mCompositionEngine->dump(result);
4563
4564 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 * Dump SurfaceFlinger global state
4566 */
4567
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004568 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004569 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004570 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004571
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004572 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004573
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004574 DebugEGLImageTracker::getInstance()->dump(result);
4575
Dominik Laskowski075d3172018-05-24 15:50:06 -07004576 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004577 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4578 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004579 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4580 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004581 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 StringAppendF(&result,
4583 " transaction-flags : %08x\n"
4584 " gpu_to_cpu_unsupported : %d\n",
4585 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004586
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004587 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004588 displayId && getHwComposer().isConnected(*displayId)) {
4589 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result,
4591 " refresh-rate : %f fps\n"
4592 " x-dpi : %f\n"
4593 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004594 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4595 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004596 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004599
Dan Stozae22aec72016-08-01 13:20:59 -07004600 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004601 * Tracing state
4602 */
4603 mTracing.dump(result);
4604 result.append("\n");
4605
4606 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004607 * HWC layer minidump
4608 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004609 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004610 const auto displayId = display->getId();
4611 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004612 continue;
4613 }
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004616 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004617 const sp<DisplayDevice> displayDevice = display;
4618 mCurrentState.traverseInZOrder(
4619 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004620 result.append("\n");
4621 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004622
4623 /*
4624 * Dump HWComposer state
4625 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004627 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004628 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004629 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004631 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632
4633 /*
4634 * Dump gralloc state
4635 */
4636 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4637 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004638
4639 /*
4640 * Dump VrFlinger state if in use.
4641 */
4642 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4643 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004645 result.append("\n");
4646 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004647
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004648 result.append(mTimeStats->miniDump());
4649 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004650}
4651
Chia-I Wu28f320b2018-05-03 11:02:56 -07004652void SurfaceFlinger::updateColorMatrixLocked() {
4653 mat4 colorMatrix;
4654 if (mGlobalSaturationFactor != 1.0f) {
4655 // Rec.709 luma coefficients
4656 float3 luminance{0.213f, 0.715f, 0.072f};
4657 luminance *= 1.0f - mGlobalSaturationFactor;
4658 mat4 saturationMatrix = mat4(
4659 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4660 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4661 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4662 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4663 );
4664 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4665 } else {
4666 colorMatrix = mClientColorMatrix * mDaltonizer();
4667 }
4668
4669 if (mCurrentState.colorMatrix != colorMatrix) {
4670 mCurrentState.colorMatrix = colorMatrix;
4671 mCurrentState.colorMatrixChanged = true;
4672 setTransactionFlags(eTransactionNeeded);
4673 }
4674}
4675
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004676status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004677#pragma clang diagnostic push
4678#pragma clang diagnostic error "-Wswitch-enum"
4679 switch (static_cast<ISurfaceComposerTag>(code)) {
4680 // These methods should at minimum make sure that the client requested
4681 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004682 case BOOT_FINISHED:
4683 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004684 case CREATE_DISPLAY:
4685 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004686 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004687 case GET_ANIMATION_FRAME_STATS:
4688 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004689 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004690 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004691 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004692 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4693 case SET_AUTO_LOW_LATENCY_MODE:
4694 case GET_GAME_CONTENT_TYPE_SUPPORT:
4695 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004696 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004697 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004698 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004699 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004700 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004701 case NOTIFY_POWER_HINT:
4702 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004703 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4704 IPCThreadState* ipc = IPCThreadState::self();
4705 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4706 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004707 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004708 }
Robert Carr1db73f62016-12-21 12:58:51 -08004709 return OK;
4710 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004711 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004712 IPCThreadState* ipc = IPCThreadState::self();
4713 const int pid = ipc->getCallingPid();
4714 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004715 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4716 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004717 return PERMISSION_DENIED;
4718 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004719 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004720 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004721 // Used by apps to hook Choreographer to SurfaceFlinger.
4722 case CREATE_DISPLAY_EVENT_CONNECTION:
4723 // The following calls are currently used by clients that do not
4724 // request necessary permissions. However, they do not expose any secret
4725 // information, so it is OK to pass them.
4726 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004727 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004729 case GET_PHYSICAL_DISPLAY_IDS:
4730 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004732 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004733 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004734 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004735 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004736 case GET_DISPLAY_STATS:
4737 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4738 // Calling setTransactionState is safe, because you need to have been
4739 // granted a reference to Client* and Handle* to do anything with it.
4740 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004741 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004742 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004743 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004744 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004745 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004746 // setFrameRate() is deliberately available for apps to call without any
4747 // special permissions.
4748 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004749 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4750 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004751 return OK;
4752 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004753 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004754 case CAPTURE_SCREEN:
4755 case ADD_REGION_SAMPLING_LISTENER:
4756 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004757 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004758 IPCThreadState* ipc = IPCThreadState::self();
4759 const int pid = ipc->getCallingPid();
4760 const int uid = ipc->getCallingUid();
4761 if ((uid != AID_GRAPHICS) &&
4762 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4763 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4764 return PERMISSION_DENIED;
4765 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 return OK;
4767 }
chaviw93df2ea2019-04-30 16:45:12 -07004768 case CAPTURE_SCREEN_BY_ID: {
4769 IPCThreadState* ipc = IPCThreadState::self();
4770 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004771 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004772 return OK;
4773 }
4774 return PERMISSION_DENIED;
4775 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004776 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004777
4778 // These codes are used for the IBinder protocol to either interrogate the recipient
4779 // side of the transaction for its canonical interface descriptor or to dump its state.
4780 // We let them pass by default.
4781 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4782 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4783 code == IBinder::SYSPROPS_TRANSACTION) {
4784 return OK;
4785 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004786 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004788 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004789 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4790 return OK;
4791 }
4792 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4793 return PERMISSION_DENIED;
4794#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004795}
4796
Ana Krulec13be8ad2018-08-21 02:43:56 +00004797status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4798 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004799 status_t credentialCheck = CheckTransactCodeCredentials(code);
4800 if (credentialCheck != OK) {
4801 return credentialCheck;
4802 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004804 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4805 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004806 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004807 IPCThreadState* ipc = IPCThreadState::self();
4808 const int uid = ipc->getCallingUid();
4809 if (CC_UNLIKELY(uid != AID_SYSTEM
4810 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004811 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004812 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004813 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004814 return PERMISSION_DENIED;
4815 }
4816 int n;
4817 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004818 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004819 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 return NO_ERROR;
4821 case 1002: // SHOW_UPDATES
4822 n = data.readInt32();
4823 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004824 invalidateHwcGeometry();
4825 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004826 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004827 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004828 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004829 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004830 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004831 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004832 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004833 setTransactionFlags(
4834 eTransactionNeeded|
4835 eDisplayTransactionNeeded|
4836 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004837 return NO_ERROR;
4838 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004839 case 1006:{ // send empty update
4840 signalRefresh();
4841 return NO_ERROR;
4842 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004843 case 1008: // toggle use of hw composer
4844 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004845 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004846 invalidateHwcGeometry();
4847 repaintEverything();
4848 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004849 case 1009: // toggle use of transform hint
4850 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004851 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004852 invalidateHwcGeometry();
4853 repaintEverything();
4854 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004855 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004856 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004857 reply->writeInt32(0);
4858 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004859 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004860 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004861 return NO_ERROR;
4862 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004863 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004864 if (!display) {
4865 return NAME_NOT_FOUND;
4866 }
4867
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004868 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004869 return NO_ERROR;
4870 }
4871 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004872 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004873 // daltonize
4874 n = data.readInt32();
4875 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004876 case 1:
4877 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4878 break;
4879 case 2:
4880 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4881 break;
4882 case 3:
4883 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4884 break;
4885 default:
4886 mDaltonizer.setType(ColorBlindnessType::None);
4887 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004888 }
4889 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004890 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004891 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004892 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004893 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004894
4895 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004897 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004898 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004899 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004900 // apply a color matrix
4901 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004902 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004903 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004904 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004905 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004906 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004907 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004908 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004909 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004910 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004911 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004912
4913 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4914 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004915 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004916 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4917 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4918 }
4919
Chia-I Wu28f320b2018-05-03 11:02:56 -07004920 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004921 return NO_ERROR;
4922 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004923 case 1016: { // Unused.
4924 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004925 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004926 case 1017: {
4927 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004928 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004929 return NO_ERROR;
4930 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004931 case 1018: { // Modify Choreographer's phase offset
4932 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004933 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004934 return NO_ERROR;
4935 }
4936 case 1019: { // Modify SurfaceFlinger's phase offset
4937 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004938 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004939 return NO_ERROR;
4940 }
Irvel468051e2016-06-13 16:44:44 -07004941 case 1020: { // Layer updates interceptor
4942 n = data.readInt32();
4943 if (n) {
4944 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004945 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004946 }
4947 else{
4948 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004949 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004950 }
4951 return NO_ERROR;
4952 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004953 case 1021: { // Disable HWC virtual displays
4954 n = data.readInt32();
4955 mUseHwcVirtualDisplays = !n;
4956 return NO_ERROR;
4957 }
Romain Guy0147a172017-06-01 13:53:56 -07004958 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004959 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004960 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004961
Chia-I Wu28f320b2018-05-03 11:02:56 -07004962 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004963 return NO_ERROR;
4964 }
Romain Guy54f154a2017-10-24 21:40:32 +01004965 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004966 int32_t colorMode;
4967
Chia-I Wu0d711262018-05-21 15:19:35 -07004968 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004969 if (data.readInt32(&colorMode) == NO_ERROR) {
4970 mForceColorMode = static_cast<ColorMode>(colorMode);
4971 }
Romain Guy54f154a2017-10-24 21:40:32 +01004972 invalidateHwcGeometry();
4973 repaintEverything();
4974 return NO_ERROR;
4975 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004976 // Deprecate, use 1030 to check whether the device is color managed.
4977 case 1024: {
4978 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004979 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004980 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004981 n = data.readInt32();
4982 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004983 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004984 Mutex::Autolock lock(mStateLock);
4985 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004986 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004987 reply->writeInt32(NO_ERROR);
4988 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004989 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004990 bool writeFile = false;
4991 {
4992 Mutex::Autolock lock(mStateLock);
4993 mTracingEnabledChanged = true;
4994 writeFile = mTracing.disable();
4995 }
4996
4997 if (writeFile) {
4998 reply->writeInt32(mTracing.writeToFile());
4999 } else {
5000 reply->writeInt32(NO_ERROR);
5001 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005002 }
5003 return NO_ERROR;
5004 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005005 case 1026: { // Get layer tracing status
5006 reply->writeBool(mTracing.isEnabled());
5007 return NO_ERROR;
5008 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005009 // Is a DisplayColorSetting supported?
5010 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005011 const auto display = getDefaultDisplayDevice();
5012 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005013 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005014 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005015
5016 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5017 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005018 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005019 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005020 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005021 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005022 reply->writeBool(true);
5023 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005024 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005025 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005026 break;
5027 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005028 reply->writeBool(
5029 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005030 break;
5031 }
5032 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005033 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005034 // Is VrFlinger active?
5035 case 1028: {
5036 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005037 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005038 return NO_ERROR;
5039 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005040 // Set buffer size for SF tracing (value in KB)
5041 case 1029: {
5042 n = data.readInt32();
5043 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5044 ALOGW("Invalid buffer size: %d KB", n);
5045 reply->writeInt32(BAD_VALUE);
5046 return BAD_VALUE;
5047 }
5048
5049 ALOGD("Updating trace buffer to %d KB", n);
5050 mTracing.setBufferSize(n * 1024);
5051 reply->writeInt32(NO_ERROR);
5052 return NO_ERROR;
5053 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005054 // Is device color managed?
5055 case 1030: {
5056 reply->writeBool(useColorManagement);
5057 return NO_ERROR;
5058 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005059 // Override default composition data space
5060 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5061 // && adb shell stop zygote && adb shell start zygote
5062 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5063 // adb shell stop zygote && adb shell start zygote
5064 case 1031: {
5065 Mutex::Autolock _l(mStateLock);
5066 n = data.readInt32();
5067 if (n) {
5068 n = data.readInt32();
5069 if (n) {
5070 Dataspace dataspace = static_cast<Dataspace>(n);
5071 if (!validateCompositionDataspace(dataspace)) {
5072 return BAD_VALUE;
5073 }
5074 mDefaultCompositionDataspace = dataspace;
5075 }
5076 n = data.readInt32();
5077 if (n) {
5078 Dataspace dataspace = static_cast<Dataspace>(n);
5079 if (!validateCompositionDataspace(dataspace)) {
5080 return BAD_VALUE;
5081 }
5082 mWideColorGamutCompositionDataspace = dataspace;
5083 }
5084 } else {
5085 // restore composition data space.
5086 mDefaultCompositionDataspace = defaultCompositionDataspace;
5087 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5088 }
5089 return NO_ERROR;
5090 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005091 // Set trace flags
5092 case 1033: {
5093 n = data.readUint32();
5094 ALOGD("Updating trace flags to 0x%x", n);
5095 mTracing.setTraceFlags(n);
5096 reply->writeInt32(NO_ERROR);
5097 return NO_ERROR;
5098 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005099 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005100 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005101 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005102 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005103 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5104 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005105 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005106 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005107 } else {
5108 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005109 }
5110 return NO_ERROR;
5111 }
Ady Abraham34392f72019-04-10 11:29:27 -07005112 case 1035: {
5113 n = data.readInt32();
5114 mDebugDisplayConfigSetByBackdoor = false;
5115 if (n >= 0) {
5116 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005117 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005118 if (result != NO_ERROR) {
5119 return result;
5120 }
5121 mDebugDisplayConfigSetByBackdoor = true;
5122 }
5123 return NO_ERROR;
5124 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005125 }
5126 }
5127 return err;
5128}
5129
Steven Thomas6d8110b2017-08-31 18:24:21 -07005130void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005131 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005132 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005133}
5134
Ana Krulec7d1d6832018-12-27 11:10:09 -08005135void SurfaceFlinger::repaintEverythingForHWC() {
5136 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005137 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005138 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005139}
5140
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005141// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5142class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005143public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005144 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5145 ~WindowDisconnector() {
5146 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005147 }
5148
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005149private:
5150 ANativeWindow* mWindow;
5151 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005152};
5153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005154status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005155 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005156 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5157 const Rect& sourceCrop, uint32_t reqWidth,
5158 uint32_t reqHeight, bool useIdentityTransform,
5159 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005160 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005162 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005163
Dominik Laskowski718f9602019-11-09 20:01:35 -08005164 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5165 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5166 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5167 renderAreaRotation = ui::Transform::ROT_0;
5168 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005169
Chia-I Wu20261cb2018-08-23 12:55:44 -07005170 sp<DisplayDevice> display;
5171 {
5172 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005173
Chia-I Wu20261cb2018-08-23 12:55:44 -07005174 display = getDisplayDeviceLocked(displayToken);
5175 if (!display) return BAD_VALUE;
5176
Chia-I Wucb023152018-08-28 12:57:23 -07005177 // set the requested width/height to the logical display viewport size
5178 // by default
5179 if (reqWidth == 0 || reqHeight == 0) {
5180 reqWidth = uint32_t(display->getViewport().width());
5181 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005182 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005183 }
5184
Peiyong Lin0e003c92018-09-17 11:09:51 -07005185 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005186 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005187
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005188 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5189 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005190 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005191 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005192}
5193
chaviw93df2ea2019-04-30 16:45:12 -07005194static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5195 switch (colorMode) {
5196 case ColorMode::DISPLAY_P3:
5197 case ColorMode::BT2100_PQ:
5198 case ColorMode::BT2100_HLG:
5199 case ColorMode::DISPLAY_BT2020:
5200 return Dataspace::DISPLAY_P3;
5201 default:
5202 return Dataspace::V0_SRGB;
5203 }
5204}
5205
5206const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5207 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5208 if (displayToken) {
5209 return getDisplayDeviceLocked(displayToken);
5210 }
5211 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5212 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005213 return getDisplayByLayerStack(displayOrLayerStack);
5214}
5215
5216const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005217 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005218 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005219 return display;
5220 }
5221 }
5222 return nullptr;
5223}
5224
5225status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5226 sp<GraphicBuffer>* outBuffer) {
5227 sp<DisplayDevice> display;
5228 uint32_t width;
5229 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005230 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005231 {
5232 Mutex::Autolock _l(mStateLock);
5233 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5234 if (!display) {
5235 return BAD_VALUE;
5236 }
5237
5238 width = uint32_t(display->getViewport().width());
5239 height = uint32_t(display->getViewport().height());
5240
Dominik Laskowski718f9602019-11-09 20:01:35 -08005241 const auto orientation = display->getOrientation();
5242 captureOrientation = ui::Transform::toRotationFlags(orientation);
5243
5244 switch (captureOrientation) {
5245 case ui::Transform::ROT_90:
5246 captureOrientation = ui::Transform::ROT_270;
5247 break;
5248
5249 case ui::Transform::ROT_270:
5250 captureOrientation = ui::Transform::ROT_90;
5251 break;
5252
5253 case ui::Transform::ROT_INVALID:
5254 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5255 captureOrientation = ui::Transform::ROT_0;
5256 break;
5257
5258 default:
5259 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005260 }
chaviw93df2ea2019-04-30 16:45:12 -07005261 *outDataspace =
5262 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5263 }
5264
5265 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5266 false /* captureSecureLayers */);
5267
5268 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5269 std::placeholders::_1);
5270 bool ignored = false;
5271 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5272 false /* useIdentityTransform */,
5273 ignored /* outCapturedSecureLayers */);
5274}
5275
Robert Carr866455f2019-04-02 16:28:26 -07005276status_t SurfaceFlinger::captureLayers(
5277 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5278 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5279 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5280 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005281 ATRACE_CALL();
5282
5283 class LayerRenderArea : public RenderArea {
5284 public:
Robert Carr578038f2018-03-09 12:25:24 -08005285 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005286 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005287 bool childrenOnly, const Rect& displayViewport)
5288 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005289 mLayer(layer),
5290 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005291 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005292 mFlinger(flinger),
5293 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005294 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005295 Rect getBounds() const override {
5296 const Layer::State& layerState(mLayer->getDrawingState());
5297 return mLayer->getBufferSize(layerState);
5298 }
Marissa Wall61c58622018-07-18 10:12:20 -07005299 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005300 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005301 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005302 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005303 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005304 }
chaviwa76b2712017-09-20 12:02:26 -07005305 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005306 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005307 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005308 Rect getSourceCrop() const override {
5309 if (mCrop.isEmpty()) {
5310 return getBounds();
5311 } else {
5312 return mCrop;
5313 }
5314 }
Robert Carr578038f2018-03-09 12:25:24 -08005315 class ReparentForDrawing {
5316 public:
5317 const sp<Layer>& oldParent;
5318 const sp<Layer>& newParent;
5319
Vishnu Nair4351ad52019-02-11 14:13:02 -08005320 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5321 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005322 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005323 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005324 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5325 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005326 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005327 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005328 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005329 };
5330
5331 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005332 const Rect sourceCrop = getSourceCrop();
5333 // no need to check rotation because there is none
5334 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5335 sourceCrop.height() != getReqHeight();
5336
Robert Carr578038f2018-03-09 12:25:24 -08005337 if (!mChildrenOnly) {
5338 mTransform = mLayer->getTransform().inverse();
5339 drawLayers();
5340 } else {
5341 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005342 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5343 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005344 // In the "childrenOnly" case we reparent the children to a screenshot
5345 // layer which has no properties set and which does not draw.
5346 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005347 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5348 "Screenshot Parent"s, w, h, 0,
5349 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005350
Vishnu Nair4351ad52019-02-11 14:13:02 -08005351 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005352 drawLayers();
5353 }
5354 }
chaviwa76b2712017-09-20 12:02:26 -07005355
chaviwa76b2712017-09-20 12:02:26 -07005356 private:
chaviw7206d492017-11-10 16:16:12 -08005357 const sp<Layer> mLayer;
5358 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005359
Peiyong Linefefaac2018-08-17 12:27:51 -07005360 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005361 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005362
5363 SurfaceFlinger* mFlinger;
5364 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005365 };
5366
Robert Carrc0df3122019-04-11 13:18:21 -07005367 int reqWidth = 0;
5368 int reqHeight = 0;
5369 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005370 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005371 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005372 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005373 {
5374 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005375
Robert Carrc0df3122019-04-11 13:18:21 -07005376 parent = fromHandle(layerHandleBinder);
5377 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5378 ALOGE("captureLayers called with an invalid or removed parent");
5379 return NAME_NOT_FOUND;
5380 }
5381
5382 const int uid = IPCThreadState::self()->getCallingUid();
5383 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5384 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5385 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5386 return PERMISSION_DENIED;
5387 }
5388
Vishnu Nairefc42e22019-12-03 17:36:12 -08005389 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005390 if (sourceCrop.width() <= 0) {
5391 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005392 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005393 }
5394
5395 if (sourceCrop.height() <= 0) {
5396 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005397 crop.bottom = parentSourceBounds.getHeight();
5398 }
5399
5400 if (crop.isEmpty() || frameScale <= 0.0f) {
5401 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5402 // crop was not specified, or an invalid frame scale was provided.
5403 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005404 }
5405 reqWidth = crop.width() * frameScale;
5406 reqHeight = crop.height() * frameScale;
5407
5408 for (const auto& handle : excludeHandles) {
5409 sp<Layer> excludeLayer = fromHandle(handle);
5410 if (excludeLayer != nullptr) {
5411 excludeLayers.emplace(excludeLayer);
5412 } else {
5413 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5414 return NAME_NOT_FOUND;
5415 }
5416 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005417
5418 auto display = getDisplayByLayerStack(parent->getLayerStack());
5419 if (!display) {
5420 return BAD_VALUE;
5421 }
5422
5423 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005424 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005425
Chia-I Wu20261cb2018-08-23 12:55:44 -07005426 // really small crop or frameScale
5427 if (reqWidth <= 0) {
5428 reqWidth = 1;
5429 }
5430 if (reqHeight <= 0) {
5431 reqHeight = 1;
5432 }
5433
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005434 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5435 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005436 auto traverseLayers = [parent, childrenOnly,
5437 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005438 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5439 if (!layer->isVisible()) {
5440 return;
Robert Carr578038f2018-03-09 12:25:24 -08005441 } else if (childrenOnly && layer == parent.get()) {
5442 return;
chaviwa76b2712017-09-20 12:02:26 -07005443 }
Robert Carr866455f2019-04-02 16:28:26 -07005444
5445 sp<Layer> p = layer;
5446 while (p != nullptr) {
5447 if (excludeLayers.count(p) != 0) {
5448 return;
5449 }
5450 p = p->getParent();
5451 }
5452
chaviwa76b2712017-09-20 12:02:26 -07005453 visitor(layer);
5454 });
5455 };
Robert Carr108b2c72019-04-02 16:32:58 -07005456
5457 bool outCapturedSecureLayers = false;
5458 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5459 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005460}
5461
5462status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5463 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005464 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005465 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005466 bool useIdentityTransform,
5467 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005468 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005469
Peiyong Lin0e003c92018-09-17 11:09:51 -07005470 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005471 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5472 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005473 *outBuffer =
5474 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5475 static_cast<android_pixel_format>(reqPixelFormat), 1,
5476 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005477
Robert Carr108b2c72019-04-02 16:32:58 -07005478 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5479 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005480}
5481
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005482status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5483 TraverseLayersFunction traverseLayers,
5484 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005485 bool useIdentityTransform,
5486 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005487 // This mutex protects syncFd and captureResult for communication of the return values from the
5488 // main thread back to this Binder thread
5489 std::mutex captureMutex;
5490 std::condition_variable captureCondition;
5491 std::unique_lock<std::mutex> captureLock(captureMutex);
5492 int syncFd = -1;
5493 std::optional<status_t> captureResult;
5494
Robert Carr03480e22018-01-04 16:02:06 -08005495 const int uid = IPCThreadState::self()->getCallingUid();
5496 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5497
Dominik Laskowski8c001672018-05-30 16:52:06 -07005498 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005499 // If there is a refresh pending, bug out early and tell the binder thread to try again
5500 // after the refresh.
5501 if (mRefreshPending) {
5502 ATRACE_NAME("Skipping screenshot for now");
5503 std::unique_lock<std::mutex> captureLock(captureMutex);
5504 captureResult = std::make_optional<status_t>(EAGAIN);
5505 captureCondition.notify_one();
5506 return;
5507 }
5508
5509 status_t result = NO_ERROR;
5510 int fd = -1;
5511 {
5512 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005513 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005514 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005515 useIdentityTransform, forSystem, &fd,
5516 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005517 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005518 }
5519
5520 {
5521 std::unique_lock<std::mutex> captureLock(captureMutex);
5522 syncFd = fd;
5523 captureResult = std::make_optional<status_t>(result);
5524 captureCondition.notify_one();
5525 }
5526 });
5527
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005528 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005529 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005530 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005531 while (*captureResult == EAGAIN) {
5532 captureResult.reset();
5533 result = postMessageAsync(message);
5534 if (result != NO_ERROR) {
5535 return result;
5536 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005537 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005538 }
5539 result = *captureResult;
5540 }
5541
5542 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005543 sync_wait(syncFd, -1);
5544 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005545 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005546
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005547 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005548}
5549
chaviwa76b2712017-09-20 12:02:26 -07005550void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005551 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005552 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5553 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005554 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005555
chaviwa76b2712017-09-20 12:02:26 -07005556 const auto reqWidth = renderArea.getReqWidth();
5557 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005558 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005559 const auto transform = renderArea.getTransform();
5560 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005561 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005562
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005563 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005564 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005565
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005566 // assume that bounds are never offset, and that they are the same as the
5567 // buffer bounds.
5568 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005569 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005570 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005571
5572 // Now take into account the rotation flag. We append a transform that
5573 // rotates the layer stack about the origin, then translate by buffer
5574 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005575 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005576 int displacementX = 0;
5577 int displacementY = 0;
5578 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5579 switch (rotation) {
5580 case ui::Transform::ROT_90:
5581 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005582 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005583 break;
5584 case ui::Transform::ROT_180:
5585 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005586 displacementY = renderArea.getBounds().getWidth();
5587 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005588 break;
5589 case ui::Transform::ROT_270:
5590 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005591 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005592 break;
5593 default:
5594 break;
5595 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005596
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005597 // We need to transform the clipping window into the right spot.
5598 // First, rotate the clipping rectangle by the rotation hint to get the
5599 // right orientation
5600 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5601 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5602 const vec4 rotClipTL = rotMatrix * clipTL;
5603 const vec4 rotClipBR = rotMatrix * clipBR;
5604 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5605 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5606 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5607 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5608
5609 // Now reposition the clipping rectangle with the displacement vector
5610 // computed above.
5611 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005612 clientCompositionDisplay.clip =
5613 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5614 newClipRight + displacementX, newClipBottom + displacementY);
5615
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005616 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005617 clientCompositionDisplay.globalTransform =
5618 clipTransform * clientCompositionDisplay.globalTransform;
5619
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005620 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5621 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005622
chaviw50da5042018-04-09 13:49:37 -07005623 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005624
Vishnu Nair9b079a22020-01-21 14:36:08 -08005625 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005626 fillLayer.source.buffer.buffer = nullptr;
5627 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5628 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5629 fillLayer.alpha = half(alpha);
5630 clientCompositionLayers.push_back(fillLayer);
5631
5632 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005633 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005634 const bool supportProtectedContent = false;
5635 Region clip(renderArea.getBounds());
5636 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5637 clip,
5638 useIdentityTransform,
5639 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5640 renderArea.isSecure(),
5641 supportProtectedContent,
5642 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005643 displayViewport,
5644 clientCompositionDisplay.outputDataspace,
5645 true, /* realContentIsVisible */
5646 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005647 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005648 std::vector<compositionengine::LayerFE::LayerSettings> results =
5649 layer->prepareClientCompositionList(targetSettings);
5650 clientCompositionLayers.insert(clientCompositionLayers.end(),
5651 std::make_move_iterator(results.begin()),
5652 std::make_move_iterator(results.end()));
5653 results.clear();
5654
chaviwa76b2712017-09-20 12:02:26 -07005655 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005656
Vishnu Nair9b079a22020-01-21 14:36:08 -08005657 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5658 clientCompositionLayers.reserve(clientCompositionLayers.size());
5659 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5660 std::back_inserter(clientCompositionLayerPointers),
5661 [](compositionengine::LayerFE::LayerSettings& settings)
5662 -> renderengine::LayerSettings* { return &settings; });
5663
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005664 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005665 // Use an empty fence for the buffer fence, since we just created the buffer so
5666 // there is no need for synchronization with the GPU.
5667 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005668 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005669 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005670 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005671 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005672
5673 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005674}
5675
chaviwa76b2712017-09-20 12:02:26 -07005676status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5677 TraverseLayersFunction traverseLayers,
5678 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005679 bool useIdentityTransform, bool forSystem,
5680 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005681 ATRACE_CALL();
5682
chaviwa76b2712017-09-20 12:02:26 -07005683 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005684 outCapturedSecureLayers =
5685 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005686 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005687
Robert Carr03480e22018-01-04 16:02:06 -08005688 // We allow the system server to take screenshots of secure layers for
5689 // use in situations like the Screen-rotation animation and place
5690 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005691 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005692 ALOGW("FB is protected: PERMISSION_DENIED");
5693 return PERMISSION_DENIED;
5694 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005696 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005697}
5698
chaviw95ef3c42019-02-14 10:55:09 -08005699void SurfaceFlinger::setInputWindowsFinished() {
5700 Mutex::Autolock _l(mStateLock);
5701
5702 mPendingSyncInputWindows = false;
5703 mTransactionCV.broadcast();
5704}
chaviw5f21a5e2019-02-14 10:00:34 -08005705
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005706// ---------------------------------------------------------------------------
5707
Edgar Arriaga844fa672020-01-16 14:21:42 -08005708void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5709 layersSortedByZ.traverse(visitor);
5710}
5711
Dan Stoza412903f2017-04-27 13:42:17 -07005712void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5713 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005714}
5715
Dan Stoza412903f2017-04-27 13:42:17 -07005716void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5717 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005718}
5719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005720void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005721 const LayerVector::Visitor& visitor) {
5722 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005723 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005724 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005725 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005726 continue;
5727 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005728 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005729 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005730 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005731 return;
5732 }
chaviwa76b2712017-09-20 12:02:26 -07005733 if (!layer->isVisible()) {
5734 return;
5735 }
5736 visitor(layer);
5737 });
5738 }
5739}
5740
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005741status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5742 HwcConfigIndexType defaultConfig,
5743 float minRefreshRate,
5744 float maxRefreshRate) {
5745 Mutex::Autolock lock(mStateLock);
5746
Dominik Laskowski22488f62019-03-28 09:53:04 -07005747 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005748 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5749 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5750 // it should go thru setDesiredActiveConfig, similar to primary display.
5751 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5752 const auto displayId = display->getId();
5753 LOG_ALWAYS_FATAL_IF(!displayId);
5754
5755 HWC2::VsyncPeriodChangeConstraints constraints;
5756 constraints.desiredTimeNanos = systemTime();
5757 constraints.seamlessRequired = false;
5758
5759 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005760 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5761 constraints, &timeline) < 0) {
5762 return BAD_VALUE;
5763 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005764 if (timeline.refreshRequired) {
5765 repaintEverythingForHWC();
5766 }
5767
Ady Abrahamdfa37362020-01-21 18:02:39 -08005768 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005769 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005770 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5771 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005772 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005773 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005774 }
5775
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005776 if (mDebugDisplayConfigSetByBackdoor) {
5777 // ignore this request as config is overridden by backdoor
5778 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005779 }
5780
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005781 bool policyChanged;
5782 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5783 &policyChanged) < 0) {
5784 return BAD_VALUE;
5785 }
5786 if (!policyChanged) {
5787 return NO_ERROR;
5788 }
5789
5790 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5791 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005792
5793 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5794 // that listeners that care about a change in allowed configs can get the notification.
5795 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005796 const nsecs_t vsyncPeriod =
5797 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005798 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005799 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005800
Ana Krulec3f6a2062020-01-23 15:48:01 -08005801 auto configId = mScheduler->getPreferredConfigId();
5802 auto preferredRefreshRate = configId
5803 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5804 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5805 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5806 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5807 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5808
5809 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5810 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5811 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005812 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005813 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005814 }
5815
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005816 return NO_ERROR;
5817}
5818
Ana Krulec0782b882019-10-15 17:34:54 -07005819status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005820 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005821 float maxRefreshRate) {
5822 ATRACE_CALL();
5823
5824 if (!displayToken) {
5825 return BAD_VALUE;
5826 }
5827
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005828 status_t result = NO_ERROR;
5829
Ana Krulec234bb162019-11-10 22:55:55 +01005830 postMessageSync(new LambdaMessage([&]() {
5831 const auto display = getDisplayDeviceLocked(displayToken);
5832 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005833 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005834 ALOGE("Attempt to set desired display configs for invalid display token %p",
5835 displayToken.get());
5836 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005837 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005838 ALOGW("Attempt to set desired display configs for virtual display");
5839 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005840 result =
5841 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5842 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005843 }
5844 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005845
5846 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005847}
5848
5849status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005850 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005851 float* outMinRefreshRate,
5852 float* outMaxRefreshRate) {
5853 ATRACE_CALL();
5854
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005855 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005856 return BAD_VALUE;
5857 }
5858
5859 Mutex::Autolock lock(mStateLock);
5860 const auto display = getDisplayDeviceLocked(displayToken);
5861 if (!display) {
5862 return NAME_NOT_FOUND;
5863 }
5864
5865 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005866 HwcConfigIndexType defaultConfig;
5867 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5868 *outDefaultConfig = defaultConfig.value();
5869 return NO_ERROR;
5870 } else if (display->isVirtual()) {
5871 return BAD_VALUE;
5872 } else {
5873 const auto displayId = display->getId();
5874 if (!displayId) {
5875 return BAD_VALUE;
5876 }
5877 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5878 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5879 *outMinRefreshRate = 1e9f / vsyncPeriod;
5880 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5881 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005882 }
Ana Krulec0782b882019-10-15 17:34:54 -07005883}
5884
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005885void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005886 mFlinger->setInputWindowsFinished();
5887}
5888
Robert Carrc0df3122019-04-11 13:18:21 -07005889sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005890 BBinder* b = nullptr;
5891 if (handle) {
5892 b = handle->localBinder();
5893 }
Robert Carrc0df3122019-04-11 13:18:21 -07005894 if (b == nullptr) {
5895 return nullptr;
5896 }
5897 auto it = mLayersByLocalBinderToken.find(b);
5898 if (it != mLayersByLocalBinderToken.end()) {
5899 return it->second.promote();
5900 }
5901 return nullptr;
5902}
5903
Dominik Laskowski75848362019-11-11 17:57:20 -08005904void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005905 mNumLayers++;
5906 mScheduler->registerLayer(layer);
5907}
5908
5909void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5910 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005911 removeFromOffscreenLayers(layer);
5912}
5913
5914// WARNING: ONLY CALL THIS FROM LAYER DTOR
5915// Here we add children in the current state to offscreen layers and remove the
5916// layer itself from the offscreen layer list. Since
5917// this is the dtor, it is safe to access the current state. This keeps us
5918// from dangling children layers such that they are not reachable from the
5919// Drawing state nor the offscreen layer list
5920// See b/141111965
5921void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5922 for (auto& child : layer->getCurrentChildren()) {
5923 mOffscreenLayers.emplace(child.get());
5924 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005925 mOffscreenLayers.erase(layer);
5926}
5927
Alec Mouri4545a8a2019-08-08 20:05:32 -07005928void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5929 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5930}
5931
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005932status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5933 float lightPosY, float lightPosZ,
5934 float lightRadius) {
5935 Mutex::Autolock _l(mStateLock);
5936 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5937 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5938 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5939 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5940 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5941
5942 // these values are overridden when calculating the shadow settings for a layer.
5943 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5944 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005945 return NO_ERROR;
5946}
5947
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005948const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5949 const {
5950 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5951 // on the work to remove the table in that bug rather than adding more to
5952 // it.
5953 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5954 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5955 // supported, and exposed via the
5956 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5957 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5958 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5959 };
5960 return genericLayerMetadataKeyMap;
5961}
5962
Steven Thomas62a4cf82020-01-31 12:04:03 -08005963status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5964 int8_t compatibility) {
5965 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5966 return BAD_VALUE;
5967 }
5968
5969 Mutex::Autolock lock(mStateLock);
5970 if (authenticateSurfaceTextureLocked(surface)) {
5971 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5972 if (layer->setFrameRate(
5973 Layer::FrameRate(frameRate,
5974 Layer::FrameRate::convertCompatibility(compatibility)))) {
5975 setTransactionFlags(eTraversalNeeded);
5976 }
5977 } else {
5978 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5979 return BAD_VALUE;
5980 }
5981 return NO_ERROR;
5982}
5983
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005984} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005985
Mathias Agopian3f844832013-08-07 21:24:32 -07005986#if defined(__gl_h_)
5987#error "don't include gl/gl.h in this file"
5988#endif
5989
5990#if defined(__gl2_h_)
5991#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005992#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005993
5994// TODO(b/129481165): remove the #pragma below and fix conversion issues
5995#pragma clang diagnostic pop // ignored "-Wconversion"