blob: 1da894daf8bbbed0c9af9734875b12f177086916 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquede196652020-01-22 17:29:58 -080039#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080040#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070041#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080043#include <configstore/Utils.h>
44#include <cutils/compiler.h>
45#include <cutils/properties.h>
46#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080048#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070049#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070050#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080055#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080056#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080057#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080059#include <layerproto/LayerProtoParser.h>
60#include <log/log.h>
61#include <private/android_filesystem_config.h>
62#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070063#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080064#include <statslog.h>
65#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <ui/ColorSpace.h>
67#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080068#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <ui/DisplayInfo.h>
70#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080071#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <ui/GraphicBufferAllocator.h>
73#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070074#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070076#include <utils/String16.h>
77#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070078#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080079#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070080#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Alec Mouri5f487d42020-02-06 09:26:19 -080082#include <algorithm>
83#include <cinttypes>
84#include <cmath>
85#include <cstdint>
86#include <functional>
87#include <mutex>
88#include <optional>
89#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Robert Carr578038f2018-03-09 12:25:24 -080091#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070092#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070093#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020094#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080096#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070098#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070099#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700100#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700101#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700102#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800103#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700105#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800106#include "Layer.h"
107#include "LayerVector.h"
108#include "MonitoredProducer.h"
109#include "NativeWindowSurface.h"
110#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700111#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700112#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700113#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114#include "Scheduler/EventControlThread.h"
115#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700116#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700117#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700118#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800119#include "StartPropertySetThread.h"
120#include "SurfaceFlingerProperties.h"
121#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800122#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700123#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800124#include "android-base/stringprintf.h"
125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700127
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700128using namespace std::string_literals;
129
Jaesoo Lee43518572017-01-23 19:03:16 +0900130using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900131using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900132using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133
Ady Abraham8532d012019-05-08 14:50:56 -0700134using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800135using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700136using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700137using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800138using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700139using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700140using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900141
Steven Thomasb02664d2017-07-26 18:48:28 -0700142namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700143
144#pragma clang diagnostic push
145#pragma clang diagnostic error "-Wswitch-enum"
146
147bool isWideColorMode(const ColorMode colorMode) {
148 switch (colorMode) {
149 case ColorMode::DISPLAY_P3:
150 case ColorMode::ADOBE_RGB:
151 case ColorMode::DCI_P3:
152 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700153 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700154 case ColorMode::BT2100_PQ:
155 case ColorMode::BT2100_HLG:
156 return true;
157 case ColorMode::NATIVE:
158 case ColorMode::STANDARD_BT601_625:
159 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
160 case ColorMode::STANDARD_BT601_525:
161 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
162 case ColorMode::STANDARD_BT709:
163 case ColorMode::SRGB:
164 return false;
165 }
166 return false;
167}
168
169#pragma clang diagnostic pop
170
Steven Thomasb02664d2017-07-26 18:48:28 -0700171class ConditionalLock {
172public:
173 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
174 if (lock) {
175 mMutex.lock();
176 }
177 }
178 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
179private:
180 Mutex& mMutex;
181 bool mLocked;
182};
Peiyong Linfca547f2018-07-09 13:03:33 -0700183
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800184// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
185constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
186
187float getDensityFromProperty(const char* property, bool required) {
188 char value[PROPERTY_VALUE_MAX];
189 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
190 if (!density && required) {
191 ALOGE("%s must be defined as a build property", property);
192 return FALLBACK_DENSITY;
193 }
194 return density / 160.f;
195}
196
Peiyong Lin9d846a52018-11-05 13:18:20 -0800197// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
198bool validateCompositionDataspace(Dataspace dataspace) {
199 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
200}
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202} // namespace anonymous
203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204// ---------------------------------------------------------------------------
205
Mathias Agopian99b49842011-06-27 16:05:52 -0700206const String16 sHardwareTest("android.permission.HARDWARE_TEST");
207const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
208const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
209const String16 sDump("android.permission.DUMP");
210
211// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700212int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700213bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800214uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800215bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800216bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800217int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600218bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800219ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700220bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700221bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700222Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
223ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
224Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
225ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800226bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700227
Kalle Raitaa099a242017-01-11 11:17:29 -0800228std::string getHwcServiceName() {
229 char value[PROPERTY_VALUE_MAX] = {};
230 property_get("debug.sf.hwc_service_name", value, "default");
231 ALOGI("Using HWComposer service: '%s'", value);
232 return std::string(value);
233}
234
235bool useTrebleTestingOverride() {
236 char value[PROPERTY_VALUE_MAX] = {};
237 property_get("debug.sf.treble_testing_override", value, "false");
238 ALOGI("Treble testing override: '%s'", value);
239 return std::string(value) == "true";
240}
241
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800242std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
243 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Enhanced");
250 default:
251 return std::string("Unknown ") +
252 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800253 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800254}
255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800257
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
259 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700261 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700262 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700264 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800265 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
266 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800267
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700268SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800269 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800278
Steven Thomas050b2c82017-03-06 11:45:16 -0800279 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 mDefaultCompositionDataspace =
289 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700290 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
291 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 defaultCompositionDataspace = mDefaultCompositionDataspace;
293 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
294 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
295 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
296 wideColorGamutCompositionPixelFormat =
297 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700298
Yichi Chenda901bf2019-06-28 14:58:27 +0800299 mColorSpaceAgnosticDataspace =
300 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800303
Dominik Laskowski718f9602019-11-09 20:01:35 -0800304 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
305 switch (primary_display_orientation(Values::ORIENTATION_0)) {
306 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800308 case Values::ORIENTATION_90:
309 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 case Values::ORIENTATION_180:
312 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800314 case Values::ORIENTATION_270:
315 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
317 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahn85131bd2019-02-18 15:51:53 +0900320 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // debugging stuff...
323 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700324
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700326 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327
Alec Mouri5f487d42020-02-06 09:26:19 -0800328 property_get("ro.build.type", value, "user");
329 mIsUserBuild = strcmp(value, "user") == 0;
330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 property_get("debug.sf.showupdates", value, "0");
332 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700333
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700334 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000335
336 // DDMS debugging deprecated (b/120782499)
337 property_get("debug.sf.ddms", value, "0");
338 int debugDdms = atoi(value);
339 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700340
341 property_get("debug.sf.disable_backpressure", value, "0");
342 mPropagateBackpressure = !atoi(value);
343 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700344
Ady Abrahamadb9a992019-09-19 21:21:55 +0000345 property_get("debug.sf.enable_gl_backpressure", value, "0");
346 mPropagateBackpressureClientComposition = atoi(value);
347 ALOGI_IF(mPropagateBackpressureClientComposition,
348 "Enabling backpressure propagation for Client Composition");
349
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800350 property_get("debug.sf.enable_hwc_vds", value, "0");
351 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800352 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800354 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800355 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800356 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700357
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800358 property_get("ro.surface_flinger.supports_background_blur", value, "0");
359 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800360 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800361 bool disableBlurs = atoi(value);
362 mEnableBlurs = supportsBlurs && !disableBlurs;
363 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
364 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800365 property_get("ro.sf.blurs_are_expensive", value, "0");
366 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800367
Yiwei Zhang243b3782018-05-15 17:40:04 -0700368 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700369 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
370 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
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 Lin4137a1d2019-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 Lin4137a1d2019-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();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001490 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001491}
1492
1493void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001494 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001495 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496}
1497
1498void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001499 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001500 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001501}
1502
1503status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001504 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001505 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001506}
1507
1508status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001509 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001510 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511 if (res == NO_ERROR) {
1512 msg->wait();
1513 }
1514 return res;
1515}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001516
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001517void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001518 do {
1519 waitForEvent();
1520 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521}
1522
Dominik Laskowski83b88212018-12-11 13:34:06 -08001523nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001524 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001525 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1526 return 0;
1527 }
1528
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001529 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001530}
1531
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001532void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001533 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001534 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001535 ATRACE_NAME("SF onVsync");
1536
Steven Thomas3cfac282017-02-06 12:29:30 -08001537 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001538 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001539 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001540 return;
1541 }
1542
Dominik Laskowski075d3172018-05-24 15:50:06 -07001543 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001544 return;
1545 }
1546
Dominik Laskowski075d3172018-05-24 15:50:06 -07001547 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001548 // For now, we don't do anything with external display vsyncs.
1549 return;
1550 }
1551
Alec Mourif8e689c2019-05-20 18:32:22 -07001552 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001553 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001554 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001555 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001556 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001557}
1558
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001560 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1561 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562}
1563
Ady Abraham2139f732019-11-13 18:56:40 -08001564bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001565 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001566}
1567
Ady Abraham2139f732019-11-13 18:56:40 -08001568void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1569 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001570 const auto display = getDefaultDisplayDeviceLocked();
1571 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001572 return;
1573 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001574 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001575
Ana Krulec7d1d6832018-12-27 11:10:09 -08001576 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001577 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1578 ALOGV("Skipping config %d as it is not part of allowed configs",
1579 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001580 return;
1581 }
1582
Ady Abraham2139f732019-11-13 18:56:40 -08001583 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001584}
1585
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001586void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001587 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001588 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001589 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590
Lloyd Piqueba04e622017-12-14 17:11:26 -08001591 // Ignore events that do not have the right sequenceId.
1592 if (sequenceId != getBE().mComposerSequenceId) {
1593 return;
1594 }
1595
Steven Thomasb02664d2017-07-26 18:48:28 -07001596 // Only lock if we're not on the main thread. This function is normally
1597 // called on a hwbinder thread, but for the primary display it's called on
1598 // the main thread with the state lock already held, so don't attempt to
1599 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001600 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001601
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001602 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001603
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001604 if (std::this_thread::get_id() == mMainThreadId) {
1605 // Process all pending hot plug events immediately if we are on the main thread.
1606 processDisplayHotplugEventsLocked();
1607 }
1608
Lloyd Piqueba04e622017-12-14 17:11:26 -08001609 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001610}
1611
Ady Abraham7159f572019-10-11 11:10:18 -07001612void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001613 int32_t sequenceId, hwc2_display_t /*display*/,
1614 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1615 Mutex::Autolock lock(mStateLock);
1616 if (sequenceId != getBE().mComposerSequenceId) {
1617 return;
1618 }
1619 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001620}
1621
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001622void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1623 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1624 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1625}
1626
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001627void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001628 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001629 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001630 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001631 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001632 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001633}
1634
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001635void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001636 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001637
1638 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1639 // display power state.
1640 postMessageAsync(new LambdaMessage(
1641 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1642}
1643
1644void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1645 ATRACE_CALL();
1646
Ady Abraham27c70212019-06-11 10:52:26 -07001647 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1648
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001649 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001650 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1651 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001652 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001653 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001654 }
Mathias Agopian86303202012-07-24 22:46:10 -07001655}
1656
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001657// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001658void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001659 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001660 // Clear the drawing state so that the logic inside of
1661 // handleTransactionLocked will fire. It will determine the delta between
1662 // mCurrentState and mDrawingState and re-apply all changes when we make the
1663 // transition.
1664 mDrawingState.displays.clear();
1665 mDisplays.clear();
1666}
1667
Steven Thomas050b2c82017-03-06 11:45:16 -08001668void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001669 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001670 if (!mVrFlinger)
1671 return;
1672 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001673 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001674 return;
1675 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676
Lloyd Pique441d5042018-10-18 16:49:51 -07001677 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001678 ALOGE("Vr flinger is only supported for remote hardware composer"
1679 " service connections. Ignoring request to transition to vr"
1680 " flinger.");
1681 mVrFlingerRequestsDisplay = false;
1682 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001683 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001684
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001686
Steven Thomas0123ac62018-07-12 11:32:34 -07001687 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001688 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001689
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001690 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001691
1692 // Clear out all the output layers from the composition engine for all
1693 // displays before destroying the hardware composer interface. This ensures
1694 // any HWC layers are destroyed through that interface before it becomes
1695 // invalid.
1696 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001697 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001698 }
1699
Steven Thomas0123ac62018-07-12 11:32:34 -07001700 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1701 // called below. Clear the reference now so we don't accidentally use it
1702 // later.
1703 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001704
Steven Thomasb02664d2017-07-26 18:48:28 -07001705 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001706 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001707 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001708
Steven Thomasb02664d2017-07-26 18:48:28 -07001709 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001710 // Delete the current instance before creating the new one
1711 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1712 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1713 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001714 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001715
Lloyd Pique441d5042018-10-18 16:49:51 -07001716 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001717 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001718
1719 if (vrFlingerRequestsDisplay) {
1720 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001721 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001722
1723 mVisibleRegionsDirty = true;
1724 invalidateHwcGeometry();
1725
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001726 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001727 display = getDefaultDisplayDeviceLocked();
1728 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001729 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001730
Steven Thomasb02664d2017-07-26 18:48:28 -07001731 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001732 const nsecs_t vsyncPeriod = getVsyncPeriod();
1733 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001734
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001735 // The present fences returned from vr_hwc are not an accurate
1736 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001737 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001738
Steven Thomasb02664d2017-07-26 18:48:28 -07001739 // Use phase of 0 since phase is not known.
1740 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001741 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001742 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001743
Ana Krulecc2870422019-01-29 19:00:58 -08001744 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001745
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001746 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001747 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001748}
1749
Ady Abraham11579302019-09-19 12:35:58 -07001750bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1751 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001752 // We are storing the last 2 present fences. If sf's phase offset is to be
1753 // woken up before the actual vsync but targeting the next vsync, we need to check
1754 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001755 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1756 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001757
Ady Abraham11579302019-09-19 12:35:58 -07001758 if (fence == Fence::NO_FENCE) {
1759 return false;
1760 }
1761
1762 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1763 fence->wait(graceTimeMs);
1764 }
1765
1766 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001767}
1768
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001769void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001770 DisplayStatInfo stats;
1771 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001772 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001773 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001774 mExpectedPresentTime.store(
1775 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001776}
1777
Dominik Laskowski22488f62019-03-28 09:53:04 -07001778void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001779 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001780 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001781 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001782 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001783 // calculate the expected present time once and use the cached
1784 // value throughout this frame to make sure all layers are
1785 // seeing this same value.
1786 populateExpectedPresentTime();
1787
Ady Abraham11579302019-09-19 12:35:58 -07001788 // When Backpressure propagation is enabled we want to give a small grace period
1789 // for the present fence to fire instead of just giving up on this frame to handle cases
1790 // where present fence is just about to get signaled.
1791 const int graceTimeForPresentFenceMs =
1792 (mPropagateBackpressure &&
1793 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1794 ? 1
1795 : 0;
1796 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1797 previousFrameMissed(
1798 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001799 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1800 mHadDeviceComposition && frameMissed};
1801 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1802 mHadClientComposition && frameMissed};
1803
Alec Mouricc0fc602019-02-26 21:45:19 -08001804 if (frameMissed) {
1805 mFrameMissedCount++;
1806 mTimeStats->incrementMissedFrames();
Alec Mouri5f487d42020-02-06 09:26:19 -08001807 if (mMissedFrameJankCount == 0) {
1808 mMissedFrameJankStart = systemTime();
1809 }
1810 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001811 }
1812
Alec Mouri40189b02019-03-05 15:07:54 -08001813 if (hwcFrameMissed) {
1814 mHwcFrameMissedCount++;
1815 }
1816
1817 if (gpuFrameMissed) {
1818 mGpuFrameMissedCount++;
1819 }
1820
Ady Abrahamadb9a992019-09-19 21:21:55 +00001821 if (frameMissed && mPropagateBackpressure) {
1822 if ((hwcFrameMissed && !gpuFrameMissed) ||
1823 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001824 signalLayerUpdate();
1825 break;
1826 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001827 }
Dan Stoza50182882016-07-08 12:02:20 -07001828
Alec Mouri5f487d42020-02-06 09:26:19 -08001829 // Our jank window is always at least 100ms since we missed a
1830 // frame...
1831 static constexpr nsecs_t kMinJankyDuration =
1832 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1833 // ...but if it's larger than 1s then we missed the trace cutoff.
1834 static constexpr nsecs_t kMaxJankyDuration =
1835 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1836 // If we're in a user build then don't push any atoms
1837 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1838 const auto displayDevice = getDefaultDisplayDeviceLocked();
1839 // Only report jank when the display is on, as displays in DOZE
1840 // power mode may operate at a different frame rate than is
1841 // reported in their config, which causes noticeable (but less
1842 // severe) jank.
1843 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1844 const nsecs_t currentTime = systemTime();
1845 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1846 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1847 ATRACE_NAME("Jank detected");
1848 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1849 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1850 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1851 jankyDurationMillis, mMissedFrameJankCount);
1852 }
1853
1854 // We either reported a jank event or we missed the trace
1855 // window, so clear counters here.
1856 if (jankDuration > kMinJankyDuration) {
1857 mMissedFrameJankCount = 0;
1858 mMissedFrameJankStart = 0;
1859 }
1860 }
1861 }
1862
Steven Thomas050b2c82017-03-06 11:45:16 -08001863 // Now that we're going to make it to the handleMessageTransaction()
1864 // call below it's safe to call updateVrFlinger(), which will
1865 // potentially trigger a display handoff.
1866 updateVrFlinger();
1867
Dan Stoza6b9454d2014-11-07 16:00:59 -08001868 bool refreshNeeded = handleMessageTransaction();
1869 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001870
Ana Krulecc84d09b2019-11-02 23:10:29 +01001871 // Layers need to get updated (in the previous line) before we can use them for
1872 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001873 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1874 // and may eventually call to ~Layer() if it holds the last reference
1875 {
1876 Mutex::Autolock _l(mStateLock);
1877 mScheduler->chooseRefreshRateForContent();
1878 }
1879
Ana Krulecc84d09b2019-11-02 23:10:29 +01001880 if (performSetActiveConfig()) {
1881 break;
1882 }
1883
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001884 updateCursorAsync();
1885 updateInputFlinger();
1886
Dan Stoza58784442014-12-02 16:58:17 -08001887 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001888 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001889 // Signal a refresh if a transaction modified the window state,
1890 // a new buffer was latched, or if HWC has requested a full
1891 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001892 if (mFrameStartTime <= 0) {
1893 // We should only use the time of the first invalidate
1894 // message that signals a refresh as the beginning of the
1895 // frame. Otherwise the real frame time will be
1896 // underestimated.
1897 mFrameStartTime = frameStart;
1898 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001899 signalRefresh();
1900 }
1901 break;
1902 }
1903 case MessageQueue::REFRESH: {
1904 handleMessageRefresh();
1905 break;
1906 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001907 }
1908}
1909
Dan Stoza6b9454d2014-11-07 16:00:59 -08001910bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001911 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001912 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001913
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001914 bool flushedATransaction = flushTransactionQueues();
1915
1916 bool runHandleTransaction = transactionFlags &&
1917 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1918
1919 if (runHandleTransaction) {
1920 handleTransaction(eTransactionMask);
1921 } else {
1922 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001923 }
1924
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001925 if (transactionFlushNeeded()) {
1926 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001927 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001928
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001929 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001930}
1931
Mathias Agopian4fec8732012-06-29 14:12:52 -07001932void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001933 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001934
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001935 mRefreshPending = false;
1936
Lloyd Piqueab039b52019-02-13 14:22:42 -08001937 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001938 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001939 for (const auto& [_, display] : mDisplays) {
1940 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1941 }
1942 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001943 if (auto layerFE = layer->getCompositionEngineLayerFE())
1944 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001945 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001946 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1947 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001948 if (auto layerFE = layer->getCompositionEngineLayerFE())
1949 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001950 }
1951
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001952 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001953 refreshArgs.outputColorSetting = useColorManagement
1954 ? mDisplayColorSetting
1955 : compositionengine::OutputColorSetting::kUnmanaged;
1956 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1957 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001958
1959 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1960 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001961 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001962
1963 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1964 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1965 mDrawingState.colorMatrixChanged = false;
1966 }
1967
1968 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1969
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001970 if (mDebugRegion != 0) {
1971 refreshArgs.devOptFlashDirtyRegionsDelay =
1972 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1973 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001974
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001975 mGeometryInvalid = false;
1976
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001977 // Store the present time just before calling to the composition engine so we could notify
1978 // the scheduler.
1979 const auto presentTime = systemTime();
1980
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001981 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001982 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1983 // Reset the frame start time now that we've recorded this frame.
1984 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001985
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001986 mScheduler->onDisplayRefreshed(presentTime);
1987
David Sodmanfa9b2af2017-12-24 13:28:59 -08001988 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001989 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001990
Lloyd Pique66d68602019-02-13 14:23:31 -08001991 mHadClientComposition =
1992 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1993 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001994 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1995 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001996 });
1997 mHadDeviceComposition =
1998 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1999 auto& displayDevice = tokenDisplayPair.second;
2000 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2001 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002002 mReusedClientComposition =
2003 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2004 auto& displayDevice = tokenDisplayPair.second;
2005 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2006 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002007
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002008 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002009
David Sodman7e4ae112018-02-09 15:02:28 -08002010 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002011 if (mVisibleRegionsDirty) {
2012 mVisibleRegionsDirty = false;
2013 if (mTracingEnabled) {
2014 mTracing.notify("visibleRegionsDirty");
2015 }
2016 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002017
2018 if (mCompositionEngine->needsAnotherUpdate()) {
2019 signalLayerUpdate();
2020 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002021}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002022
David Sodmanfa9b2af2017-12-24 13:28:59 -08002023
2024bool SurfaceFlinger::handleMessageInvalidate() {
2025 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002026 bool refreshNeeded = handlePageFlip();
2027
Vishnu Nair4351ad52019-02-11 14:13:02 -08002028 if (mVisibleRegionsDirty) {
2029 computeLayerBounds();
2030 }
2031
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002032 for (auto& layer : mLayersPendingRefresh) {
2033 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002034 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002035 invalidateLayerStack(layer, visibleReg);
2036 }
2037 mLayersPendingRefresh.clear();
2038 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002039}
2040
Ana Krulece588e312018-09-18 12:32:24 -07002041void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2042 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043 // Update queue of past composite+present times and determine the
2044 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002045 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002046 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002047 while (!getBE().mCompositePresentTimes.empty()) {
2048 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 // Cached values should have been updated before calling this method,
2050 // which helps avoid duplicate syscalls.
2051 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2052 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2053 break;
2054 }
2055 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002056 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002057 }
2058
2059 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002060 while (getBE().mCompositePresentTimes.size() > 16) {
2061 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 }
2063
Ana Krulece588e312018-09-18 12:32:24 -07002064 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002065}
2066
Ana Krulece588e312018-09-18 12:32:24 -07002067void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2068 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069 // Integer division and modulo round toward 0 not -inf, so we need to
2070 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002071 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2072 ? (stats.vsyncPeriod -
2073 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2074 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
Ady Abraham9e16a482019-12-03 17:19:41 -08002076 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002077 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002078 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002079 }
2080
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081 // Snap the latency to a value that removes scheduling jitter from the
2082 // composition and present times, which often have >1ms of jitter.
2083 // Reducing jitter is important if an app attempts to extrapolate
2084 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002085 // Snapping also allows an app to precisely calculate
2086 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002087 nsecs_t bias = stats.vsyncPeriod / 2;
2088 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2089 nsecs_t snappedCompositeToPresentLatency =
2090 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002091
David Sodman99974d22017-11-28 12:04:33 -08002092 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002093 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2094 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002095 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002096}
2097
David Sodman2b406362017-12-15 13:33:47 -08002098void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002099{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 ATRACE_CALL();
2101 ALOGV("postComposition");
2102
Brian Andersonf6386862016-10-31 16:34:13 -07002103 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002104 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002105 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002106 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002107 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002108 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002109
David Sodman73beded2017-11-15 11:56:06 -08002110 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002111 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002112 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002114 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2115 ->getRenderSurface()
2116 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002117 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118 } else {
2119 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2120 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002121
David Sodman73beded2017-11-15 11:56:06 -08002122 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002123 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2124 mPreviousPresentFences[0] = displayDevice
2125 ? getHwComposer().getPresentFence(*displayDevice->getId())
2126 : Fence::NO_FENCE;
2127 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002128 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002129
Ana Krulece588e312018-09-18 12:32:24 -07002130 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002131 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002132
Lloyd Piqueab039b52019-02-13 14:22:42 -08002133 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2134 // be sampled a little later than when we started doing work for this frame,
2135 // but that should be okay since updateCompositorTiming has snapping logic.
2136 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2137 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002138 CompositorTiming compositorTiming;
2139 {
David Sodman99974d22017-11-28 12:04:33 -08002140 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2141 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002142 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002143
Edgar Arriaga844fa672020-01-16 14:21:42 -08002144 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002145 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2146 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002147 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002148 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002149 }
Robert Carr2047fae2016-11-28 14:09:09 -08002150 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002151
Ady Abraham92fa2f42020-02-11 15:33:56 -08002152 if (displayDevice && displayDevice->isPrimary() &&
2153 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002154 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002155 }
2156
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002157 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002158 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2159 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002160 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002161 }
2162 }
2163
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002164 if (mAnimCompositionPending) {
2165 mAnimCompositionPending = false;
2166
Brian Anderson4e606e32017-03-16 15:34:57 -07002167 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002168 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002169 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002170 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002171 // The HWC doesn't support present fences, so use the refresh
2172 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002173 const nsecs_t presentTime =
2174 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002175 mAnimFrameTracker.setActualPresentTime(presentTime);
2176 }
2177 mAnimFrameTracker.advanceFrame();
2178 }
Dan Stozab90cf072015-03-05 11:05:59 -08002179
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002180 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002181 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002182 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002183 }
2184
Vishnu Nair9b079a22020-01-21 14:36:08 -08002185 if (mReusedClientComposition) {
2186 mTimeStats->incrementClientCompositionReusedFrames();
2187 }
2188
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002189 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002190
Alec Mouri717bcb62020-02-10 17:07:19 -08002191 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2192 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2193 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2194
Lloyd Pique32cbe282018-10-19 13:09:22 -07002195 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2196 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002197 return;
2198 }
2199
2200 nsecs_t currentTime = systemTime();
2201 if (mHasPoweredOff) {
2202 mHasPoweredOff = false;
2203 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002204 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002205 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002206 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2207 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002208 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002209 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002210 }
David Sodman4a36e932017-11-07 14:29:47 -08002211 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002212 }
David Sodman4a36e932017-11-07 14:29:47 -08002213 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002214
2215 {
2216 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002217 if (mTexturePool.size() < mTexturePoolSize) {
2218 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002219 const size_t offset = mTexturePool.size();
2220 mTexturePool.resize(mTexturePoolSize);
2221 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2222 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002223 } else if (mTexturePool.size() > mTexturePoolSize) {
2224 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2225 const size_t offset = mTexturePoolSize;
2226 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2227 mTexturePool.resize(mTexturePoolSize);
2228 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002229 }
2230 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002231
Ady Abrahambe0f9482019-04-24 15:41:53 -07002232 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002233 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002234
Kevin DuBois413287f2019-02-25 08:46:47 -08002235 if (mLumaSampling && mRegionSamplingThread) {
2236 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002237 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002238
2239 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2240 // side-effect of getTotalSize(), so we check that again here
2241 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002242 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002243 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2244 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002245}
2246
Vishnu Nair4351ad52019-02-11 14:13:02 -08002247void SurfaceFlinger::computeLayerBounds() {
2248 for (const auto& pair : mDisplays) {
2249 const auto& displayDevice = pair.second;
2250 const auto display = displayDevice->getCompositionDisplay();
2251 for (const auto& layer : mDrawingState.layersSortedByZ) {
2252 // only consider the layers on the given layer stack
2253 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002254 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002255 }
2256
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002257 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2258 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002259 }
2260 }
2261}
2262
David Sodmanfa9b2af2017-12-24 13:28:59 -08002263void SurfaceFlinger::postFrame()
2264{
2265 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002266 const auto display = getDefaultDisplayDeviceLocked();
2267 if (display && getHwComposer().isConnected(*display->getId())) {
2268 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002269 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2270 logFrameStats();
2271 }
2272 }
2273}
2274
Mathias Agopian87baae12012-07-31 12:38:26 -07002275void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276{
Mathias Agopian841cde52012-03-01 15:44:37 -08002277 ATRACE_CALL();
2278
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002279 // here we keep a copy of the drawing state (that is the state that's
2280 // going to be overwritten by handleTransactionLocked()) outside of
2281 // mStateLock so that the side-effects of the State assignment
2282 // don't happen with mStateLock held (which can cause deadlocks).
2283 State drawingState(mDrawingState);
2284
Mathias Agopianca4d3602011-05-19 15:38:14 -07002285 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002286 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287
Mathias Agopianca4d3602011-05-19 15:38:14 -07002288 // Here we're guaranteed that some transaction flags are set
2289 // so we can call handleTransactionLocked() unconditionally.
2290 // We call getTransactionFlags(), which will also clear the flags,
2291 // with mStateLock held to guarantee that mCurrentState won't change
2292 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002293
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002294 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002295 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002296 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002297
Mathias Agopianca4d3602011-05-19 15:38:14 -07002298 mDebugInTransaction = 0;
2299 invalidateHwcGeometry();
2300 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002301}
2302
Lloyd Piqueba04e622017-12-14 17:11:26 -08002303void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2304 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 const std::optional<DisplayIdentificationInfo> info =
2306 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002307
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002309 continue;
2310 }
2311
Dominik Laskowski55c85402020-01-21 16:25:47 -08002312 const DisplayId displayId = info->id;
2313 const auto it = mPhysicalDisplayTokens.find(displayId);
2314
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002316 if (it == mPhysicalDisplayTokens.end()) {
2317 ALOGV("Creating display %s", to_string(displayId).c_str());
2318
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002319 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002320 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002321 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002322
Dominik Laskowski075d3172018-05-24 15:50:06 -07002323 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002324 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 state.isSecure = true; // All physical displays are currently considered secure.
2326 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002327
2328 sp<IBinder> token = new BBinder();
2329 mCurrentState.displays.add(token, state);
2330 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2331
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002333 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002334 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002335 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002336
Dominik Laskowski55c85402020-01-21 16:25:47 -08002337 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 if (index >= 0) {
2339 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2340 mInterceptor->saveDisplayDeletion(state.sequenceId);
2341 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002342 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002343 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002344 }
2345
2346 processDisplayChangesLocked();
2347 }
2348
2349 mPendingHotplugEvents.clear();
2350}
2351
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002352void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002353 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2354 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002355}
2356
Lloyd Pique99d3da52018-01-22 17:48:03 -08002357sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002359 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002360 const sp<IGraphicBufferProducer>& producer) {
2361 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002362 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002363 creationArgs.isSecure = state.isSecure;
2364 creationArgs.displaySurface = dispSurface;
2365 creationArgs.hasWideColorGamut = false;
2366 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002367 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002368
Dominik Laskowski55c85402020-01-21 16:25:47 -08002369 if (const auto& physical = state.physical) {
2370 creationArgs.connectionType = physical->type;
2371 }
2372
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002373 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002374 creationArgs.isPrimary = isInternalDisplay;
2375
2376 if (useColorManagement && displayId) {
2377 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002379 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002380 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002382
Dominik Laskowski7e045462018-05-30 13:02:02 -07002383 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002384 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002386 }
tangrobin6753a022018-08-10 10:58:54 +08002387 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002388
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 if (displayId) {
2390 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002391 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002393 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394
Lloyd Pique90c115d2018-09-18 21:39:42 -07002395 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002397 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399 // Make sure that composition can never be stalled by a virtual display
2400 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002401 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002402 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2404 }
2405
Dominik Laskowski718f9602019-11-09 20:01:35 -08002406 creationArgs.physicalOrientation =
2407 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002408
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002410 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411
Lloyd Pique90c115d2018-09-18 21:39:42 -07002412 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413
2414 if (maxFrameBufferAcquiredBuffers >= 3) {
2415 nativeWindowSurface->preallocateBuffers();
2416 }
2417
2418 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002419 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002420 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002421 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002422 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002423 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002424 display->getCompositionDisplay()->setColorProfile(
2425 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2426 RenderIntent::COLORIMETRIC,
2427 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 if (!state.isVirtual()) {
2429 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002430 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2431 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002432 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002434 display->setLayerStack(state.layerStack);
2435 display->setProjection(state.orientation, state.viewport, state.frame);
2436 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439}
2440
Lloyd Pique347200f2017-12-14 17:00:15 -08002441void SurfaceFlinger::processDisplayChangesLocked() {
2442 // here we take advantage of Vector's copy-on-write semantics to
2443 // improve performance by skipping the transaction entirely when
2444 // know that the lists are identical
2445 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2446 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2447 if (!curr.isIdenticalTo(draw)) {
2448 mVisibleRegionsDirty = true;
2449 const size_t cc = curr.size();
2450 size_t dc = draw.size();
2451
2452 // find the displays that were removed
2453 // (ie: in drawing state but not in current state)
2454 // also handle displays that changed
2455 // (ie: displays that are in both lists)
2456 for (size_t i = 0; i < dc;) {
2457 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2458 if (j < 0) {
2459 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002460 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002461 // Save display ID before disconnecting.
2462 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002463 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002464
2465 if (!display->isVirtual()) {
2466 LOG_ALWAYS_FATAL_IF(!displayId);
2467 dispatchDisplayHotplugEvent(displayId->value, false);
2468 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002469 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002470
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002471 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002472 } else {
2473 // this display is in both lists. see if something changed.
2474 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002476 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2477 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2478 if (state_binder != draw_binder) {
2479 // changing the surface is like destroying and
2480 // recreating the DisplayDevice, so we just remove it
2481 // from the drawing state, so that it get re-added
2482 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002484 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002486 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 mDrawingState.displays.removeItemsAt(i);
2488 dc--;
2489 // at this point we must loop to the next item
2490 continue;
2491 }
2492
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002493 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002494 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 }
2497 if ((state.orientation != draw[i].orientation) ||
2498 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 }
2501 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002503 if (display->isPrimary()) {
2504 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2505 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 }
2507 }
2508 }
2509 ++i;
2510 }
2511
2512 // find displays that were added
2513 // (ie: in current state but not in drawing state)
2514 for (size_t i = 0; i < cc; i++) {
2515 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2516 const DisplayDeviceState& state(curr[i]);
2517
Lloyd Pique542307f2018-10-19 13:24:08 -07002518 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002519 sp<IGraphicBufferProducer> producer;
2520 sp<IGraphicBufferProducer> bqProducer;
2521 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002522 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002523
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002525 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002526 // Virtual displays without a surface are dormant:
2527 // they have external state (layer stack, projection,
2528 // etc.) but no internal state (i.e. a DisplayDevice).
2529 if (state.surface != nullptr) {
2530 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002532 int width = 0;
2533 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2534 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2535 int height = 0;
2536 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2537 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2538 int intFormat = 0;
2539 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2540 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002541 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002542
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 displayId =
2544 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002545 }
2546
2547 // TODO: Plumb requested format back up to consumer
2548
2549 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002551 bqProducer, bqConsumer,
2552 state.displayName);
2553
2554 dispSurface = vds;
2555 producer = vds;
2556 }
2557 } else {
2558 ALOGE_IF(state.surface != nullptr,
2559 "adding a supported display, but rendering "
2560 "surface is provided (%p), ignoring it",
2561 state.surface.get());
2562
Dominik Laskowski55c85402020-01-21 16:25:47 -08002563 LOG_FATAL_IF(!state.physical);
2564 displayId = state.physical->id;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002566 producer = bqProducer;
2567 }
2568
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002569 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002570 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002571 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002572 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002573 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002574 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002576 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002577 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002578
2579 const auto displayDevice = mDisplays[displayToken];
2580 if (displayDevice->isPrimary()) {
2581 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2582 displayDevice->getHeight());
2583 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002584 }
2585 }
2586 }
2587 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588
2589 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002590}
2591
Mathias Agopian87baae12012-07-31 12:38:26 -07002592void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002593{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002594 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2595
Dan Stoza7dde5992015-05-22 09:51:44 -07002596 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002597 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002598 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002599 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002600
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 /*
2602 * Traversal of the children
2603 * (perform the transaction for each of them if needed)
2604 */
2605
Marissa Wall06255332019-03-27 13:48:27 -07002606 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002607 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002609 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002610
2611 const uint32_t flags = layer->doTransaction(0);
2612 if (flags & Layer::eVisibleRegion)
2613 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002614
2615 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002616 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002617 }
Robert Carr2047fae2016-11-28 14:09:09 -08002618 });
Marissa Wall06255332019-03-27 13:48:27 -07002619 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 }
2621
2622 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002623 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624 */
2625
Mathias Agopiane57f2922012-08-09 16:29:12 -07002626 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002627 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002628 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002629 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002631 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002632 // The transform hint might have changed for some layers
2633 // (either because a display has changed, or because a layer
2634 // as changed).
2635 //
2636 // Walk through all the layers in currentLayers,
2637 // and update their transform hint.
2638 //
2639 // If a layer is visible only on a single display, then that
2640 // display is used to calculate the hint, otherwise we use the
2641 // default display.
2642 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002643 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002644 // the hint is set before we acquire a buffer from the surface texture.
2645 //
2646 // NOTE: layer transactions have taken place already, so we use their
2647 // drawing state. However, SurfaceFlinger's own transaction has not
2648 // happened yet, so we must use the current state layer list
2649 // (soon to become the drawing state list).
2650 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002651 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002652 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002653 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002654 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002655 // NOTE: we rely on the fact that layers are sorted by
2656 // layerStack first (so we don't have to traverse the list
2657 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002658 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002659 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002660 currentlayerStack = layerStack;
2661 // figure out if this layerstack is mirrored
2662 // (more than one display) if so, pick the default display,
2663 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 hintDisplay = nullptr;
2665 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002666 if (display->getCompositionDisplay()
2667 ->belongsInOutput(layer->getLayerStack(),
2668 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002669 if (hintDisplay) {
2670 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002671 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002673 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002674 }
2675 }
2676 }
2677 }
Chet Haase91d25932013-04-11 15:24:55 -07002678
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002679 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002680 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2681 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002682
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002683 // could be null when this layer is using a layerStack
2684 // that is not visible on any display. Also can occur at
2685 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002686 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002687 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002688
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002689 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002690 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 if (hintDisplay) {
2692 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002693 }
Robert Carr2047fae2016-11-28 14:09:09 -08002694
2695 first = false;
2696 });
Mathias Agopian84300952012-11-21 16:02:13 -08002697 }
2698
2699
Mathias Agopian3559b072012-08-15 13:46:03 -07002700 /*
2701 * Perform our own transaction if needed
2702 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703
2704 if (mLayersAdded) {
2705 mLayersAdded = false;
2706 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002707 mVisibleRegionsDirty = true;
2708 }
2709
2710 // some layers might have been removed, so
2711 // we need to update the regions they're exposing.
2712 if (mLayersRemoved) {
2713 mLayersRemoved = false;
2714 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002715 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002716 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002717 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002719 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002720 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002721 }
Robert Carr2047fae2016-11-28 14:09:09 -08002722 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723 }
2724
Vishnu Nairec0ab382019-02-13 15:32:56 -08002725 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002727}
2728
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002729void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002730 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002731 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002732 return;
2733 }
2734
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002735 if (mVisibleRegionsDirty || mInputInfoChanged) {
2736 mInputInfoChanged = false;
2737 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002738 } else if (mInputWindowCommands.syncInputWindows) {
2739 // If the caller requested to sync input windows, but there are no
2740 // changes to input windows, notify immediately.
2741 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002742 }
2743
Arthur Hung6cbb9752019-09-05 16:38:18 +08002744 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002745}
2746
2747void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002748 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002749
2750 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2751 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002752 // When calculating the screen bounds we ignore the transparent region since it may
2753 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002754 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002755 }
2756 });
chaviw291d88a2019-02-14 10:33:58 -08002757
2758 mInputFlinger->setInputWindows(inputHandles,
2759 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2760 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002761}
2762
Vishnu Nairec0ab382019-02-13 15:32:56 -08002763void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002764 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002765 mPendingInputWindowCommands.clear();
2766}
2767
Riley Andrews03414a12014-07-01 14:22:59 -07002768void SurfaceFlinger::updateCursorAsync()
2769{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002770 compositionengine::CompositionRefreshArgs refreshArgs;
2771 for (const auto& [_, display] : mDisplays) {
2772 if (display->getId()) {
2773 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002774 }
2775 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002776
2777 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002778}
2779
Ady Abraham2139f732019-11-13 18:56:40 -08002780void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002781 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2782 // If this is called from the main thread mStateLock must be locked before
2783 // Currently the only way to call this function from the main thread is from
2784 // Sheduler::chooseRefreshRateForContent
2785
2786 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002787 changeRefreshRateLocked(refreshRate, event);
2788}
2789
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002790void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2791 if (mScheduler) {
2792 // In practice it's not allowed to hotplug in/out the primary display once it's been
2793 // connected during startup, but some tests do it, so just warn and return.
2794 ALOGW("Can't re-init scheduler");
2795 return;
2796 }
2797
Ady Abraham2139f732019-11-13 18:56:40 -08002798 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002799 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002800 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002801 primaryDisplayId),
2802 currentConfig);
2803 mRefreshRateStats =
2804 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2805 currentConfig, HWC_POWER_MODE_OFF);
2806 mRefreshRateStats->setConfigMode(currentConfig);
2807
Ady Abraham9e16a482019-12-03 17:19:41 -08002808 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2809
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002810 // start the EventThread
2811 mScheduler =
2812 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002813 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002814 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002815 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002816 impl::EventThread::InterceptVSyncsCallback());
2817 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002818 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002819 [this](nsecs_t timestamp) {
2820 mInterceptor->saveVSyncEvent(timestamp);
2821 });
2822
2823 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2824 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002825 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002826
2827 mRegionSamplingThread =
2828 new RegionSamplingThread(*this, *mScheduler,
2829 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002830 // Dispatch a config change request for the primary display on scheduler
2831 // initialization, so that the EventThreads always contain a reference to a
2832 // prior configuration.
2833 //
2834 // This is a bit hacky, but this avoids a back-pointer into the main SF
2835 // classes from EventThread, and there should be no run-time binder cost
2836 // anyway since there are no connected apps at this point.
2837 const nsecs_t vsyncPeriod =
2838 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2839 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2840 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002841}
2842
Mathias Agopian4fec8732012-06-29 14:12:52 -07002843void SurfaceFlinger::commitTransaction()
2844{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002845 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002846
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002847 mTransactionPending = false;
2848 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002849 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850}
2851
Lloyd Pique58e24a32019-08-01 15:50:14 -07002852void SurfaceFlinger::commitTransactionLocked() {
2853 if (!mLayersPendingRemoval.isEmpty()) {
2854 // Notify removed layers now that they can't be drawn from
2855 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002856 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002857
2858 // Ensure any buffers set to display on any children are released.
2859 if (l->isRemovedFromCurrentState()) {
2860 l->latchAndReleaseBuffer();
2861 }
2862
2863 // If the layer has been removed and has no parent, then it will not be reachable
2864 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2865 // ensure we can copy its current to drawing state.
2866 if (!l->getParent()) {
2867 mOffscreenLayers.emplace(l.get());
2868 }
2869 }
2870 mLayersPendingRemoval.clear();
2871 }
2872
2873 // If this transaction is part of a window animation then the next frame
2874 // we composite should be considered an animation as well.
2875 mAnimCompositionPending = mAnimTransactionPending;
2876
2877 mDrawingState = mCurrentState;
2878 // clear the "changed" flags in current state
2879 mCurrentState.colorMatrixChanged = false;
2880
Edgar Arriaga844fa672020-01-16 14:21:42 -08002881 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002882 layer->commitChildList();
2883
2884 // If the layer can be reached when traversing mDrawingState, then the layer is no
2885 // longer offscreen. Remove the layer from the offscreenLayer set.
2886 if (mOffscreenLayers.count(layer)) {
2887 mOffscreenLayers.erase(layer);
2888 }
2889 });
2890
2891 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002892 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002893}
2894
Nataniel Borges2b796da2019-02-15 13:32:18 -08002895void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2896 if (mTracingEnabledChanged) {
2897 mTracingEnabled = mTracing.isEnabled();
2898 mTracingEnabledChanged = false;
2899 }
2900
2901 // Synchronize with Tracing thread
2902 std::unique_lock<std::mutex> lock;
2903 if (mTracingEnabled) {
2904 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2905 }
2906
2907 lockedOperation();
2908
2909 // Synchronize with Tracing thread
2910 if (mTracingEnabled) {
2911 lock.unlock();
2912 }
2913}
2914
chaviw74d90ad2019-04-26 14:45:26 -07002915void SurfaceFlinger::commitOffscreenLayers() {
2916 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002917 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002918 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2919 if (!trFlags) return;
2920
2921 layer->doTransaction(0);
2922 layer->commitChildList();
2923 });
2924 }
2925}
2926
Chia-I Wuab0c3192017-08-01 11:29:00 -07002927void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002928 for (const auto& [token, displayDevice] : mDisplays) {
2929 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002930 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002931 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002932 }
2933 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002934}
2935
Dan Stoza6b9454d2014-11-07 16:00:59 -08002936bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937{
Ady Abraham09bd3922019-04-08 10:44:56 -07002938 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 ALOGV("handlePageFlip");
2940
Brian Andersond6927fb2016-07-23 23:37:30 -07002941 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942
Mathias Agopian4fec8732012-06-29 14:12:52 -07002943 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002944 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002945 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002946
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002947 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2948
Eric Penner51c59cd2014-07-28 19:51:58 -07002949 // Store the set of layers that need updates. This set must not change as
2950 // buffers are being latched, as this could result in a deadlock.
2951 // Example: Two producers share the same command stream and:
2952 // 1.) Layer 0 is latched
2953 // 2.) Layer 0 gets a new frame
2954 // 2.) Layer 1 gets a new frame
2955 // 3.) Layer 1 is latched.
2956 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2957 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002958 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002959 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002960 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002961 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002962 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002963 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002964 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002965 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002966 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002967 } else {
2968 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002969 }
Robert Carr2047fae2016-11-28 14:09:09 -08002970 });
2971
chaviw49a108c2019-08-12 11:23:06 -07002972 // The client can continue submitting buffers for offscreen layers, but they will not
2973 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2974 // layers to ensure dequeueBuffer doesn't block indefinitely.
2975 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002976 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002977 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2978 }
2979
Lloyd Piquef2c79392018-12-20 16:23:33 -08002980 if (!mLayersWithQueuedFrames.empty()) {
2981 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2982 // writes to Layer current state. See also b/119481871
2983 Mutex::Autolock lock(mStateLock);
2984
2985 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002986 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002987 mLayersPendingRefresh.push_back(layer);
2988 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002989 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002990 if (layer->isBufferLatched()) {
2991 newDataLatched = true;
2992 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002993 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002994 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002995
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002996 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002997
2998 // If we will need to wake up at some time in the future to deal with a
2999 // queued frame that shouldn't be displayed during this vsync period, wake
3000 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003001 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003002 signalLayerUpdate();
3003 }
3004
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003005 // enter boot animation on first buffer latch
3006 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3007 ALOGI("Enter boot animation");
3008 mBootStage = BootStage::BOOTANIMATION;
3009 }
3010
Edgar Arriaga844fa672020-01-16 14:21:42 -08003011 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003012
Dan Stoza6b9454d2014-11-07 16:00:59 -08003013 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003014 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015}
3016
Mathias Agopianad456f92011-01-13 17:53:01 -08003017void SurfaceFlinger::invalidateHwcGeometry()
3018{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003019 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003020}
3021
Robert Carrc0df3122019-04-11 13:18:21 -07003022status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3023 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3024 const sp<IBinder>& parentHandle,
3025 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003026 // add this layer to the current state list
3027 {
3028 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003029 sp<Layer> parent;
3030 if (parentHandle != nullptr) {
3031 parent = fromHandle(parentHandle);
3032 if (parent == nullptr) {
3033 return NAME_NOT_FOUND;
3034 }
3035 } else {
3036 parent = parentLayer;
3037 }
3038
Robert Carr1f0a16a2016-10-24 16:27:39 -07003039 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003040 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003041 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003042 return NO_MEMORY;
3043 }
Robert Carrc0df3122019-04-11 13:18:21 -07003044
3045 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3046
Robert Carrb89ea9d2018-12-10 13:01:14 -08003047 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003048 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003049 } else if (parent == nullptr) {
3050 lbc->onRemovedFromCurrentState();
3051 } else if (parent->isRemovedFromCurrentState()) {
3052 parent->addChild(lbc);
3053 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003054 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003055 parent->addChild(lbc);
3056 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003057
Yiwei Zhang243b3782018-05-15 17:40:04 -07003058 if (gbc != nullptr) {
3059 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3060 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3061 mMaxGraphicBufferProducerListSize,
3062 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3063 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003064 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003065 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003067 }
3068
Mathias Agopian96f08192010-06-02 23:28:45 -07003069 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003070 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003071
Dan Stoza7d89d062015-04-30 13:29:25 -07003072 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003073}
3074
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003075uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003076 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003077}
3078
Mathias Agopian3f844832013-08-07 21:24:32 -07003079uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003080 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081}
3082
Mathias Agopian3f844832013-08-07 21:24:32 -07003083uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003084 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003085}
3086
3087uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003088 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003089 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003090 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003092 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093 }
3094 return old;
3095}
3096
Marissa Wall713b63f2018-10-17 15:42:43 -07003097bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003098 // to prevent onHandleDestroyed from being called while the lock is held,
3099 // we must keep a copy of the transactions (specifically the composer
3100 // states) around outside the scope of the lock
3101 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003102 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003103 {
3104 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003105
Valerie Haufce31b82019-04-30 16:41:14 -07003106 auto it = mTransactionQueues.begin();
3107 while (it != mTransactionQueues.end()) {
3108 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003109
Valerie Haufce31b82019-04-30 16:41:14 -07003110 while (!transactionQueue.empty()) {
3111 const auto& transaction = transactionQueue.front();
3112 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003113 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003114 transaction.states)) {
3115 setTransactionFlags(eTransactionFlushNeeded);
3116 break;
3117 }
3118 transactions.push_back(transaction);
3119 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3120 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003121 transaction.buffer, transaction.postTime,
3122 transaction.privileged, transaction.hasListenerCallbacks,
3123 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003124 transactionQueue.pop();
3125 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003126 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003127
Valerie Haufce31b82019-04-30 16:41:14 -07003128 if (transactionQueue.empty()) {
3129 it = mTransactionQueues.erase(it);
3130 mTransactionCV.broadcast();
3131 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003132 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003133 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003134 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003135 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003136 return flushedATransaction;
3137}
3138
3139bool SurfaceFlinger::transactionFlushNeeded() {
3140 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003141}
3142
chaviwca27f252018-02-06 16:46:39 -08003143
Marissa Wall17b4e452018-12-26 16:32:34 -08003144bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003145 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003146 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003147 if (!useCachedExpectedPresentTime)
3148 populateExpectedPresentTime();
3149
3150 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003151 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3152 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3153 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3154 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3155 return false;
3156 }
3157
Marissa Wall713b63f2018-10-17 15:42:43 -07003158 for (const ComposerState& state : states) {
3159 const layer_state_t& s = state.state;
3160 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3161 continue;
3162 }
3163 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003164 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003165 }
3166 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003167 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003168}
3169
Valerie Hau9dab9732019-08-20 09:29:25 -07003170void SurfaceFlinger::setTransactionState(
3171 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3172 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3173 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3174 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003175 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003176
Valerie Haubc6ddb12019-03-08 11:10:15 -08003177 const int64_t postTime = systemTime();
3178
Robert Carr14167e02019-02-13 13:50:55 -08003179 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3180
Mathias Agopian698c0872011-06-28 19:09:31 -07003181 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003182
Marissa Wall713b63f2018-10-17 15:42:43 -07003183 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003184 auto itr = mTransactionQueues.find(applyToken);
3185 // if this is an animation frame, wait until prior animation frame has
3186 // been applied by SF
3187 if (flags & eAnimation) {
3188 while (itr != mTransactionQueues.end()) {
3189 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3190 if (CC_UNLIKELY(err != NO_ERROR)) {
3191 ALOGW_IF(err == TIMED_OUT,
3192 "setTransactionState timed out "
3193 "waiting for animation frame to apply");
3194 break;
3195 }
3196 itr = mTransactionQueues.find(applyToken);
3197 }
3198 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003199
3200 // Expected present time is computed and cached on invalidate, so it may be stale.
3201 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3202 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003203 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003204 uncacheBuffer, postTime, privileged,
3205 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003206 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003207 return;
3208 }
3209
Valerie Haubc6ddb12019-03-08 11:10:15 -08003210 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003211 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3212 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003213}
3214
Valerie Hau9dab9732019-08-20 09:29:25 -07003215void SurfaceFlinger::applyTransactionState(
3216 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3217 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3218 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3219 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3220 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003221 uint32_t transactionFlags = 0;
3222
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003223 if (flags & eAnimation) {
3224 // For window updates that are part of an animation we must wait for
3225 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003226 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003227 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003228 if (CC_UNLIKELY(err != NO_ERROR)) {
3229 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003230 // caller after a few seconds.
3231 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3232 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003233 mAnimTransactionPending = false;
3234 break;
3235 }
3236 }
3237 }
3238
chaviwca27f252018-02-06 16:46:39 -08003239 for (const DisplayState& display : displays) {
3240 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003241 }
3242
Valerie Hau9dab9732019-08-20 09:29:25 -07003243 // start and end registration for listeners w/ no surface so they can get their callback. Note
3244 // that listeners with SurfaceControls will start registration during setClientStateLocked
3245 // below.
3246 for (const auto& listener : listenerCallbacks) {
3247 mTransactionCompletedThread.startRegistration(listener);
3248 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003249 }
3250
Valerie Hau9dab9732019-08-20 09:29:25 -07003251 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003252 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003253 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003254 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3255 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003256 }
3257
Valerie Hau9dab9732019-08-20 09:29:25 -07003258 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003259 mTransactionCompletedThread.endRegistration(listenerCallback);
3260 }
3261
Marissa Walle2ffb422018-10-12 11:33:52 -07003262 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003263 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003264 mTransactionCompletedThread.sendCallbacks();
3265 }
3266 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003267
chaviw273171b2018-12-26 11:46:30 -08003268 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3269
Marissa Wall947d34e2019-03-29 14:03:53 -07003270 if (uncacheBuffer.isValid()) {
3271 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003272 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003273 }
3274
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003275 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3276 // anyway. This can be used as a flush mechanism for previous async transactions.
3277 // Empty animation transaction can be used to simulate back-pressure, so also force a
3278 // transaction for empty animation transactions.
3279 if (transactionFlags == 0 &&
3280 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003281 transactionFlags = eTransactionNeeded;
3282 }
3283
Marissa Wall06255332019-03-27 13:48:27 -07003284 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3285 // so we don't have to wake up again next frame to preform an uneeded traversal.
3286 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3287 transactionFlags = transactionFlags & (~eTraversalNeeded);
3288 mTraversalNeededMainThread = true;
3289 }
3290
Mathias Agopian386aa982011-11-07 21:58:03 -08003291 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003292 if (mInterceptor->isEnabled()) {
3293 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003294 }
Irvel468051e2016-06-13 16:44:44 -07003295
Mathias Agopian386aa982011-11-07 21:58:03 -08003296 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003297 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3298 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003299 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003300
3301 // if this is a synchronous transaction, wait for it to take effect
3302 // before returning.
3303 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003304 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003305 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003306 if (flags & eAnimation) {
3307 mAnimTransactionPending = true;
3308 }
chaviw4fe36852019-04-15 16:25:49 -07003309 if (mPendingInputWindowCommands.syncInputWindows) {
3310 mPendingSyncInputWindows = true;
3311 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003312
3313 // applyTransactionState can be called by either the main SF thread or by
3314 // another process through setTransactionState. While a given process may wish
3315 // to wait on synchronous transactions, the main SF thread should never
3316 // be blocked. Therefore, we only wait if isMainThread is false.
3317 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003318 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3319 if (CC_UNLIKELY(err != NO_ERROR)) {
3320 // just in case something goes wrong in SF, return to the
3321 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003322 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3323 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003324 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003325 break;
3326 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003327 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328 }
3329}
3330
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003331uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3332 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3333 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003334
Mathias Agopiane57f2922012-08-09 16:29:12 -07003335 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003336 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3337
3338 const uint32_t what = s.what;
3339 if (what & DisplayState::eSurfaceChanged) {
3340 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3341 state.surface = s.surface;
3342 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003343 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003345 if (what & DisplayState::eLayerStackChanged) {
3346 if (state.layerStack != s.layerStack) {
3347 state.layerStack = s.layerStack;
3348 flags |= eDisplayTransactionNeeded;
3349 }
3350 }
3351 if (what & DisplayState::eDisplayProjectionChanged) {
3352 if (state.orientation != s.orientation) {
3353 state.orientation = s.orientation;
3354 flags |= eDisplayTransactionNeeded;
3355 }
3356 if (state.frame != s.frame) {
3357 state.frame = s.frame;
3358 flags |= eDisplayTransactionNeeded;
3359 }
3360 if (state.viewport != s.viewport) {
3361 state.viewport = s.viewport;
3362 flags |= eDisplayTransactionNeeded;
3363 }
3364 }
3365 if (what & DisplayState::eDisplaySizeChanged) {
3366 if (state.width != s.width) {
3367 state.width = s.width;
3368 flags |= eDisplayTransactionNeeded;
3369 }
3370 if (state.height != s.height) {
3371 state.height = s.height;
3372 flags |= eDisplayTransactionNeeded;
3373 }
3374 }
3375
Mathias Agopiane57f2922012-08-09 16:29:12 -07003376 return flags;
3377}
3378
Robert Carr14167e02019-02-13 13:50:55 -08003379bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003380 IPCThreadState* ipc = IPCThreadState::self();
3381 const int pid = ipc->getCallingPid();
3382 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003383 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003384 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003385 return false;
3386 }
3387 return true;
3388}
3389
Marissa Wall3dad52d2019-03-22 14:03:19 -07003390uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003391 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3392 bool privileged,
3393 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003394 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003395
Valerie Hau9dab9732019-08-20 09:29:25 -07003396 for (auto& listener : s.listeners) {
3397 // note that startRegistration will not re-register if the listener has
3398 // already be registered for a prior surface control
3399 mTransactionCompletedThread.startRegistration(listener);
3400 listenerCallbacks.insert(listener);
3401 }
3402
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003403 sp<Layer> layer = nullptr;
3404 if (s.surface) {
3405 layer = fromHandle(s.surface);
3406 } else {
3407 // The client may provide us a null handle. Treat it as if the layer was removed.
3408 ALOGW("Attempt to set client state with a null layer handle");
3409 }
chaviw8b3871a2017-11-01 17:41:01 -07003410 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003411 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003412 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003413 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003414 }
chaviw8b3871a2017-11-01 17:41:01 -07003415 return 0;
3416 }
3417
chaviw8b3871a2017-11-01 17:41:01 -07003418 uint32_t flags = 0;
3419
Garfield Tan8a3083e2018-12-03 13:21:07 -08003420 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003421
3422 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3423 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003424 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003425 layer->pushPendingState();
3426 }
3427
Valerie Hau871d6352020-01-29 08:44:02 -08003428 // Only set by BLAST adapter layers
3429 if (what & layer_state_t::eProducerDisconnect) {
3430 layer->onDisconnect();
3431 }
3432
chaviw8b3871a2017-11-01 17:41:01 -07003433 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003434 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003435 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 }
3438 if (what & layer_state_t::eLayerChanged) {
3439 // NOTE: index needs to be calculated before we update the state
3440 const auto& p = layer->getParent();
3441 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003442 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003443 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003444 mCurrentState.layersSortedByZ.removeAt(idx);
3445 mCurrentState.layersSortedByZ.add(layer);
3446 // we need traversal (state changed)
3447 // AND transaction (list changed)
3448 flags |= eTransactionNeeded|eTraversalNeeded;
3449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 } else {
3451 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003452 flags |= eTransactionNeeded|eTraversalNeeded;
3453 }
3454 }
chaviw8b3871a2017-11-01 17:41:01 -07003455 }
3456 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003457 // NOTE: index needs to be calculated before we update the state
3458 const auto& p = layer->getParent();
3459 if (p == nullptr) {
3460 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3461 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3462 mCurrentState.layersSortedByZ.removeAt(idx);
3463 mCurrentState.layersSortedByZ.add(layer);
3464 // we need traversal (state changed)
3465 // AND transaction (list changed)
3466 flags |= eTransactionNeeded|eTraversalNeeded;
3467 }
3468 } else {
3469 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3470 flags |= eTransactionNeeded|eTraversalNeeded;
3471 }
chaviw8b3871a2017-11-01 17:41:01 -07003472 }
3473 }
3474 if (what & layer_state_t::eSizeChanged) {
3475 if (layer->setSize(s.w, s.h)) {
3476 flags |= eTraversalNeeded;
3477 }
3478 }
3479 if (what & layer_state_t::eAlphaChanged) {
3480 if (layer->setAlpha(s.alpha))
3481 flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eColorChanged) {
3484 if (layer->setColor(s.color))
3485 flags |= eTraversalNeeded;
3486 }
Peiyong Lind3788632018-09-18 16:01:31 -07003487 if (what & layer_state_t::eColorTransformChanged) {
3488 if (layer->setColorTransform(s.colorTransform)) {
3489 flags |= eTraversalNeeded;
3490 }
3491 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003492 if (what & layer_state_t::eBackgroundColorChanged) {
3493 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3494 flags |= eTraversalNeeded;
3495 }
3496 }
chaviw8b3871a2017-11-01 17:41:01 -07003497 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003498 // TODO: b/109894387
3499 //
3500 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3501 // rotation. To see the problem observe that if we have a square parent, and a child
3502 // of the same size, then we rotate the child 45 degrees around it's center, the child
3503 // must now be cropped to a non rectangular 8 sided region.
3504 //
3505 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3506 // private API, and the WindowManager only uses rotation in one case, which is on a top
3507 // level layer in which cropping is not an issue.
3508 //
3509 // However given that abuse of rotation matrices could lead to surfaces extending outside
3510 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3511 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3512 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003513 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003514 flags |= eTraversalNeeded;
3515 }
3516 if (what & layer_state_t::eTransparentRegionChanged) {
3517 if (layer->setTransparentRegionHint(s.transparentRegion))
3518 flags |= eTraversalNeeded;
3519 }
3520 if (what & layer_state_t::eFlagsChanged) {
3521 if (layer->setFlags(s.flags, s.mask))
3522 flags |= eTraversalNeeded;
3523 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003524 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003525 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003526 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003527 if (what & layer_state_t::eCornerRadiusChanged) {
3528 if (layer->setCornerRadius(s.cornerRadius))
3529 flags |= eTraversalNeeded;
3530 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003531 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3532 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3533 }
chaviw8b3871a2017-11-01 17:41:01 -07003534 if (what & layer_state_t::eLayerStackChanged) {
3535 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3536 // We only allow setting layer stacks for top level layers,
3537 // everything else inherits layer stack from its parent.
3538 if (layer->hasParent()) {
3539 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003540 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003541 } else if (idx < 0) {
3542 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003543 "that also does not appear in the top level layer list. Something"
3544 " has gone wrong.",
3545 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003546 } else if (layer->setLayerStack(s.layerStack)) {
3547 mCurrentState.layersSortedByZ.removeAt(idx);
3548 mCurrentState.layersSortedByZ.add(layer);
3549 // we need traversal (state changed)
3550 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003551 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003552 }
3553 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003554 if (what & layer_state_t::eDeferTransaction_legacy) {
3555 if (s.barrierHandle_legacy != nullptr) {
3556 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3557 } else if (s.barrierGbp_legacy != nullptr) {
3558 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003559 if (authenticateSurfaceTextureLocked(gbp)) {
3560 const auto& otherLayer =
3561 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003562 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003563 } else {
3564 ALOGE("Attempt to defer transaction to to an"
3565 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003566 }
3567 }
chaviw8b3871a2017-11-01 17:41:01 -07003568 // We don't trigger a traversal here because if no other state is
3569 // changed, we don't want this to cause any more work
3570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 if (what & layer_state_t::eReparentChildren) {
3572 if (layer->reparentChildren(s.reparentHandle)) {
3573 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003574 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003575 }
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (what & layer_state_t::eDetachChildren) {
3577 layer->detachChildren();
3578 }
3579 if (what & layer_state_t::eOverrideScalingModeChanged) {
3580 layer->setOverrideScalingMode(s.overrideScalingMode);
3581 // We don't trigger a traversal here because if no other state is
3582 // changed, we don't want this to cause any more work
3583 }
Marissa Wall61c58622018-07-18 10:12:20 -07003584 if (what & layer_state_t::eTransformChanged) {
3585 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3586 }
3587 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3588 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3589 flags |= eTraversalNeeded;
3590 }
3591 if (what & layer_state_t::eCropChanged) {
3592 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3593 }
Marissa Wall861616d2018-10-22 12:52:23 -07003594 if (what & layer_state_t::eFrameChanged) {
3595 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3596 }
Marissa Wall61c58622018-07-18 10:12:20 -07003597 if (what & layer_state_t::eAcquireFenceChanged) {
3598 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eDataspaceChanged) {
3601 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3602 }
3603 if (what & layer_state_t::eHdrMetadataChanged) {
3604 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3605 }
3606 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3607 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3608 }
3609 if (what & layer_state_t::eApiChanged) {
3610 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eSidebandStreamChanged) {
3613 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3614 }
Robert Carr720e5062018-07-30 17:45:14 -07003615 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003616 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003617 layer->setInputInfo(s.inputInfo);
3618 flags |= eTraversalNeeded;
3619 } else {
3620 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3621 }
Robert Carr720e5062018-07-30 17:45:14 -07003622 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003623 if (what & layer_state_t::eMetadataChanged) {
3624 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3625 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003626 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3627 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3628 flags |= eTraversalNeeded;
3629 }
3630 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003631 if (what & layer_state_t::eShadowRadiusChanged) {
3632 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3633 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003634 if (what & layer_state_t::eFrameRateSelectionPriority) {
3635 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3636 flags |= eTraversalNeeded;
3637 }
3638 }
Steven Thomas3172e202020-01-06 19:25:30 -08003639 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003640 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3641 "SurfaceFlinger::setClientStateLocked") &&
3642 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3643 Layer::FrameRate::convertCompatibility(
3644 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003645 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003646 }
Steven Thomas3172e202020-01-06 19:25:30 -08003647 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003648 // This has to happen after we reparent children because when we reparent to null we remove
3649 // child layers from current state and remove its relative z. If the children are reparented in
3650 // the same transaction, then we have to make sure we reparent the children first so we do not
3651 // lose its relative z order.
3652 if (what & layer_state_t::eReparent) {
3653 bool hadParent = layer->hasParent();
3654 if (layer->reparent(s.parentHandleForChild)) {
3655 if (!hadParent) {
3656 mCurrentState.layersSortedByZ.remove(layer);
3657 }
3658 flags |= eTransactionNeeded | eTraversalNeeded;
3659 }
3660 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003661 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003662 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3663 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003664 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3665 }
3666 }
Marissa Wall78b72202019-03-15 14:58:34 -07003667 bool bufferChanged = what & layer_state_t::eBufferChanged;
3668 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3669 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003670 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003671 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003672 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3673 if (success) {
3674 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3675 success = ClientCache::getInstance()
3676 .registerErasedRecipient(s.cachedBuffer,
3677 wp<ClientCache::ErasedRecipient>(this));
3678 if (!success) {
3679 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3680 }
3681 }
Marissa Wall78b72202019-03-15 14:58:34 -07003682 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003683 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003684 } else if (bufferChanged) {
3685 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003686 }
Marissa Wall78b72202019-03-15 14:58:34 -07003687 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003688 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3689 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003690 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003691 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003692 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003693 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3694 // Do not put anything that updates layer state or modifies flags after
3695 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003696 return flags;
3697}
3698
chaviw273171b2018-12-26 11:46:30 -08003699uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3700 uint32_t flags = 0;
3701 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3702 flags |= eTraversalNeeded;
3703 }
3704
chaviwa911b102019-02-14 10:18:33 -08003705 if (inputWindowCommands.syncInputWindows) {
3706 flags |= eTraversalNeeded;
3707 }
3708
Vishnu Nairec0ab382019-02-13 15:32:56 -08003709 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003710 return flags;
3711}
3712
chaviwfe94a222019-08-21 13:52:59 -07003713status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3714 sp<IBinder>* outHandle) {
3715 if (!mirrorFromHandle) {
3716 return NAME_NOT_FOUND;
3717 }
3718
3719 sp<Layer> mirrorLayer;
3720 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003721 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003722
3723 {
3724 Mutex::Autolock _l(mStateLock);
3725 mirrorFrom = fromHandle(mirrorFromHandle);
3726 if (!mirrorFrom) {
3727 return NAME_NOT_FOUND;
3728 }
3729
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003730 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3731 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003732 if (result != NO_ERROR) {
3733 return result;
3734 }
3735
3736 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3737 }
3738
3739 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3740}
3741
Marissa Wall2d814fb2019-04-09 18:52:57 +00003742status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3743 uint32_t h, PixelFormat format, uint32_t flags,
3744 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003745 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003746 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3747 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003748 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003749 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003750 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003752 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003753
Robert Carrc0df3122019-04-11 13:18:21 -07003754 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3755 "Expected only one of parentLayer or parentHandle to be non-null. "
3756 "Programmer error?");
3757
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758 status_t result = NO_ERROR;
3759
3760 sp<Layer> layer;
3761
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003762 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003763
Evan Roskya1f1e152019-01-24 16:17:46 -08003764 bool primaryDisplayOnly = false;
3765
3766 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3767 // TODO b/64227542
3768 if (metadata.has(METADATA_WINDOW_TYPE)) {
3769 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3770 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003771 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003772 primaryDisplayOnly = true;
3773 }
3774 }
3775
Mathias Agopian3165cc22012-08-08 19:42:09 -07003776 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003777 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003778 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3779 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003780
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003782 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003783 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003784 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003785 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003786 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003787 // check if buffer size is set for color layer.
3788 if (w > 0 || h > 0) {
3789 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3790 int(w), int(h));
3791 return BAD_VALUE;
3792 }
3793
Vishnu Nairfa247b12020-02-11 08:58:26 -08003794 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3795 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003796 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003797 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003798 // check if buffer size is set for container layer.
3799 if (w > 0 || h > 0) {
3800 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3801 int(w), int(h));
3802 return BAD_VALUE;
3803 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003804 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3805 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003806 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003807 default:
3808 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809 break;
3810 }
3811
Dan Stoza7d89d062015-04-30 13:29:25 -07003812 if (result != NO_ERROR) {
3813 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003815
Evan Roskya1f1e152019-01-24 16:17:46 -08003816 if (primaryDisplayOnly) {
3817 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003818 }
3819
Robert Carrb89ea9d2018-12-10 13:01:14 -08003820 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003821 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3822 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003823 if (result != NO_ERROR) {
3824 return result;
3825 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003826 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003827
3828 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003829 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830}
3831
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003832std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3833 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003834
3835 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003836 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003837
Dan Stoza436ccf32018-06-21 12:10:12 -07003838 // Grab the state lock since we're accessing mCurrentState
3839 Mutex::Autolock lock(mStateLock);
3840
Cody Northropbc755282017-03-31 12:00:08 -06003841 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003842 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003843 while (matchFound) {
3844 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003845 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003846 if (layer->getName() == uniqueName) {
3847 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003848 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003849 }
3850 });
3851 }
3852
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003853 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003854 return uniqueName;
3855}
3856
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003857status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003858 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003859 LayerMetadata metadata, PixelFormat& format,
3860 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003861 sp<IGraphicBufferProducer>* gbp,
3862 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003863 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003864 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 case PIXEL_FORMAT_TRANSPARENT:
3866 case PIXEL_FORMAT_TRANSLUCENT:
3867 format = PIXEL_FORMAT_RGBA_8888;
3868 break;
3869 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003870 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003871 break;
3872 }
3873
chaviwb4c6e582019-08-16 14:35:07 -07003874 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003875 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003876 args.textureName = getNewTexture();
3877 {
3878 // Grab the SF state lock during this since it's the only safe way to access
3879 // RenderEngine when creating a BufferLayerConsumer
3880 // TODO: Check if this lock is still needed here
3881 Mutex::Autolock lock(mStateLock);
3882 layer = getFactory().createBufferQueueLayer(args);
3883 }
3884
Marissa Wallfd668622018-05-10 10:21:13 -07003885 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003886 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003887 *handle = layer->getHandle();
3888 *gbp = layer->getProducer();
3889 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003890 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003891
Marissa Wallfd668622018-05-10 10:21:13 -07003892 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003893 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894}
3895
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003896status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003897 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003898 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003899 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003900 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003901 args.displayDevice = getDefaultDisplayDevice();
3902 args.textureName = getNewTexture();
3903 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003904 if (outTransformHint) {
3905 *outTransformHint = layer->getTransformHint();
3906 }
Marissa Wall61c58622018-07-18 10:12:20 -07003907 *handle = layer->getHandle();
3908 *outLayer = layer;
3909
3910 return NO_ERROR;
3911}
3912
Vishnu Nairfa247b12020-02-11 08:58:26 -08003913status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3914 uint32_t h, uint32_t flags, LayerMetadata metadata,
3915 sp<IBinder>* handle, sp<Layer>* outLayer) {
3916 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003917 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003918 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003919 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003920}
3921
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003923 uint32_t w, uint32_t h, uint32_t flags,
3924 LayerMetadata metadata, sp<IBinder>* handle,
3925 sp<Layer>* outLayer) {
3926 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003927 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003928 *handle = (*outLayer)->getHandle();
3929 return NO_ERROR;
3930}
3931
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003932void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003933 mLayersPendingRemoval.add(layer);
3934 mLayersRemoved = true;
3935 setTransactionFlags(eTransactionNeeded);
3936}
3937
Robert Carr695d5282018-12-18 15:27:58 -08003938void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003939{
Robert Carr2e102c92018-10-23 12:11:15 -07003940 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003941 // If a layer has a parent, we allow it to out-live it's handle
3942 // with the idea that the parent holds a reference and will eventually
3943 // be cleaned up. However no one cleans up the top-level so we do so
3944 // here.
3945 if (layer->getParent() == nullptr) {
3946 mCurrentState.layersSortedByZ.remove(layer);
3947 }
3948 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003949
3950 auto it = mLayersByLocalBinderToken.begin();
3951 while (it != mLayersByLocalBinderToken.end()) {
3952 if (it->second == layer) {
3953 it = mLayersByLocalBinderToken.erase(it);
3954 } else {
3955 it++;
3956 }
3957 }
3958
Robert Carr695d5282018-12-18 15:27:58 -08003959 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003960}
3961
Mathias Agopianb60314a2012-04-10 22:09:54 -07003962// ---------------------------------------------------------------------------
3963
Andy McFadden13a082e2012-08-24 10:16:42 -07003964void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003965 const auto display = getDefaultDisplayDeviceLocked();
3966 if (!display) return;
3967
3968 const sp<IBinder> token = display->getDisplayToken().promote();
3969 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003970
Jesse Hall01e29052013-02-19 16:13:35 -08003971 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003972 Vector<ComposerState> state;
3973 Vector<DisplayState> displays;
3974 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003975 d.what = DisplayState::eDisplayProjectionChanged |
3976 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003977 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003978 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003979 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003980 d.frame.makeInvalid();
3981 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003982 d.width = 0;
3983 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003984 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003985 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3986 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003987
Dominik Laskowskie9774092018-12-11 10:04:24 -08003988 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003989
Dominik Laskowski83b88212018-12-11 13:34:06 -08003990 const nsecs_t vsyncPeriod = getVsyncPeriod();
3991 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003992
Brian Andersond0010582017-03-07 13:20:31 -08003993 // Use phase of 0 since phase is not known.
3994 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003995 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003996 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003997}
3998
3999void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004000 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004001 postMessageAsync(
4002 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004003}
4004
Ady Abraham27c70212019-06-11 10:52:26 -07004005void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4006 if (mHWCVsyncState != enabled) {
4007 getHwComposer().setVsyncEnabled(displayId, enabled);
4008 mHWCVsyncState = enabled;
4009 }
4010}
4011
Dominik Laskowskie9774092018-12-11 10:04:24 -08004012void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004013 if (display->isVirtual()) {
4014 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004015 return;
4016 }
4017
Dominik Laskowski075d3172018-05-24 15:50:06 -07004018 const auto displayId = display->getId();
4019 LOG_ALWAYS_FATAL_IF(!displayId);
4020
Dominik Laskowski34157762018-10-31 13:07:19 -07004021 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004022
4023 int currentMode = display->getPowerMode();
4024 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004025 return;
4026 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004028 display->setPowerMode(mode);
4029
Lloyd Pique4dccc412018-01-22 17:21:36 -08004030 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004031 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004032 }
4033
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004034 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004035 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004036 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004037 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004038 mScheduler->onScreenAcquired(mAppConnectionHandle);
4039 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004040 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004042 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004043 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004044 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004045
4046 struct sched_param param = {0};
4047 param.sched_priority = 1;
4048 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4049 ALOGW("Couldn't set SCHED_FIFO on display on");
4050 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004051 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004052 // Turn off the display
4053 struct sched_param param = {0};
4054 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4055 ALOGW("Couldn't set SCHED_OTHER on display off");
4056 }
4057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004058 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004059 mScheduler->disableHardwareVsync(true);
4060 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004061 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004062
Ady Abraham27c70212019-06-11 10:52:26 -07004063 // Make sure HWVsync is disabled before turning off the display
4064 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4065
Dominik Laskowski075d3172018-05-24 15:50:06 -07004066 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004067 mVisibleRegionsDirty = true;
4068 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004069 } else if (mode == HWC_POWER_MODE_DOZE ||
4070 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004071 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004072 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004073 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004074 mScheduler->onScreenAcquired(mAppConnectionHandle);
4075 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004076 }
4077 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4078 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004079 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004080 mScheduler->disableHardwareVsync(true);
4081 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004082 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004083 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004084 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004085 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004086 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004087 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004088
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004089 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004090 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004091 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004092 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004093 }
4094
Dominik Laskowski34157762018-10-31 13:07:19 -07004095 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004096}
4097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004098void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004099 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004100 const auto display = getDisplayDevice(displayToken);
4101 if (!display) {
4102 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4103 displayToken.get());
4104 } else if (display->isVirtual()) {
4105 ALOGW("Attempt to set power mode %d for virtual display", mode);
4106 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004107 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004108 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004109 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004110}
4111
4112// ---------------------------------------------------------------------------
4113
Dominik Laskowskic2867142019-01-21 11:33:38 -08004114status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4115 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004116 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004117
Mathias Agopianbd115332013-04-18 16:41:04 -07004118 IPCThreadState* ipc = IPCThreadState::self();
4119 const int pid = ipc->getCallingPid();
4120 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004121
Mathias Agopianbd115332013-04-18 16:41:04 -07004122 if ((uid != AID_SHELL) &&
4123 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004124 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4125 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004127 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004128 // (this would indicate SF is stuck, but we want to be able to
4129 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004130 status_t err = mStateLock.timedLock(s2ns(1));
4131 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004132 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004133 StringAppendF(&result,
4134 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4135 "(no locks held)\n",
4136 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004137 }
4138
Dominik Laskowskic2867142019-01-21 11:33:38 -08004139 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004140 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004141 {"--dispsync"s,
4142 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004143 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004144 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4145 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4146 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4147 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4148 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4149 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004150 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004151 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4152 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153
Dominik Laskowskic2867142019-01-21 11:33:38 -08004154 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155
Dominik Laskowski46470112019-08-02 13:13:11 -07004156 const auto it = dumpers.find(flag);
4157 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004158 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004159 } else if (!asProto) {
4160 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004161 }
4162
Mathias Agopian9795c422009-08-26 16:36:26 -07004163 if (locked) {
4164 mStateLock.unlock();
4165 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004166
Dominik Laskowski46470112019-08-02 13:13:11 -07004167 if (it == dumpers.end()) {
4168 const LayersProto layersProto = dumpProtoFromMainThread();
4169 if (asProto) {
4170 result.append(layersProto.SerializeAsString());
4171 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004172 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004173 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4174 result.append(LayerProtoParser::layerTreeToString(layerTree));
4175 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004176 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004177 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004179 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004180 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004181 return NO_ERROR;
4182}
4183
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004184status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4185 if (asProto && mTracing.isEnabled()) {
4186 mTracing.writeToFileAsync();
4187 }
4188
4189 return doDump(fd, DumpArgs(), asProto);
4190}
4191
Dominik Laskowskic2867142019-01-21 11:33:38 -08004192void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004193 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004194 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004195}
4196
Dominik Laskowskic2867142019-01-21 11:33:38 -08004197void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004198 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004199
Dominik Laskowskic2867142019-01-21 11:33:38 -08004200 if (args.size() > 1) {
4201 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004202 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004203 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004204 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004205 }
Robert Carr2047fae2016-11-28 14:09:09 -08004206 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004207 } else {
4208 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004209 }
4210}
4211
Dominik Laskowskic2867142019-01-21 11:33:38 -08004212void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004213 const bool clearAll = args.size() < 2;
4214 const auto name = clearAll ? String8() : String8(args[1]);
4215
Edgar Arriaga844fa672020-01-16 14:21:42 -08004216 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004217 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004218 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004219 }
Robert Carr2047fae2016-11-28 14:09:09 -08004220 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004221
Svetoslavd85084b2014-03-20 10:28:31 -07004222 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004223}
4224
Dominik Laskowskic2867142019-01-21 11:33:38 -08004225void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4226 mTimeStats->parseArgs(asProto, args, result);
4227}
4228
Jamie Gennis6547ff42013-07-16 20:12:42 -07004229// This should only be called from the main thread. Otherwise it would need
4230// the lock and should use mCurrentState rather than mDrawingState.
4231void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004232 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004233 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004234 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004235
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004236 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004237}
4238
Yiwei Zhang5434a782018-12-05 18:06:32 -08004239void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004240 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004241
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004242 if (isLayerTripleBufferingDisabled())
4243 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004244
Yiwei Zhang5434a782018-12-05 18:06:32 -08004245 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4246 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4247 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4248 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4249 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4250 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004251 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004252}
4253
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004254void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004255 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004256
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004257 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004258 result.append("\n");
4259
Ady Abraham9e16a482019-12-03 17:19:41 -08004260 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004261 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004262 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004263 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004264
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004265 HwcConfigIndexType defaultConfig;
4266 float minFps, maxFps;
4267 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004268 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004269 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004270 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004271 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004272 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4273 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004274
Ana Krulecc2870422019-01-29 19:00:58 -08004275 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004276}
4277
Yiwei Zhang5434a782018-12-05 18:06:32 -08004278void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4279 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004280 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4281 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004282 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004283 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004284 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004285 }
David Sodman4a36e932017-11-07 14:29:47 -08004286 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004287 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004288 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004289 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4290 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004291}
4292
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004293void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4294 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004295 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4296 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004297 for (const auto& segment : history) {
4298 if (!segment.usedThirdBuffer) {
4299 stats.twoBufferTime += segment.totalTime;
4300 }
4301 if (segment.occupancyAverage < 1.0f) {
4302 stats.doubleBufferedTime += segment.totalTime;
4303 } else if (segment.occupancyAverage < 2.0f) {
4304 stats.tripleBufferedTime += segment.totalTime;
4305 }
4306 ++stats.numSegments;
4307 stats.totalTime += segment.totalTime;
4308 }
4309}
4310
Yiwei Zhang5434a782018-12-05 18:06:32 -08004311void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4312 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004313
4314 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4315 const size_t count = currentLayers.size();
4316 for (size_t i=0 ; i<count ; i++) {
4317 currentLayers[i]->dumpFrameEvents(result);
4318 }
4319}
4320
Yiwei Zhang5434a782018-12-05 18:06:32 -08004321void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004322 result.append("Buffering stats:\n");
4323 result.append(" [Layer name] <Active time> <Two buffer> "
4324 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004325 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004326 typedef std::tuple<std::string, float, float, float> BufferTuple;
4327 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004328 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004329 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004330 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004331 if (stats.numSegments == 0) {
4332 continue;
4333 }
4334 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4335 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4336 stats.totalTime;
4337 float doubleBufferRatio = static_cast<float>(
4338 stats.doubleBufferedTime) / stats.totalTime;
4339 float tripleBufferRatio = static_cast<float>(
4340 stats.tripleBufferedTime) / stats.totalTime;
4341 sorted.insert({activeTime, {name, twoBufferRatio,
4342 doubleBufferRatio, tripleBufferRatio}});
4343 }
4344 for (const auto& sortedPair : sorted) {
4345 float activeTime = sortedPair.first;
4346 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004347 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4348 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004349 }
4350 result.append("\n");
4351}
4352
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004354 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004355 const auto displayId = display->getId();
4356 if (!displayId) {
4357 continue;
4358 }
4359 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004360 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004361 continue;
4362 }
4363
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 StringAppendF(&result,
4365 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4366 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004367 uint8_t port;
4368 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004369 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004370 result.append("no identification data\n");
4371 continue;
4372 }
4373
4374 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004375 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004376 continue;
4377 }
4378
4379 const auto edid = parseEdid(data);
4380 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004381 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004382 continue;
4383 }
4384
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004386 result.append(edid->displayName.data(), edid->displayName.length());
4387 result.append("\"\n");
4388 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004389}
4390
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004391void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4392 std::string& result) const {
4393 hwc2_display_t hwcDisplayId;
4394 uint8_t port;
4395 DisplayIdentificationData data;
4396
4397 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4398 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4399 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4400 }
4401}
4402
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004404 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4406 StringAppendF(&result, "DisplayColorSetting: %s\n",
4407 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004408
4409 // TODO: print out if wide-color mode is active or not
4410
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004411 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004412 const auto displayId = display->getId();
4413 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004414 continue;
4415 }
4416
Yiwei Zhang5434a782018-12-05 18:06:32 -08004417 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004419 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004421 }
4422
Lloyd Pique32cbe282018-10-19 13:09:22 -07004423 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004424 StringAppendF(&result, " Current color mode: %s (%d)\n",
4425 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004426 }
4427 result.append("\n");
4428}
4429
Vishnu Nair8406fd72019-07-30 11:29:31 -07004430LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004431 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004432 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4433 layer->writeToProto(layersProto, traceFlags);
4434 }
chaviw1d044282017-09-27 12:19:28 -07004435 return layersProto;
4436}
4437
Vishnu Nair0f085c62019-08-30 08:49:12 -07004438void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4439 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4440 // it.
4441 LayerProto* rootProto = layersProto.add_layers();
4442 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4443 rootProto->set_id(offscreenRootLayerId);
4444 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004445 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004446
4447 for (Layer* offscreenLayer : mOffscreenLayers) {
4448 // Add layer as child of the fake root
4449 rootProto->add_children(offscreenLayer->sequence);
4450
4451 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004452 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004453 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004454 }
4455}
4456
Vishnu Nair8406fd72019-07-30 11:29:31 -07004457LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4458 LayersProto layersProto;
4459 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4460 return layersProto;
4461}
4462
Vishnu Nair0f085c62019-08-30 08:49:12 -07004463void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4464 result.append("Offscreen Layers:\n");
4465 postMessageSync(new LambdaMessage([&]() {
4466 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004467 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004468 layer->dumpCallingUidPid(result);
4469 });
4470 }
4471 }));
4472}
4473
Dominik Laskowskic2867142019-01-21 11:33:38 -08004474void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4475 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004476 Colorizer colorizer(colorize);
4477
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004478 // figure out if we're stuck somewhere
4479 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004480 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004481 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4482
4483 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004484 * Dump library configuration.
4485 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004486
4487 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004488 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004489 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004490 appendSfConfigString(result);
4491 appendUiConfigString(result);
4492 appendGuiConfigString(result);
4493 result.append("\n");
4494
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004495 result.append("\nDisplay identification data:\n");
4496 dumpDisplayIdentificationData(result);
4497
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004498 result.append("\nWide-Color information:\n");
4499 dumpWideColorInfo(result);
4500
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004501 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004502 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004503 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004504 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004505 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004506
Andy McFadden41d67d72014-04-25 16:58:34 -07004507 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004508 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004509 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004510 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004511 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004512
Dan Stozab90cf072015-03-05 11:05:59 -08004513 dumpStaticScreenStats(result);
4514 result.append("\n");
4515
Alec Mouri40189b02019-03-05 15:07:54 -08004516 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4517 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4518 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004519
Dan Stozae77c7662016-05-13 11:37:28 -07004520 dumpBufferingStats(result);
4521
Andy McFadden4803b742012-09-24 19:07:20 -07004522 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004523 * Dump the visible layer list
4524 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004526 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004527 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4528 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004529 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004530
Chia-I Wu2f884132018-09-13 15:17:58 -07004531 {
Lloyd Pique207def92019-02-28 16:09:52 -08004532 StringAppendF(&result, "Composition layers\n");
4533 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004534 auto* compositionState = layer->getCompositionState();
4535 if (!compositionState) return;
4536
4537 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4538 layer->getDebugName() ? layer->getDebugName()
4539 : "<unknown>");
4540 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004541 });
4542 }
4543
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004544 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004545 * Dump Display state
4546 */
4547
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004548 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004549 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004550 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004551 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004552 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004553 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004554 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004555
4556 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004557 * Dump CompositionEngine state
4558 */
4559
4560 mCompositionEngine->dump(result);
4561
4562 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 * Dump SurfaceFlinger global state
4564 */
4565
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004566 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004567 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004568 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004569
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004570 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004571
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004572 DebugEGLImageTracker::getInstance()->dump(result);
4573
Dominik Laskowski075d3172018-05-24 15:50:06 -07004574 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004575 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4576 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004577 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4578 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004579 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result,
4581 " transaction-flags : %08x\n"
4582 " gpu_to_cpu_unsupported : %d\n",
4583 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004584
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004585 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004586 displayId && getHwComposer().isConnected(*displayId)) {
4587 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 StringAppendF(&result,
4589 " refresh-rate : %f fps\n"
4590 " x-dpi : %f\n"
4591 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004592 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4593 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004594 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004595
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597
Dan Stozae22aec72016-08-01 13:20:59 -07004598 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004599 * Tracing state
4600 */
4601 mTracing.dump(result);
4602 result.append("\n");
4603
4604 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004605 * HWC layer minidump
4606 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004607 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004608 const auto displayId = display->getId();
4609 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004610 continue;
4611 }
4612
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004614 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004615 const sp<DisplayDevice> displayDevice = display;
4616 mCurrentState.traverseInZOrder(
4617 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004618 result.append("\n");
4619 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004620
4621 /*
4622 * Dump HWComposer state
4623 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004625 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004627 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004630
4631 /*
4632 * Dump gralloc state
4633 */
4634 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4635 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004636
4637 /*
4638 * Dump VrFlinger state if in use.
4639 */
4640 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4641 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004643 result.append("\n");
4644 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004645
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004646 result.append(mTimeStats->miniDump());
4647 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004648}
4649
Chia-I Wu28f320b2018-05-03 11:02:56 -07004650void SurfaceFlinger::updateColorMatrixLocked() {
4651 mat4 colorMatrix;
4652 if (mGlobalSaturationFactor != 1.0f) {
4653 // Rec.709 luma coefficients
4654 float3 luminance{0.213f, 0.715f, 0.072f};
4655 luminance *= 1.0f - mGlobalSaturationFactor;
4656 mat4 saturationMatrix = mat4(
4657 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4658 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4659 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4660 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4661 );
4662 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4663 } else {
4664 colorMatrix = mClientColorMatrix * mDaltonizer();
4665 }
4666
4667 if (mCurrentState.colorMatrix != colorMatrix) {
4668 mCurrentState.colorMatrix = colorMatrix;
4669 mCurrentState.colorMatrixChanged = true;
4670 setTransactionFlags(eTransactionNeeded);
4671 }
4672}
4673
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004674status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004675#pragma clang diagnostic push
4676#pragma clang diagnostic error "-Wswitch-enum"
4677 switch (static_cast<ISurfaceComposerTag>(code)) {
4678 // These methods should at minimum make sure that the client requested
4679 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004680 case BOOT_FINISHED:
4681 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004682 case CREATE_DISPLAY:
4683 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004684 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 case GET_ANIMATION_FRAME_STATS:
4686 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004687 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004688 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004689 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004690 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4691 case SET_AUTO_LOW_LATENCY_MODE:
4692 case GET_GAME_CONTENT_TYPE_SUPPORT:
4693 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004694 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004695 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004696 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004697 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004698 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004699 case NOTIFY_POWER_HINT:
4700 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004701 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4702 IPCThreadState* ipc = IPCThreadState::self();
4703 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4704 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004705 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 }
Robert Carr1db73f62016-12-21 12:58:51 -08004707 return OK;
4708 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004709 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004710 IPCThreadState* ipc = IPCThreadState::self();
4711 const int pid = ipc->getCallingPid();
4712 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004713 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4714 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004715 return PERMISSION_DENIED;
4716 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004717 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004718 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004719 // Used by apps to hook Choreographer to SurfaceFlinger.
4720 case CREATE_DISPLAY_EVENT_CONNECTION:
4721 // The following calls are currently used by clients that do not
4722 // request necessary permissions. However, they do not expose any secret
4723 // information, so it is OK to pass them.
4724 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004725 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004726 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004727 case GET_PHYSICAL_DISPLAY_IDS:
4728 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004729 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004730 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004731 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004732 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004733 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004734 case GET_DISPLAY_STATS:
4735 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4736 // Calling setTransactionState is safe, because you need to have been
4737 // granted a reference to Client* and Handle* to do anything with it.
4738 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004739 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004740 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004741 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004742 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004743 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004744 // setFrameRate() is deliberately available for apps to call without any
4745 // special permissions.
4746 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004747 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4748 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004749 return OK;
4750 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004751 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004752 case CAPTURE_SCREEN:
4753 case ADD_REGION_SAMPLING_LISTENER:
4754 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004756 IPCThreadState* ipc = IPCThreadState::self();
4757 const int pid = ipc->getCallingPid();
4758 const int uid = ipc->getCallingUid();
4759 if ((uid != AID_GRAPHICS) &&
4760 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4761 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4762 return PERMISSION_DENIED;
4763 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 return OK;
4765 }
chaviw93df2ea2019-04-30 16:45:12 -07004766 case CAPTURE_SCREEN_BY_ID: {
4767 IPCThreadState* ipc = IPCThreadState::self();
4768 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004769 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004770 return OK;
4771 }
4772 return PERMISSION_DENIED;
4773 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004774 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775
4776 // These codes are used for the IBinder protocol to either interrogate the recipient
4777 // side of the transaction for its canonical interface descriptor or to dump its state.
4778 // We let them pass by default.
4779 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4780 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4781 code == IBinder::SYSPROPS_TRANSACTION) {
4782 return OK;
4783 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004784 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004785 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004786 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4788 return OK;
4789 }
4790 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4791 return PERMISSION_DENIED;
4792#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004793}
4794
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4796 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004797 status_t credentialCheck = CheckTransactCodeCredentials(code);
4798 if (credentialCheck != OK) {
4799 return credentialCheck;
4800 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004802 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4803 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004804 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004805 IPCThreadState* ipc = IPCThreadState::self();
4806 const int uid = ipc->getCallingUid();
4807 if (CC_UNLIKELY(uid != AID_SYSTEM
4808 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004809 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004810 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004811 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004812 return PERMISSION_DENIED;
4813 }
4814 int n;
4815 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004816 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004817 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004818 return NO_ERROR;
4819 case 1002: // SHOW_UPDATES
4820 n = data.readInt32();
4821 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004822 invalidateHwcGeometry();
4823 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004824 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004825 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004826 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004827 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004829 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004830 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004831 setTransactionFlags(
4832 eTransactionNeeded|
4833 eDisplayTransactionNeeded|
4834 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004835 return NO_ERROR;
4836 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004837 case 1006:{ // send empty update
4838 signalRefresh();
4839 return NO_ERROR;
4840 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004841 case 1008: // toggle use of hw composer
4842 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004843 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004844 invalidateHwcGeometry();
4845 repaintEverything();
4846 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004847 case 1009: // toggle use of transform hint
4848 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004849 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004850 invalidateHwcGeometry();
4851 repaintEverything();
4852 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004853 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004854 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004855 reply->writeInt32(0);
4856 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004857 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004858 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004859 return NO_ERROR;
4860 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004862 if (!display) {
4863 return NAME_NOT_FOUND;
4864 }
4865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004867 return NO_ERROR;
4868 }
4869 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004870 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004871 // daltonize
4872 n = data.readInt32();
4873 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004874 case 1:
4875 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4876 break;
4877 case 2:
4878 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4879 break;
4880 case 3:
4881 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4882 break;
4883 default:
4884 mDaltonizer.setType(ColorBlindnessType::None);
4885 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004886 }
4887 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004888 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004889 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004890 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004891 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004892
4893 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004894 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004896 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004897 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004898 // apply a color matrix
4899 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004900 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004901 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004902 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004903 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004904 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004905 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004906 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004907 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004908 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004909 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004910
4911 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4912 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004913 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004914 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4915 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4916 }
4917
Chia-I Wu28f320b2018-05-03 11:02:56 -07004918 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004919 return NO_ERROR;
4920 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004921 case 1016: { // Unused.
4922 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004923 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004924 case 1017: {
4925 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004926 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004927 return NO_ERROR;
4928 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004929 case 1018: { // Modify Choreographer's phase offset
4930 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004931 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004932 return NO_ERROR;
4933 }
4934 case 1019: { // Modify SurfaceFlinger's phase offset
4935 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004936 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004937 return NO_ERROR;
4938 }
Irvel468051e2016-06-13 16:44:44 -07004939 case 1020: { // Layer updates interceptor
4940 n = data.readInt32();
4941 if (n) {
4942 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004943 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004944 }
4945 else{
4946 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004947 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004948 }
4949 return NO_ERROR;
4950 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004951 case 1021: { // Disable HWC virtual displays
4952 n = data.readInt32();
4953 mUseHwcVirtualDisplays = !n;
4954 return NO_ERROR;
4955 }
Romain Guy0147a172017-06-01 13:53:56 -07004956 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004957 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004958 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004959
Chia-I Wu28f320b2018-05-03 11:02:56 -07004960 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004961 return NO_ERROR;
4962 }
Romain Guy54f154a2017-10-24 21:40:32 +01004963 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004964 int32_t colorMode;
4965
Chia-I Wu0d711262018-05-21 15:19:35 -07004966 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004967 if (data.readInt32(&colorMode) == NO_ERROR) {
4968 mForceColorMode = static_cast<ColorMode>(colorMode);
4969 }
Romain Guy54f154a2017-10-24 21:40:32 +01004970 invalidateHwcGeometry();
4971 repaintEverything();
4972 return NO_ERROR;
4973 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004974 // Deprecate, use 1030 to check whether the device is color managed.
4975 case 1024: {
4976 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004977 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004978 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004979 n = data.readInt32();
4980 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004981 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004982 Mutex::Autolock lock(mStateLock);
4983 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004984 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004985 reply->writeInt32(NO_ERROR);
4986 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004987 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004988 bool writeFile = false;
4989 {
4990 Mutex::Autolock lock(mStateLock);
4991 mTracingEnabledChanged = true;
4992 writeFile = mTracing.disable();
4993 }
4994
4995 if (writeFile) {
4996 reply->writeInt32(mTracing.writeToFile());
4997 } else {
4998 reply->writeInt32(NO_ERROR);
4999 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005000 }
5001 return NO_ERROR;
5002 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005003 case 1026: { // Get layer tracing status
5004 reply->writeBool(mTracing.isEnabled());
5005 return NO_ERROR;
5006 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005007 // Is a DisplayColorSetting supported?
5008 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005009 const auto display = getDefaultDisplayDevice();
5010 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005011 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005012 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005013
5014 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5015 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005016 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005017 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005018 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005019 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005020 reply->writeBool(true);
5021 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005022 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005023 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005024 break;
5025 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005026 reply->writeBool(
5027 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005028 break;
5029 }
5030 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005031 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005032 // Is VrFlinger active?
5033 case 1028: {
5034 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005035 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005036 return NO_ERROR;
5037 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005038 // Set buffer size for SF tracing (value in KB)
5039 case 1029: {
5040 n = data.readInt32();
5041 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5042 ALOGW("Invalid buffer size: %d KB", n);
5043 reply->writeInt32(BAD_VALUE);
5044 return BAD_VALUE;
5045 }
5046
5047 ALOGD("Updating trace buffer to %d KB", n);
5048 mTracing.setBufferSize(n * 1024);
5049 reply->writeInt32(NO_ERROR);
5050 return NO_ERROR;
5051 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005052 // Is device color managed?
5053 case 1030: {
5054 reply->writeBool(useColorManagement);
5055 return NO_ERROR;
5056 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005057 // Override default composition data space
5058 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5059 // && adb shell stop zygote && adb shell start zygote
5060 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5061 // adb shell stop zygote && adb shell start zygote
5062 case 1031: {
5063 Mutex::Autolock _l(mStateLock);
5064 n = data.readInt32();
5065 if (n) {
5066 n = data.readInt32();
5067 if (n) {
5068 Dataspace dataspace = static_cast<Dataspace>(n);
5069 if (!validateCompositionDataspace(dataspace)) {
5070 return BAD_VALUE;
5071 }
5072 mDefaultCompositionDataspace = dataspace;
5073 }
5074 n = data.readInt32();
5075 if (n) {
5076 Dataspace dataspace = static_cast<Dataspace>(n);
5077 if (!validateCompositionDataspace(dataspace)) {
5078 return BAD_VALUE;
5079 }
5080 mWideColorGamutCompositionDataspace = dataspace;
5081 }
5082 } else {
5083 // restore composition data space.
5084 mDefaultCompositionDataspace = defaultCompositionDataspace;
5085 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5086 }
5087 return NO_ERROR;
5088 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005089 // Set trace flags
5090 case 1033: {
5091 n = data.readUint32();
5092 ALOGD("Updating trace flags to 0x%x", n);
5093 mTracing.setTraceFlags(n);
5094 reply->writeInt32(NO_ERROR);
5095 return NO_ERROR;
5096 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005097 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005098 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005099 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005100 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005101 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5102 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005103 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005104 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005105 } else {
5106 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005107 }
5108 return NO_ERROR;
5109 }
Ady Abraham34392f72019-04-10 11:29:27 -07005110 case 1035: {
5111 n = data.readInt32();
5112 mDebugDisplayConfigSetByBackdoor = false;
5113 if (n >= 0) {
5114 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005115 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005116 if (result != NO_ERROR) {
5117 return result;
5118 }
5119 mDebugDisplayConfigSetByBackdoor = true;
5120 }
5121 return NO_ERROR;
5122 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005123 }
5124 }
5125 return err;
5126}
5127
Steven Thomas6d8110b2017-08-31 18:24:21 -07005128void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005129 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005130 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005131}
5132
Ana Krulec7d1d6832018-12-27 11:10:09 -08005133void SurfaceFlinger::repaintEverythingForHWC() {
5134 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005135 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005136}
5137
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005138// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5139class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005140public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005141 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5142 ~WindowDisconnector() {
5143 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005144 }
5145
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005146private:
5147 ANativeWindow* mWindow;
5148 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005149};
5150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005151status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005152 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005153 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5154 const Rect& sourceCrop, uint32_t reqWidth,
5155 uint32_t reqHeight, bool useIdentityTransform,
5156 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005157 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005160
Dominik Laskowski718f9602019-11-09 20:01:35 -08005161 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5162 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5163 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5164 renderAreaRotation = ui::Transform::ROT_0;
5165 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005166
Chia-I Wu20261cb2018-08-23 12:55:44 -07005167 sp<DisplayDevice> display;
5168 {
5169 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005170
Chia-I Wu20261cb2018-08-23 12:55:44 -07005171 display = getDisplayDeviceLocked(displayToken);
5172 if (!display) return BAD_VALUE;
5173
Chia-I Wucb023152018-08-28 12:57:23 -07005174 // set the requested width/height to the logical display viewport size
5175 // by default
5176 if (reqWidth == 0 || reqHeight == 0) {
5177 reqWidth = uint32_t(display->getViewport().width());
5178 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005179 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005180 }
5181
Peiyong Lin0e003c92018-09-17 11:09:51 -07005182 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005183 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005184
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005185 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5186 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005187 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005188 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005189}
5190
chaviw93df2ea2019-04-30 16:45:12 -07005191static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5192 switch (colorMode) {
5193 case ColorMode::DISPLAY_P3:
5194 case ColorMode::BT2100_PQ:
5195 case ColorMode::BT2100_HLG:
5196 case ColorMode::DISPLAY_BT2020:
5197 return Dataspace::DISPLAY_P3;
5198 default:
5199 return Dataspace::V0_SRGB;
5200 }
5201}
5202
5203const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5204 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5205 if (displayToken) {
5206 return getDisplayDeviceLocked(displayToken);
5207 }
5208 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5209 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005210 return getDisplayByLayerStack(displayOrLayerStack);
5211}
5212
5213const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005214 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005215 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005216 return display;
5217 }
5218 }
5219 return nullptr;
5220}
5221
5222status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5223 sp<GraphicBuffer>* outBuffer) {
5224 sp<DisplayDevice> display;
5225 uint32_t width;
5226 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005227 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005228 {
5229 Mutex::Autolock _l(mStateLock);
5230 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5231 if (!display) {
5232 return BAD_VALUE;
5233 }
5234
5235 width = uint32_t(display->getViewport().width());
5236 height = uint32_t(display->getViewport().height());
5237
Dominik Laskowski718f9602019-11-09 20:01:35 -08005238 const auto orientation = display->getOrientation();
5239 captureOrientation = ui::Transform::toRotationFlags(orientation);
5240
5241 switch (captureOrientation) {
5242 case ui::Transform::ROT_90:
5243 captureOrientation = ui::Transform::ROT_270;
5244 break;
5245
5246 case ui::Transform::ROT_270:
5247 captureOrientation = ui::Transform::ROT_90;
5248 break;
5249
5250 case ui::Transform::ROT_INVALID:
5251 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5252 captureOrientation = ui::Transform::ROT_0;
5253 break;
5254
5255 default:
5256 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005257 }
chaviw93df2ea2019-04-30 16:45:12 -07005258 *outDataspace =
5259 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5260 }
5261
5262 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5263 false /* captureSecureLayers */);
5264
5265 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5266 std::placeholders::_1);
5267 bool ignored = false;
5268 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5269 false /* useIdentityTransform */,
5270 ignored /* outCapturedSecureLayers */);
5271}
5272
Robert Carr866455f2019-04-02 16:28:26 -07005273status_t SurfaceFlinger::captureLayers(
5274 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5275 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5276 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5277 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005278 ATRACE_CALL();
5279
5280 class LayerRenderArea : public RenderArea {
5281 public:
Robert Carr578038f2018-03-09 12:25:24 -08005282 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005283 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005284 bool childrenOnly, const Rect& displayViewport)
5285 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005286 mLayer(layer),
5287 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005288 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005289 mFlinger(flinger),
5290 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005291 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005292 Rect getBounds() const override {
5293 const Layer::State& layerState(mLayer->getDrawingState());
5294 return mLayer->getBufferSize(layerState);
5295 }
Marissa Wall61c58622018-07-18 10:12:20 -07005296 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005297 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005298 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005299 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005300 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005301 }
chaviwa76b2712017-09-20 12:02:26 -07005302 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005303 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005304 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005305 Rect getSourceCrop() const override {
5306 if (mCrop.isEmpty()) {
5307 return getBounds();
5308 } else {
5309 return mCrop;
5310 }
5311 }
Robert Carr578038f2018-03-09 12:25:24 -08005312 class ReparentForDrawing {
5313 public:
5314 const sp<Layer>& oldParent;
5315 const sp<Layer>& newParent;
5316
Vishnu Nair4351ad52019-02-11 14:13:02 -08005317 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5318 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005319 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005320 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005321 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5322 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005323 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005324 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005325 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005326 };
5327
5328 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005329 const Rect sourceCrop = getSourceCrop();
5330 // no need to check rotation because there is none
5331 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5332 sourceCrop.height() != getReqHeight();
5333
Robert Carr578038f2018-03-09 12:25:24 -08005334 if (!mChildrenOnly) {
5335 mTransform = mLayer->getTransform().inverse();
5336 drawLayers();
5337 } else {
5338 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005339 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5340 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005341 // In the "childrenOnly" case we reparent the children to a screenshot
5342 // layer which has no properties set and which does not draw.
5343 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005344 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5345 "Screenshot Parent"s, w, h, 0,
5346 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005347
Vishnu Nair4351ad52019-02-11 14:13:02 -08005348 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005349 drawLayers();
5350 }
5351 }
chaviwa76b2712017-09-20 12:02:26 -07005352
chaviwa76b2712017-09-20 12:02:26 -07005353 private:
chaviw7206d492017-11-10 16:16:12 -08005354 const sp<Layer> mLayer;
5355 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005356
Peiyong Linefefaac2018-08-17 12:27:51 -07005357 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005358 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005359
5360 SurfaceFlinger* mFlinger;
5361 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005362 };
5363
Robert Carrc0df3122019-04-11 13:18:21 -07005364 int reqWidth = 0;
5365 int reqHeight = 0;
5366 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005367 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005368 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005369 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005370 {
5371 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005372
Robert Carrc0df3122019-04-11 13:18:21 -07005373 parent = fromHandle(layerHandleBinder);
5374 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5375 ALOGE("captureLayers called with an invalid or removed parent");
5376 return NAME_NOT_FOUND;
5377 }
5378
5379 const int uid = IPCThreadState::self()->getCallingUid();
5380 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5381 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5382 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5383 return PERMISSION_DENIED;
5384 }
5385
Vishnu Nairefc42e22019-12-03 17:36:12 -08005386 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005387 if (sourceCrop.width() <= 0) {
5388 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005389 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005390 }
5391
5392 if (sourceCrop.height() <= 0) {
5393 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005394 crop.bottom = parentSourceBounds.getHeight();
5395 }
5396
5397 if (crop.isEmpty() || frameScale <= 0.0f) {
5398 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5399 // crop was not specified, or an invalid frame scale was provided.
5400 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005401 }
5402 reqWidth = crop.width() * frameScale;
5403 reqHeight = crop.height() * frameScale;
5404
5405 for (const auto& handle : excludeHandles) {
5406 sp<Layer> excludeLayer = fromHandle(handle);
5407 if (excludeLayer != nullptr) {
5408 excludeLayers.emplace(excludeLayer);
5409 } else {
5410 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5411 return NAME_NOT_FOUND;
5412 }
5413 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005414
5415 auto display = getDisplayByLayerStack(parent->getLayerStack());
5416 if (!display) {
5417 return BAD_VALUE;
5418 }
5419
5420 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005421 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005422
Chia-I Wu20261cb2018-08-23 12:55:44 -07005423 // really small crop or frameScale
5424 if (reqWidth <= 0) {
5425 reqWidth = 1;
5426 }
5427 if (reqHeight <= 0) {
5428 reqHeight = 1;
5429 }
5430
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005431 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5432 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005433 auto traverseLayers = [parent, childrenOnly,
5434 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005435 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5436 if (!layer->isVisible()) {
5437 return;
Robert Carr578038f2018-03-09 12:25:24 -08005438 } else if (childrenOnly && layer == parent.get()) {
5439 return;
chaviwa76b2712017-09-20 12:02:26 -07005440 }
Robert Carr866455f2019-04-02 16:28:26 -07005441
5442 sp<Layer> p = layer;
5443 while (p != nullptr) {
5444 if (excludeLayers.count(p) != 0) {
5445 return;
5446 }
5447 p = p->getParent();
5448 }
5449
chaviwa76b2712017-09-20 12:02:26 -07005450 visitor(layer);
5451 });
5452 };
Robert Carr108b2c72019-04-02 16:32:58 -07005453
5454 bool outCapturedSecureLayers = false;
5455 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5456 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005457}
5458
5459status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5460 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005461 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005462 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005463 bool useIdentityTransform,
5464 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005465 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005466
Peiyong Lin0e003c92018-09-17 11:09:51 -07005467 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005468 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5469 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005470 *outBuffer =
5471 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5472 static_cast<android_pixel_format>(reqPixelFormat), 1,
5473 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005474
Robert Carr108b2c72019-04-02 16:32:58 -07005475 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5476 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005477}
5478
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005479status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5480 TraverseLayersFunction traverseLayers,
5481 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005482 bool useIdentityTransform,
5483 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484 // This mutex protects syncFd and captureResult for communication of the return values from the
5485 // main thread back to this Binder thread
5486 std::mutex captureMutex;
5487 std::condition_variable captureCondition;
5488 std::unique_lock<std::mutex> captureLock(captureMutex);
5489 int syncFd = -1;
5490 std::optional<status_t> captureResult;
5491
Robert Carr03480e22018-01-04 16:02:06 -08005492 const int uid = IPCThreadState::self()->getCallingUid();
5493 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5494
Dominik Laskowski8c001672018-05-30 16:52:06 -07005495 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 // If there is a refresh pending, bug out early and tell the binder thread to try again
5497 // after the refresh.
5498 if (mRefreshPending) {
5499 ATRACE_NAME("Skipping screenshot for now");
5500 std::unique_lock<std::mutex> captureLock(captureMutex);
5501 captureResult = std::make_optional<status_t>(EAGAIN);
5502 captureCondition.notify_one();
5503 return;
5504 }
5505
5506 status_t result = NO_ERROR;
5507 int fd = -1;
5508 {
5509 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005510 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005511 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005512 useIdentityTransform, forSystem, &fd,
5513 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005514 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005515 }
5516
5517 {
5518 std::unique_lock<std::mutex> captureLock(captureMutex);
5519 syncFd = fd;
5520 captureResult = std::make_optional<status_t>(result);
5521 captureCondition.notify_one();
5522 }
5523 });
5524
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005525 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005527 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005528 while (*captureResult == EAGAIN) {
5529 captureResult.reset();
5530 result = postMessageAsync(message);
5531 if (result != NO_ERROR) {
5532 return result;
5533 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005534 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005535 }
5536 result = *captureResult;
5537 }
5538
5539 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005540 sync_wait(syncFd, -1);
5541 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005542 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005543
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005544 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005545}
5546
chaviwa76b2712017-09-20 12:02:26 -07005547void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005548 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5550 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005551 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005552
chaviwa76b2712017-09-20 12:02:26 -07005553 const auto reqWidth = renderArea.getReqWidth();
5554 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005555 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005556 const auto transform = renderArea.getTransform();
5557 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005558 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005559
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005560 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005561 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005562
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005563 // assume that bounds are never offset, and that they are the same as the
5564 // buffer bounds.
5565 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005566 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005567 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005568
5569 // Now take into account the rotation flag. We append a transform that
5570 // rotates the layer stack about the origin, then translate by buffer
5571 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005572 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005573 int displacementX = 0;
5574 int displacementY = 0;
5575 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5576 switch (rotation) {
5577 case ui::Transform::ROT_90:
5578 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005579 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005580 break;
5581 case ui::Transform::ROT_180:
5582 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005583 displacementY = renderArea.getBounds().getWidth();
5584 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005585 break;
5586 case ui::Transform::ROT_270:
5587 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005588 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005589 break;
5590 default:
5591 break;
5592 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005593
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005594 // We need to transform the clipping window into the right spot.
5595 // First, rotate the clipping rectangle by the rotation hint to get the
5596 // right orientation
5597 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5598 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5599 const vec4 rotClipTL = rotMatrix * clipTL;
5600 const vec4 rotClipBR = rotMatrix * clipBR;
5601 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5602 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5603 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5604 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5605
5606 // Now reposition the clipping rectangle with the displacement vector
5607 // computed above.
5608 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005609 clientCompositionDisplay.clip =
5610 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5611 newClipRight + displacementX, newClipBottom + displacementY);
5612
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005613 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005614 clientCompositionDisplay.globalTransform =
5615 clipTransform * clientCompositionDisplay.globalTransform;
5616
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005617 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5618 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005619
chaviw50da5042018-04-09 13:49:37 -07005620 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005621
Vishnu Nair9b079a22020-01-21 14:36:08 -08005622 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005623 fillLayer.source.buffer.buffer = nullptr;
5624 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5625 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5626 fillLayer.alpha = half(alpha);
5627 clientCompositionLayers.push_back(fillLayer);
5628
5629 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005630 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005631 const bool supportProtectedContent = false;
5632 Region clip(renderArea.getBounds());
5633 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5634 clip,
5635 useIdentityTransform,
5636 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5637 renderArea.isSecure(),
5638 supportProtectedContent,
5639 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005640 displayViewport,
5641 clientCompositionDisplay.outputDataspace,
5642 true, /* realContentIsVisible */
5643 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005644 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005645 std::vector<compositionengine::LayerFE::LayerSettings> results =
5646 layer->prepareClientCompositionList(targetSettings);
5647 clientCompositionLayers.insert(clientCompositionLayers.end(),
5648 std::make_move_iterator(results.begin()),
5649 std::make_move_iterator(results.end()));
5650 results.clear();
5651
chaviwa76b2712017-09-20 12:02:26 -07005652 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005653
Vishnu Nair9b079a22020-01-21 14:36:08 -08005654 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5655 clientCompositionLayers.reserve(clientCompositionLayers.size());
5656 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5657 std::back_inserter(clientCompositionLayerPointers),
5658 [](compositionengine::LayerFE::LayerSettings& settings)
5659 -> renderengine::LayerSettings* { return &settings; });
5660
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005662 // Use an empty fence for the buffer fence, since we just created the buffer so
5663 // there is no need for synchronization with the GPU.
5664 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005665 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005666 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005667 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005668 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005669
5670 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005671}
5672
chaviwa76b2712017-09-20 12:02:26 -07005673status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5674 TraverseLayersFunction traverseLayers,
5675 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005676 bool useIdentityTransform, bool forSystem,
5677 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005678 ATRACE_CALL();
5679
chaviwa76b2712017-09-20 12:02:26 -07005680 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005681 outCapturedSecureLayers =
5682 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005683 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005684
Robert Carr03480e22018-01-04 16:02:06 -08005685 // We allow the system server to take screenshots of secure layers for
5686 // use in situations like the Screen-rotation animation and place
5687 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005688 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005689 ALOGW("FB is protected: PERMISSION_DENIED");
5690 return PERMISSION_DENIED;
5691 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005692 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005693 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005694}
5695
chaviw95ef3c42019-02-14 10:55:09 -08005696void SurfaceFlinger::setInputWindowsFinished() {
5697 Mutex::Autolock _l(mStateLock);
5698
5699 mPendingSyncInputWindows = false;
5700 mTransactionCV.broadcast();
5701}
chaviw5f21a5e2019-02-14 10:00:34 -08005702
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005703// ---------------------------------------------------------------------------
5704
Edgar Arriaga844fa672020-01-16 14:21:42 -08005705void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5706 layersSortedByZ.traverse(visitor);
5707}
5708
Dan Stoza412903f2017-04-27 13:42:17 -07005709void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5710 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005711}
5712
Dan Stoza412903f2017-04-27 13:42:17 -07005713void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5714 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005715}
5716
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005717void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005718 const LayerVector::Visitor& visitor) {
5719 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005720 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005721 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005722 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005723 continue;
5724 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005725 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005726 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005727 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005728 return;
5729 }
chaviwa76b2712017-09-20 12:02:26 -07005730 if (!layer->isVisible()) {
5731 return;
5732 }
5733 visitor(layer);
5734 });
5735 }
5736}
5737
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005738status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5739 HwcConfigIndexType defaultConfig,
5740 float minRefreshRate,
5741 float maxRefreshRate) {
5742 Mutex::Autolock lock(mStateLock);
5743
Dominik Laskowski22488f62019-03-28 09:53:04 -07005744 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005745 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5746 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5747 // it should go thru setDesiredActiveConfig, similar to primary display.
5748 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5749 const auto displayId = display->getId();
5750 LOG_ALWAYS_FATAL_IF(!displayId);
5751
5752 HWC2::VsyncPeriodChangeConstraints constraints;
5753 constraints.desiredTimeNanos = systemTime();
5754 constraints.seamlessRequired = false;
5755
5756 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005757 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5758 constraints, &timeline) < 0) {
5759 return BAD_VALUE;
5760 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005761 if (timeline.refreshRequired) {
5762 repaintEverythingForHWC();
5763 }
5764
Ady Abrahamdfa37362020-01-21 18:02:39 -08005765 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005766 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005767 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5768 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005769 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005770 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005771 }
5772
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005773 if (mDebugDisplayConfigSetByBackdoor) {
5774 // ignore this request as config is overridden by backdoor
5775 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005776 }
5777
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005778 bool policyChanged;
5779 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5780 &policyChanged) < 0) {
5781 return BAD_VALUE;
5782 }
5783 if (!policyChanged) {
5784 return NO_ERROR;
5785 }
5786
5787 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5788 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005789
5790 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5791 // that listeners that care about a change in allowed configs can get the notification.
5792 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005793 const nsecs_t vsyncPeriod =
5794 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005795 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005796 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005797
Ana Krulec3f6a2062020-01-23 15:48:01 -08005798 auto configId = mScheduler->getPreferredConfigId();
5799 auto preferredRefreshRate = configId
5800 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5801 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5802 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5803 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5804 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5805
5806 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5807 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5808 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005809 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005810 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005811 }
5812
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005813 return NO_ERROR;
5814}
5815
Ana Krulec0782b882019-10-15 17:34:54 -07005816status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005817 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005818 float maxRefreshRate) {
5819 ATRACE_CALL();
5820
5821 if (!displayToken) {
5822 return BAD_VALUE;
5823 }
5824
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005825 status_t result = NO_ERROR;
5826
Ana Krulec234bb162019-11-10 22:55:55 +01005827 postMessageSync(new LambdaMessage([&]() {
5828 const auto display = getDisplayDeviceLocked(displayToken);
5829 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005830 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005831 ALOGE("Attempt to set desired display configs for invalid display token %p",
5832 displayToken.get());
5833 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005834 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005835 ALOGW("Attempt to set desired display configs for virtual display");
5836 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005837 result =
5838 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5839 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005840 }
5841 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005842
5843 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005844}
5845
5846status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005847 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005848 float* outMinRefreshRate,
5849 float* outMaxRefreshRate) {
5850 ATRACE_CALL();
5851
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005852 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005853 return BAD_VALUE;
5854 }
5855
5856 Mutex::Autolock lock(mStateLock);
5857 const auto display = getDisplayDeviceLocked(displayToken);
5858 if (!display) {
5859 return NAME_NOT_FOUND;
5860 }
5861
5862 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005863 HwcConfigIndexType defaultConfig;
5864 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5865 *outDefaultConfig = defaultConfig.value();
5866 return NO_ERROR;
5867 } else if (display->isVirtual()) {
5868 return BAD_VALUE;
5869 } else {
5870 const auto displayId = display->getId();
5871 if (!displayId) {
5872 return BAD_VALUE;
5873 }
5874 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5875 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5876 *outMinRefreshRate = 1e9f / vsyncPeriod;
5877 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5878 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005879 }
Ana Krulec0782b882019-10-15 17:34:54 -07005880}
5881
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005882void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005883 mFlinger->setInputWindowsFinished();
5884}
5885
Robert Carrc0df3122019-04-11 13:18:21 -07005886sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005887 BBinder* b = nullptr;
5888 if (handle) {
5889 b = handle->localBinder();
5890 }
Robert Carrc0df3122019-04-11 13:18:21 -07005891 if (b == nullptr) {
5892 return nullptr;
5893 }
5894 auto it = mLayersByLocalBinderToken.find(b);
5895 if (it != mLayersByLocalBinderToken.end()) {
5896 return it->second.promote();
5897 }
5898 return nullptr;
5899}
5900
Dominik Laskowski75848362019-11-11 17:57:20 -08005901void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005902 mNumLayers++;
5903 mScheduler->registerLayer(layer);
5904}
5905
5906void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5907 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005908 removeFromOffscreenLayers(layer);
5909}
5910
5911// WARNING: ONLY CALL THIS FROM LAYER DTOR
5912// Here we add children in the current state to offscreen layers and remove the
5913// layer itself from the offscreen layer list. Since
5914// this is the dtor, it is safe to access the current state. This keeps us
5915// from dangling children layers such that they are not reachable from the
5916// Drawing state nor the offscreen layer list
5917// See b/141111965
5918void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5919 for (auto& child : layer->getCurrentChildren()) {
5920 mOffscreenLayers.emplace(child.get());
5921 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005922 mOffscreenLayers.erase(layer);
5923}
5924
Alec Mouri4545a8a2019-08-08 20:05:32 -07005925void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5926 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5927}
5928
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005929status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5930 float lightPosY, float lightPosZ,
5931 float lightRadius) {
5932 Mutex::Autolock _l(mStateLock);
5933 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5934 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5935 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5936 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5937 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5938
5939 // these values are overridden when calculating the shadow settings for a layer.
5940 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5941 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005942 return NO_ERROR;
5943}
5944
Lloyd Pique8d9f8362020-02-11 19:13:09 -08005945const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
5946 const {
5947 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
5948 // on the work to remove the table in that bug rather than adding more to
5949 // it.
5950 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
5951 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
5952 // supported, and exposed via the
5953 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
5954 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
5955 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
5956 };
5957 return genericLayerMetadataKeyMap;
5958}
5959
Steven Thomas62a4cf82020-01-31 12:04:03 -08005960status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
5961 int8_t compatibility) {
5962 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
5963 return BAD_VALUE;
5964 }
5965
5966 Mutex::Autolock lock(mStateLock);
5967 if (authenticateSurfaceTextureLocked(surface)) {
5968 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
5969 if (layer->setFrameRate(
5970 Layer::FrameRate(frameRate,
5971 Layer::FrameRate::convertCompatibility(compatibility)))) {
5972 setTransactionFlags(eTraversalNeeded);
5973 }
5974 } else {
5975 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
5976 return BAD_VALUE;
5977 }
5978 return NO_ERROR;
5979}
5980
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005981} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005982
Mathias Agopian3f844832013-08-07 21:24:32 -07005983#if defined(__gl_h_)
5984#error "don't include gl/gl.h in this file"
5985#endif
5986
5987#if defined(__gl2_h_)
5988#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005989#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005990
5991// TODO(b/129481165): remove the #pragma below and fix conversion issues
5992#pragma clang diagnostic pop // ignored "-Wconversion"