blob: cca2a709e709ea1a554f644a593c9b7e804d9d70 [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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070024#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080027
28#include <algorithm>
29#include <cinttypes>
30#include <cmath>
31#include <cstdint>
32#include <functional>
33#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070034#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080035#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080037#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070038#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070043
Lloyd Pique70d91362018-10-18 16:02:55 -070044#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080045#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070047#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquede196652020-01-22 17:29:58 -080048#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080049#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070050#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080052#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070054#include <gui/DebugEGLImageTracker.h>
55
Andy McFadden4803b742012-09-24 19:07:20 -070056#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070057#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080058#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080059#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080060#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070062#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070063#include <ui/ColorSpace.h>
64#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080065#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <ui/DisplayInfo.h>
67#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080068#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070069#include <ui/GraphicBufferAllocator.h>
70#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070071#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070073#include <utils/String16.h>
74#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070075#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080076#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopian921e6ac2012-07-23 23:11:29 -070079#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070080#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Robert Carr578038f2018-03-09 12:25:24 -080082#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070083#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070084#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020085#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080086#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020087#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080088#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080089#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070091#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080092#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070093#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070094#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070095#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070097#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080098
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700104#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700105#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700106#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700107#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700108#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700109#include "Scheduler/EventControlThread.h"
110#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700111#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700113#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800114#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115
Mathias Agopianff2ed702013-09-01 21:36:12 -0700116#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700117
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700118#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800119#include "android-base/stringprintf.h"
120
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800121#include <android/configuration.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800123#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
124#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700125#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900126#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127
chaviw1d044282017-09-27 12:19:28 -0700128#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700130
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700132
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700133using namespace std::string_literals;
134
Jaesoo Lee43518572017-01-23 19:03:16 +0900135using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900136using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900137using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800138
Ady Abraham8532d012019-05-08 14:50:56 -0700139using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800140using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700141using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700142using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800143using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700144using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700145using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900146
Steven Thomasb02664d2017-07-26 18:48:28 -0700147namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700148
149#pragma clang diagnostic push
150#pragma clang diagnostic error "-Wswitch-enum"
151
152bool isWideColorMode(const ColorMode colorMode) {
153 switch (colorMode) {
154 case ColorMode::DISPLAY_P3:
155 case ColorMode::ADOBE_RGB:
156 case ColorMode::DCI_P3:
157 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700158 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700159 case ColorMode::BT2100_PQ:
160 case ColorMode::BT2100_HLG:
161 return true;
162 case ColorMode::NATIVE:
163 case ColorMode::STANDARD_BT601_625:
164 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
165 case ColorMode::STANDARD_BT601_525:
166 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
167 case ColorMode::STANDARD_BT709:
168 case ColorMode::SRGB:
169 return false;
170 }
171 return false;
172}
173
174#pragma clang diagnostic pop
175
Steven Thomasb02664d2017-07-26 18:48:28 -0700176class ConditionalLock {
177public:
178 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
179 if (lock) {
180 mMutex.lock();
181 }
182 }
183 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
184private:
185 Mutex& mMutex;
186 bool mLocked;
187};
Peiyong Linfca547f2018-07-09 13:03:33 -0700188
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800189// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
190constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
191
192float getDensityFromProperty(const char* property, bool required) {
193 char value[PROPERTY_VALUE_MAX];
194 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
195 if (!density && required) {
196 ALOGE("%s must be defined as a build property", property);
197 return FALLBACK_DENSITY;
198 }
199 return density / 160.f;
200}
201
Peiyong Lin9d846a52018-11-05 13:18:20 -0800202// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
203bool validateCompositionDataspace(Dataspace dataspace) {
204 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
205}
206
Steven Thomasb02664d2017-07-26 18:48:28 -0700207} // namespace anonymous
208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800209// ---------------------------------------------------------------------------
210
Mathias Agopian99b49842011-06-27 16:05:52 -0700211const String16 sHardwareTest("android.permission.HARDWARE_TEST");
212const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
213const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
214const String16 sDump("android.permission.DUMP");
215
216// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700217int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700218bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800219uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800220bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800221bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800222int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600223bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800224ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700225bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700226bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700227Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
228ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
229Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
230ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700231
Kalle Raitaa099a242017-01-11 11:17:29 -0800232std::string getHwcServiceName() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.hwc_service_name", value, "default");
235 ALOGI("Using HWComposer service: '%s'", value);
236 return std::string(value);
237}
238
239bool useTrebleTestingOverride() {
240 char value[PROPERTY_VALUE_MAX] = {};
241 property_get("debug.sf.treble_testing_override", value, "false");
242 ALOGI("Treble testing override: '%s'", value);
243 return std::string(value) == "true";
244}
245
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
247 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Enhanced");
254 default:
255 return std::string("Unknown ") +
256 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258}
259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
263 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700265 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700266 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700268 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800269 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
270 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 mDefaultCompositionDataspace =
293 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700294 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
295 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 defaultCompositionDataspace = mDefaultCompositionDataspace;
297 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
298 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
299 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
300 wideColorGamutCompositionPixelFormat =
301 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700302
Yichi Chenda901bf2019-06-28 14:58:27 +0800303 mColorSpaceAgnosticDataspace =
304 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800307
Dominik Laskowski718f9602019-11-09 20:01:35 -0800308 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
309 switch (primary_display_orientation(Values::ORIENTATION_0)) {
310 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800312 case Values::ORIENTATION_90:
313 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_180:
316 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_270:
319 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
321 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800322 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800323
Sundong Ahn85131bd2019-02-18 15:51:53 +0900324 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 // debugging stuff...
327 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700328
Mathias Agopianb4b17302013-03-20 18:36:41 -0700329 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700330 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700331
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800332 property_get("debug.sf.showupdates", value, "0");
333 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700334
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700335 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000336
337 // DDMS debugging deprecated (b/120782499)
338 property_get("debug.sf.ddms", value, "0");
339 int debugDdms = atoi(value);
340 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700341
342 property_get("debug.sf.disable_backpressure", value, "0");
343 mPropagateBackpressure = !atoi(value);
344 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700345
Ady Abrahamadb9a992019-09-19 21:21:55 +0000346 property_get("debug.sf.enable_gl_backpressure", value, "0");
347 mPropagateBackpressureClientComposition = atoi(value);
348 ALOGI_IF(mPropagateBackpressureClientComposition,
349 "Enabling backpressure propagation for Client Composition");
350
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800351 property_get("debug.sf.enable_hwc_vds", value, "0");
352 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800353 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800354
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800355 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800356 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800357 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700358
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800359 property_get("ro.surface_flinger.supports_background_blur", value, "0");
360 bool supportsBlurs = atoi(value);
361 property_get("debug.sf.disableBlurs", value, "0");
362 bool disableBlurs = atoi(value);
363 mEnableBlurs = supportsBlurs && !disableBlurs;
364 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
365 disableBlurs);
366
Yiwei Zhang243b3782018-05-15 17:40:04 -0700367 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700368 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
369 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
370
Dan Stozaec460082018-12-17 15:35:09 -0800371 property_get("debug.sf.luma_sampling", value, "1");
372 mLumaSampling = atoi(value);
373
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800374 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800375 mDisableClientCompositionCache = atoi(value);
376
Romain Guy11d63f42017-07-20 12:47:14 -0700377 // We should be reading 'persist.sys.sf.color_saturation' here
378 // but since /data may be encrypted, we need to wait until after vold
379 // comes online to attempt to read the property. The property is
380 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800381
382 if (useTrebleTestingOverride()) {
383 // Without the override SurfaceFlinger cannot connect to HIDL
384 // services that are not listed in the manifests. Considered
385 // deriving the setting from the set service name, but it
386 // would be brittle if the name that's not 'default' is used
387 // for production purposes later on.
388 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
389 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390}
391
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800392void SurfaceFlinger::onFirstRef()
393{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800394 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395}
396
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700397SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398
Dan Stozac7014012014-02-14 15:03:43 -0800399void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400{
401 // the window manager died on us. prepare its eulogy.
402
Andy McFadden13a082e2012-08-24 10:16:42 -0700403 // restore initial conditions (default device unblank, etc)
404 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405
406 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700407 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408}
409
Robert Carr1db73f62016-12-21 12:58:51 -0800410static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700411 status_t err = client->initCheck();
412 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800413 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414 }
Robert Carr1db73f62016-12-21 12:58:51 -0800415 return nullptr;
416}
417
418sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
419 return initClient(new Client(this));
420}
421
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700422sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
423 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700424{
425 class DisplayToken : public BBinder {
426 sp<SurfaceFlinger> flinger;
427 virtual ~DisplayToken() {
428 // no more references, this display must be terminated
429 Mutex::Autolock _l(flinger->mStateLock);
430 flinger->mCurrentState.displays.removeItem(this);
431 flinger->setTransactionFlags(eDisplayTransactionNeeded);
432 }
433 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700434 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435 : flinger(flinger) {
436 }
437 };
438
439 sp<BBinder> token = new DisplayToken(this);
440
441 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700442 // Display ID is assigned when virtual display is allocated by HWC.
443 DisplayDeviceState state;
444 state.isSecure = secure;
445 state.displayName = displayName;
446 mCurrentState.displays.add(token, state);
447 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700448 return token;
449}
450
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700451void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 Mutex::Autolock _l(mStateLock);
453
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
455 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700456 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 return;
458 }
459
Dominik Laskowski075d3172018-05-24 15:50:06 -0700460 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
461 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 ALOGE("destroyDisplay called for non-virtual display");
463 return;
464 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 mInterceptor->saveDisplayDeletion(state.sequenceId);
466 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 setTransactionFlags(eDisplayTransactionNeeded);
468}
469
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800470std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
471 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473 const auto internalDisplayId = getInternalDisplayIdLocked();
474 if (!internalDisplayId) {
475 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 }
477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 std::vector<PhysicalDisplayId> displayIds;
479 displayIds.reserve(mPhysicalDisplayTokens.size());
480 displayIds.push_back(internalDisplayId->value);
481
482 for (const auto& [id, token] : mPhysicalDisplayTokens) {
483 if (id != *internalDisplayId) {
484 displayIds.push_back(id.value);
485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800488 return displayIds;
489}
490
491sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
492 Mutex::Autolock lock(mStateLock);
493 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494}
495
Ady Abraham37965d42018-11-01 13:43:32 -0700496status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
497 if (!outGetColorManagement) {
498 return BAD_VALUE;
499 }
500 *outGetColorManagement = useColorManagement;
501 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700502}
503
Lloyd Pique441d5042018-10-18 16:49:51 -0700504HWComposer& SurfaceFlinger::getHwComposer() const {
505 return mCompositionEngine->getHwComposer();
506}
507
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700508renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
509 return mCompositionEngine->getRenderEngine();
510}
511
Lloyd Pique70d91362018-10-18 16:02:55 -0700512compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
513 return *mCompositionEngine.get();
514}
515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516void SurfaceFlinger::bootFinished()
517{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700518 if (mStartPropertySetThread->join() != NO_ERROR) {
519 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521 const nsecs_t now = systemTime();
522 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000523 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700524
Mikael Pessa90092f42019-08-26 17:22:04 -0700525 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000526 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700527
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528 // wait patiently for the window manager death
529 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700530 mWindowManager = defaultServiceManager()->getService(name);
531 if (mWindowManager != 0) {
532 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 }
Robert Carr720e5062018-07-30 17:45:14 -0700534 sp<IBinder> input(defaultServiceManager()->getService(
535 String16("inputflinger")));
536 if (input == nullptr) {
537 ALOGE("Failed to link to input service");
538 } else {
539 mInputFlinger = interface_cast<IInputFlinger>(input);
540 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
Steven Thomas050b2c82017-03-06 11:45:16 -0800542 if (mVrFlinger) {
543 mVrFlinger->OnBootFinished();
544 }
545
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700547 // formerly we would just kill the process, but we now ask it to exit so it
548 // can choose where to stop the animation.
549 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700550
551 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
552 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
553 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700554
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 readPersistentProperties();
557 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558
Ady Abraham8a82ba62020-01-17 12:43:17 -0800559 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
560 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
561 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
562 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800563 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800564}
565
Dan Stoza436ccf32018-06-21 12:10:12 -0700566uint32_t SurfaceFlinger::getNewTexture() {
567 {
568 std::lock_guard lock(mTexturePoolMutex);
569 if (!mTexturePool.empty()) {
570 uint32_t name = mTexturePool.back();
571 mTexturePool.pop_back();
572 ATRACE_INT("TexturePoolSize", mTexturePool.size());
573 return name;
574 }
575
576 // The pool was too small, so increase it for the future
577 ++mTexturePoolSize;
578 }
579
580 // The pool was empty, so we need to get a new texture name directly using a
581 // blocking call to the main thread
582 uint32_t name = 0;
583 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
584 return name;
585}
586
Mathias Agopian3f844832013-08-07 21:24:32 -0700587void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700588 std::lock_guard lock(mTexturePoolMutex);
589 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
590 // to actually delete this or not based on mTexturePoolSize
591 mTexturePool.push_back(texture);
592 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700593}
594
Wei Wangf9b05ee2017-07-19 20:59:39 -0700595// Do not call property_set on main thread which will be blocked by init
596// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700598 ALOGI( "SurfaceFlinger's main thread ready to run. "
599 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800601
Steven Thomasb02664d2017-07-26 18:48:28 -0700602 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700603 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800604 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700605 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
606 renderengine::RenderEngineCreationArgs::Builder()
607 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
608 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
609 .setUseColorManagerment(useColorManagement)
610 .setEnableProtectedContext(enable_protected_contents(false))
611 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800612 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700613 .setContextPriority(useContextPriority
614 ? renderengine::RenderEngine::ContextPriority::HIGH
615 : renderengine::RenderEngine::ContextPriority::MEDIUM)
616 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800617 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700618
619 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
620 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700621 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
622 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800623 // Process any initial hotplug and resulting display changes.
624 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 const auto display = getDefaultDisplayDeviceLocked();
626 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700627 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700628 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800629
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700631 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700632 // This callback is called from the vr flinger dispatch thread. We
633 // need to call signalTransaction(), which requires holding
634 // mStateLock when we're not on the main thread. Acquiring
635 // mStateLock from the vr flinger dispatch thread might trigger a
636 // deadlock in surface flinger (see b/66916578), so post a message
637 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700639 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
640 mVrFlingerRequestsDisplay = requestDisplay;
641 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700642 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
645 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700646 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 .value_or(0),
648 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800649 if (!mVrFlinger) {
650 ALOGE("Failed to start vrflinger");
651 }
652 }
653
Mathias Agopian92a979a2012-08-02 18:32:23 -0700654 // initialize our drawing state
655 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700656
Andy McFadden13a082e2012-08-24 10:16:42 -0700657 // set initial conditions (e.g. unblank default device)
658 initializeDisplays();
659
Steven Thomas137d4bc2019-07-25 16:55:14 -0700660 char primeShaderCache[PROPERTY_VALUE_MAX];
661 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
662 if (atoi(primeShaderCache)) {
663 getRenderEngine().primeCache();
664 }
Dan Stoza4e637772016-07-28 13:31:51 -0700665
Wei Wangf9b05ee2017-07-19 20:59:39 -0700666 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700667
668 const bool presentFenceReliable =
669 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
670 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671
672 if (mStartPropertySetThread->Start() != NO_ERROR) {
673 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700677}
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700680 Mutex::Autolock _l(mStateLock);
681
Romain Guy11d63f42017-07-20 12:47:14 -0700682 char value[PROPERTY_VALUE_MAX];
683
684 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800685 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700686 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800687 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100688
689 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700690 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800691
692 property_get("persist.sys.sf.color_mode", value, "0");
693 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700694}
695
Mathias Agopiana67e4182012-06-19 17:26:12 -0700696void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Start boot animation service by setting a property mailbox
698 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800700 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700701 if (mStartPropertySetThread->join() != NO_ERROR) {
702 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800703 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700704}
705
Mathias Agopian875d8e12013-06-07 15:35:48 -0700706size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700707 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700708}
709
Mathias Agopian875d8e12013-06-07 15:35:48 -0700710size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700711 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700712}
713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800714// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800715
Jamie Gennis582270d2011-08-17 18:19:00 -0700716bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800717 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800718 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800719 return authenticateSurfaceTextureLocked(bufferProducer);
720}
721
722bool SurfaceFlinger::authenticateSurfaceTextureLocked(
723 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800724 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800725 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800726}
727
Brian Anderson6b376712017-04-04 10:51:39 -0700728status_t SurfaceFlinger::getSupportedFrameTimestamps(
729 std::vector<FrameEvent>* outSupported) const {
730 *outSupported = {
731 FrameEvent::REQUESTED_PRESENT,
732 FrameEvent::ACQUIRE,
733 FrameEvent::LATCH,
734 FrameEvent::FIRST_REFRESH_START,
735 FrameEvent::LAST_REFRESH_START,
736 FrameEvent::GPU_COMPOSITION_DONE,
737 FrameEvent::DEQUEUE_READY,
738 FrameEvent::RELEASE,
739 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700740 ConditionalLock _l(mStateLock,
741 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700742 if (!getHwComposer().hasCapability(
743 HWC2::Capability::PresentFenceIsNotReliable)) {
744 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
745 }
746 return NO_ERROR;
747}
748
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800749status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
750 if (!displayToken || !state) {
751 return BAD_VALUE;
752 }
753
754 Mutex::Autolock lock(mStateLock);
755
756 const auto display = getDisplayDeviceLocked(displayToken);
757 if (!display) {
758 return NAME_NOT_FOUND;
759 }
760
761 state->layerStack = display->getLayerStack();
762 state->orientation = display->getOrientation();
763
764 const Rect viewport = display->getViewport();
765 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
766
767 return NO_ERROR;
768}
769
770status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
771 if (!displayToken || !info) {
772 return BAD_VALUE;
773 }
774
775 Mutex::Autolock lock(mStateLock);
776
777 const auto display = getDisplayDeviceLocked(displayToken);
778 if (!display) {
779 return NAME_NOT_FOUND;
780 }
781
782 if (display->isVirtual()) {
783 return INVALID_OPERATION;
784 }
785
786 if (mEmulatedDisplayDensity) {
787 info->density = mEmulatedDisplayDensity;
788 } else {
789 info->density = display->isPrimary() ? mInternalDisplayDensity : FALLBACK_DENSITY;
790 }
791
792 info->secure = display->isSecure();
793
794 return NO_ERROR;
795}
796
Dominik Laskowski22488f62019-03-28 09:53:04 -0700797status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800798 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700799 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 return BAD_VALUE;
801 }
802
Dominik Laskowski22488f62019-03-28 09:53:04 -0700803 Mutex::Autolock lock(mStateLock);
804
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800805 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700806 if (!displayId) {
807 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700808 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800810 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700811
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700813
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800815 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700816
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800817 auto width = hwConfig->getWidth();
818 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700819
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800820 auto xDpi = hwConfig->getDpiX();
821 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700822
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 if (isInternal &&
824 (internalDisplayOrientation == ui::ROTATION_90 ||
825 internalDisplayOrientation == ui::ROTATION_270)) {
826 std::swap(width, height);
827 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 }
829
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800831
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800832 if (mEmulatedDisplayDensity) {
833 config.xDpi = mEmulatedDisplayDensity;
834 config.yDpi = mEmulatedDisplayDensity;
835 } else {
836 config.xDpi = xDpi;
837 config.yDpi = yDpi;
838 }
839
840 const nsecs_t period = hwConfig->getVsyncPeriod();
841 config.refreshRate = 1e9f / period;
842
843 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
844 config.appVsyncOffset = offsets.late.app;
845 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846
Andy McFadden91b2ca82014-06-13 14:04:23 -0700847 // This is how far in advance a buffer must be queued for
848 // presentation at a given time. If you want a buffer to appear
849 // on the screen at time N, you must submit the buffer before
850 // (N - presentationDeadline).
851 //
852 // Normally it's one full refresh period (to give SF a chance to
853 // latch the buffer), but this can be reduced by configuring a
854 // DispSync offset. Any additional delays introduced by the hardware
855 // composer or panel must be accounted for here.
856 //
857 // We add an additional 1ms to allow for processing time and
858 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800859 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700860
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800861 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700862 }
863
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 return NO_ERROR;
865}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700866
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700867status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
868 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 return BAD_VALUE;
870 }
871
Ana Krulecc2870422019-01-29 19:00:58 -0800872 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700873 return NO_ERROR;
874}
875
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
877 const auto display = getDisplayDevice(displayToken);
878 if (!display) {
879 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800880 return BAD_VALUE;
881 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700882
Steven Thomasc9098452019-09-30 17:15:05 -0700883 if (display->isPrimary()) {
884 std::lock_guard<std::mutex> lock(mActiveConfigLock);
885 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800886 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700887 }
Steven Thomasc9098452019-09-30 17:15:05 -0700888 }
Ady Abraham2139f732019-11-13 18:56:40 -0800889
890 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700891}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700892
Ady Abraham03b02dd2019-03-21 15:40:11 -0700893void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800894 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800895 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
896 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800897
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800898 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800899 // config twice. However event generation config might have changed so we need to update it
900 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800901 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700902 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
903 mDesiredActiveConfig = info;
904 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800905
906 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800907 // This will trigger HWC refresh without resetting the idle timer.
908 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700909 // Start receiving vsync samples now, so that we can detect a period
910 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800911 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700912 // As we called to set period, we will call to onRefreshRateChangeCompleted once
913 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700914 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800915
Ady Abraham9e16a482019-12-03 17:19:41 -0800916 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
917 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800918 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800919 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700920
921 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800922 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700923 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924}
925
926status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
927 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800928
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100929 if (!displayToken) {
930 return BAD_VALUE;
931 }
Ady Abraham838de062019-02-04 10:24:03 -0800932
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100933 status_t result = NO_ERROR;
934
935 postMessageSync(new LambdaMessage([&]() {
936 const auto display = getDisplayDeviceLocked(displayToken);
937 if (!display) {
938 ALOGE("Attempt to set allowed display configs for invalid display token %p",
939 displayToken.get());
940 result = BAD_VALUE;
941 } else if (display->isVirtual()) {
942 ALOGW("Attempt to set allowed display configs for virtual display");
943 result = BAD_VALUE;
944 } else {
945 HwcConfigIndexType config(mode);
946 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
947 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
948 refreshRate.fps);
949 }
950 }));
951
952 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953}
954
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955void SurfaceFlinger::setActiveConfigInternal() {
956 ATRACE_CALL();
957
Dominik Laskowski22488f62019-03-28 09:53:04 -0700958 const auto display = getDefaultDisplayDeviceLocked();
959 if (!display) {
960 return;
961 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962
Dominik Laskowski22488f62019-03-28 09:53:04 -0700963 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800964 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700965 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966 display->setActiveConfig(mUpcomingActiveConfig.configId);
967
Ady Abraham2139f732019-11-13 18:56:40 -0800968 auto refreshRate =
969 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800970 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
971 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800972 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700973
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800974 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700975 const nsecs_t vsyncPeriod =
976 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
977 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800978 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700979 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800980 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981}
982
Ady Abraham53852a52019-05-28 18:07:44 -0700983void SurfaceFlinger::desiredActiveConfigChangeDone() {
984 std::lock_guard<std::mutex> lock(mActiveConfigLock);
985 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
986 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700987
Kevin DuBois5988f482020-01-17 09:03:32 -0800988 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800989 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800990 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800991 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
992 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700993}
994
Dominik Laskowski22488f62019-03-28 09:53:04 -0700995bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800996 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800997 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800998 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700999 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001001 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002 return true;
1003 }
1004
1005 // We received the present fence from the HWC, so we assume it successfully updated
1006 // the config, hence we update SF.
1007 mCheckPendingFence = false;
1008 setActiveConfigInternal();
1009 }
1010
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011 // Store the local variable to release the lock.
1012 ActiveConfigInfo desiredActiveConfig;
1013 {
1014 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001015 if (!mDesiredActiveConfigChanged) {
1016 return false;
1017 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001018 desiredActiveConfig = mDesiredActiveConfig;
1019 }
1020
Ady Abraham2139f732019-11-13 18:56:40 -08001021 auto refreshRate =
1022 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1023 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1024 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001025 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1027 // display is not valid or we are already in the requested mode
1028 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001029 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032
Ady Abraham838de062019-02-04 10:24:03 -08001033 // Desired active config was set, it is different than the config currently in use, however
1034 // allowed configs might have change by the time we process the refresh.
1035 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001036 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001037 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001038 return false;
1039 }
Alec Mouri7f015182019-07-11 13:56:22 -07001040
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 mUpcomingActiveConfig = desiredActiveConfig;
1042 const auto displayId = display->getId();
1043 LOG_ALWAYS_FATAL_IF(!displayId);
1044
Ady Abraham2139f732019-11-13 18:56:40 -08001045 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001047 // TODO(b/142753666) use constrains
1048 HWC2::VsyncPeriodChangeConstraints constraints;
1049 constraints.desiredTimeNanos = systemTime();
1050 constraints.seamlessRequired = false;
1051
1052 HWC2::VsyncPeriodChangeTimeline outTimeline;
1053 auto status =
1054 getHwComposer().setActiveConfigWithConstraints(*displayId,
1055 mUpcomingActiveConfig.configId.value(),
1056 constraints, &outTimeline);
1057 if (status != NO_ERROR) {
1058 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1059 return false;
1060 }
1061
1062 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1063 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001064 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001066}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1069 Vector<ColorMode>* outColorModes) {
1070 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001071 return BAD_VALUE;
1072 }
1073
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001075 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001076 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001077 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1078
1079 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1080 if (!displayId) {
1081 return NAME_NOT_FOUND;
1082 }
1083
Dominik Laskowski075d3172018-05-24 15:50:06 -07001084 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001085 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001086 }
Michael Wright28f24d02016-07-12 13:30:53 -07001087 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001088
1089 // If it's built-in display and the configuration claims it's not wide color capable,
1090 // filter out all wide color modes. The typical reason why this happens is that the
1091 // hardware is not good enough to support GPU composition of wide color, and thus the
1092 // OEMs choose to disable this capability.
1093 if (isInternalDisplay && !hasWideColorDisplay) {
1094 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1095 isWideColorMode);
1096 } else {
1097 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1098 }
Michael Wright28f24d02016-07-12 13:30:53 -07001099
1100 return NO_ERROR;
1101}
1102
Daniel Solomon42d04562019-01-20 21:03:19 -08001103status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1104 ui::DisplayPrimaries &primaries) {
1105 if (!displayToken) {
1106 return BAD_VALUE;
1107 }
1108
1109 // Currently we only support this API for a single internal display.
1110 if (getInternalDisplayToken() != displayToken) {
1111 return BAD_VALUE;
1112 }
1113
1114 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1115 return NO_ERROR;
1116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1119 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001120 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001121 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001122 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001123}
1124
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127 Vector<ColorMode> modes;
1128 getDisplayColorModes(displayToken, &modes);
1129 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1130 if (mode < ColorMode::NATIVE || !exists) {
1131 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1132 decodeColorMode(mode).c_str(), mode, displayToken.get());
1133 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001134 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const auto display = getDisplayDevice(displayToken);
1136 if (!display) {
1137 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1138 decodeColorMode(mode).c_str(), mode, displayToken.get());
1139 } else if (display->isVirtual()) {
1140 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1141 decodeColorMode(mode).c_str(), mode);
1142 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001143 display->getCompositionDisplay()->setColorProfile(
1144 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1145 RenderIntent::COLORIMETRIC,
1146 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 }
1148 }));
1149
Michael Wright28f24d02016-07-12 13:30:53 -07001150 return NO_ERROR;
1151}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001152
Galia Peycheva5492cb52019-10-30 14:13:16 +01001153status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1154 bool* outSupport) const {
1155 Mutex::Autolock _l(mStateLock);
1156
1157 if (!displayToken) {
1158 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1159 return BAD_VALUE;
1160 }
1161 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1162 if (!displayId) {
1163 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1164 displayToken.get());
1165 return NAME_NOT_FOUND;
1166 }
1167 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1168 HWC2::DisplayCapability::AutoLowLatencyMode);
1169 return NO_ERROR;
1170}
1171
1172void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1173 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1174}
1175
1176void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1177 if (!displayToken) {
1178 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1179 return;
1180 }
1181 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1182 if (!displayId) {
1183 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1184 displayToken.get());
1185 return;
1186 }
1187
1188 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1189}
1190
1191status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1192 bool* outSupport) const {
1193 Mutex::Autolock _l(mStateLock);
1194
1195 if (!displayToken) {
1196 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1197 return BAD_VALUE;
1198 }
1199 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1200 if (!displayId) {
1201 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1202 displayToken.get());
1203 return NAME_NOT_FOUND;
1204 }
1205
1206 std::vector<HWC2::ContentType> outSupportedContentTypes;
1207 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1208 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1209 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1210 return NO_ERROR;
1211}
1212
1213void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1214 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1215}
1216
1217void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1218 if (!displayToken) {
1219 ALOGE("setGameContentType() failed. Missing display token.");
1220 return;
1221 }
1222 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1223 if (!displayId) {
1224 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1225 displayToken.get());
1226 return;
1227 }
1228
1229 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1230 getHwComposer().setContentType(*displayId, type);
1231}
1232
Svetoslavd85084b2014-03-20 10:28:31 -07001233status_t SurfaceFlinger::clearAnimationFrameStats() {
1234 Mutex::Autolock _l(mStateLock);
1235 mAnimFrameTracker.clearStats();
1236 return NO_ERROR;
1237}
1238
1239status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1240 Mutex::Autolock _l(mStateLock);
1241 mAnimFrameTracker.getStats(outStats);
1242 return NO_ERROR;
1243}
1244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001245status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1246 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001247 Mutex::Autolock _l(mStateLock);
1248
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001249 const auto display = getDisplayDeviceLocked(displayToken);
1250 if (!display) {
1251 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001252 return BAD_VALUE;
1253 }
1254
Peiyong Linfb069302018-04-25 14:34:31 -07001255 // At this point the DisplayDeivce should already be set up,
1256 // meaning the luminance information is already queried from
1257 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001258 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001259 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1260 capabilities.getDesiredMaxLuminance(),
1261 capabilities.getDesiredMaxAverageLuminance(),
1262 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001263
1264 return NO_ERROR;
1265}
1266
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001267status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1268 ui::PixelFormat* outFormat,
1269 ui::Dataspace* outDataspace,
1270 uint8_t* outComponentMask) const {
1271 if (!outFormat || !outDataspace || !outComponentMask) {
1272 return BAD_VALUE;
1273 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001274 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001275 if (!display || !display->getId()) {
1276 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1277 return BAD_VALUE;
1278 }
1279 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1280 outDataspace, outComponentMask);
1281}
1282
Kevin DuBois74e53772018-11-19 10:52:38 -08001283status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1284 bool enable, uint8_t componentMask,
1285 uint64_t maxFrames) const {
1286 const auto display = getDisplayDevice(displayToken);
1287 if (!display || !display->getId()) {
1288 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1289 return BAD_VALUE;
1290 }
1291
1292 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1293 componentMask, maxFrames);
1294}
1295
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001296status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1297 uint64_t maxFrames, uint64_t timestamp,
1298 DisplayedFrameStats* outStats) const {
1299 const auto display = getDisplayDevice(displayToken);
1300 if (!display || !display->getId()) {
1301 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1302 return BAD_VALUE;
1303 }
1304
1305 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1306 outStats);
1307}
1308
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001309status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1310 if (!outSupported) {
1311 return BAD_VALUE;
1312 }
1313 *outSupported = getRenderEngine().supportsProtectedContent();
1314 return NO_ERROR;
1315}
1316
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001317status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1318 bool* outIsWideColorDisplay) const {
1319 if (!displayToken || !outIsWideColorDisplay) {
1320 return BAD_VALUE;
1321 }
1322 Mutex::Autolock _l(mStateLock);
1323 const auto display = getDisplayDeviceLocked(displayToken);
1324 if (!display) {
1325 return BAD_VALUE;
1326 }
Peiyong Linff84a152019-05-17 18:36:19 -07001327
1328 // Use hasWideColorDisplay to override built-in display.
1329 const auto displayId = display->getId();
1330 if (displayId && displayId == getInternalDisplayIdLocked()) {
1331 *outIsWideColorDisplay = hasWideColorDisplay;
1332 return NO_ERROR;
1333 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001334 *outIsWideColorDisplay = display->hasWideColorGamut();
1335 return NO_ERROR;
1336}
1337
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001338status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001339 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001340 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001341
Dominik Laskowski6505f792019-09-18 11:10:05 -07001342 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1343 mEventQueue->setEventConnection(
1344 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001345 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001346 }));
1347
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001348 return NO_ERROR;
1349}
1350
1351status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001352 Mutex::Autolock lock(mStateLock);
1353 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001354}
1355
Lloyd Pique755e3192018-01-31 16:46:15 -08001356status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1357 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001358 // Try to acquire a lock for 1s, fail gracefully
1359 const status_t err = mStateLock.timedLock(s2ns(1));
1360 const bool locked = (err == NO_ERROR);
1361 if (!locked) {
1362 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1363 return TIMED_OUT;
1364 }
1365
1366 outLayers->clear();
1367 mCurrentState.traverseInZOrder([&](Layer* layer) {
1368 outLayers->push_back(layer->getLayerDebugInfo());
1369 });
1370
1371 mStateLock.unlock();
1372 return NO_ERROR;
1373}
1374
Peiyong Linc6780972018-10-28 15:24:08 -07001375status_t SurfaceFlinger::getCompositionPreference(
1376 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1377 Dataspace* outWideColorGamutDataspace,
1378 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001379 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001380 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001381 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001382 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001383 return NO_ERROR;
1384}
1385
Dan Stozaec460082018-12-17 15:35:09 -08001386status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1387 const sp<IBinder>& stopLayerHandle,
1388 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001389 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001390 return BAD_VALUE;
1391 }
1392 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001393 return NO_ERROR;
1394}
1395
Dan Stozaec460082018-12-17 15:35:09 -08001396status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001397 if (!listener) {
1398 return BAD_VALUE;
1399 }
Dan Stozaec460082018-12-17 15:35:09 -08001400 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001401 return NO_ERROR;
1402}
Dan Gittik57e63c52019-01-18 16:37:54 +00001403
1404status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1405 bool* outSupport) const {
1406 if (!displayToken || !outSupport) {
1407 return BAD_VALUE;
1408 }
1409 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1410 if (!displayId) {
1411 return NAME_NOT_FOUND;
1412 }
1413 *outSupport =
1414 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1415 return NO_ERROR;
1416}
1417
1418status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1419 float brightness) const {
1420 if (!displayToken) {
1421 return BAD_VALUE;
1422 }
1423 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1424 if (!displayId) {
1425 return NAME_NOT_FOUND;
1426 }
1427 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1428}
1429
Ady Abraham8532d012019-05-08 14:50:56 -07001430status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1431 PowerHint powerHint = static_cast<PowerHint>(hintId);
1432
1433 if (powerHint == PowerHint::INTERACTION) {
1434 mScheduler->notifyTouchEvent();
1435 }
1436
1437 return NO_ERROR;
1438}
1439
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001440// ----------------------------------------------------------------------------
1441
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001442sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001443 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001444 const auto& handle =
1445 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001446
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001447 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001448}
1449
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001450// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001451
1452void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001453 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454}
1455
1456void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001457 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001458 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459}
1460
1461void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001462 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001463 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001464}
1465
1466void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001467 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001468 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001469}
1470
1471status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001472 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001473 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001474}
1475
1476status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001477 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001478 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001479 if (res == NO_ERROR) {
1480 msg->wait();
1481 }
1482 return res;
1483}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001484
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001485void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001486 do {
1487 waitForEvent();
1488 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001489}
1490
Dominik Laskowski83b88212018-12-11 13:34:06 -08001491nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001492 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001493 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1494 return 0;
1495 }
1496
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001497 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001498}
1499
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001500void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001501 int64_t timestamp,
1502 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001503 ATRACE_NAME("SF onVsync");
1504
Ady Abraham7159f572019-10-11 11:10:18 -07001505 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1506
Steven Thomas3cfac282017-02-06 12:29:30 -08001507 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001509 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 return;
1511 }
1512
Dominik Laskowski075d3172018-05-24 15:50:06 -07001513 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001514 return;
1515 }
1516
Dominik Laskowski075d3172018-05-24 15:50:06 -07001517 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001518 // For now, we don't do anything with external display vsyncs.
1519 return;
1520 }
1521
Alec Mourif8e689c2019-05-20 18:32:22 -07001522 bool periodFlushed = false;
1523 mScheduler->addResyncSample(timestamp, &periodFlushed);
1524 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001525 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001526 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001527}
1528
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001529void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001530 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1531 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532}
1533
Ady Abraham2139f732019-11-13 18:56:40 -08001534bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001535 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001536}
1537
Ady Abraham2139f732019-11-13 18:56:40 -08001538void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1539 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001540 const auto display = getDefaultDisplayDeviceLocked();
1541 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001542 return;
1543 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001544 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001545
Ana Krulec7d1d6832018-12-27 11:10:09 -08001546 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001547 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1548 ALOGV("Skipping config %d as it is not part of allowed configs",
1549 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001550 return;
1551 }
1552
Ady Abraham2139f732019-11-13 18:56:40 -08001553 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001554}
1555
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001556void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001557 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001558 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001559 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560
Lloyd Piqueba04e622017-12-14 17:11:26 -08001561 // Ignore events that do not have the right sequenceId.
1562 if (sequenceId != getBE().mComposerSequenceId) {
1563 return;
1564 }
1565
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 // Only lock if we're not on the main thread. This function is normally
1567 // called on a hwbinder thread, but for the primary display it's called on
1568 // the main thread with the state lock already held, so don't attempt to
1569 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001570 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001571
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001572 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001573
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001574 if (std::this_thread::get_id() == mMainThreadId) {
1575 // Process all pending hot plug events immediately if we are on the main thread.
1576 processDisplayHotplugEventsLocked();
1577 }
1578
Lloyd Piqueba04e622017-12-14 17:11:26 -08001579 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001580}
1581
Ady Abraham7159f572019-10-11 11:10:18 -07001582void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001583 int32_t sequenceId, hwc2_display_t /*display*/,
1584 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1585 Mutex::Autolock lock(mStateLock);
1586 if (sequenceId != getBE().mComposerSequenceId) {
1587 return;
1588 }
1589 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001590}
1591
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001592void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1593 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1594 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1595}
1596
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001597void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001598 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001599 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001600 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001601 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001602 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001603}
1604
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001605void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001606 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001607
1608 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1609 // display power state.
1610 postMessageAsync(new LambdaMessage(
1611 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1612}
1613
1614void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1615 ATRACE_CALL();
1616
Ady Abraham27c70212019-06-11 10:52:26 -07001617 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1618
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001619 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001620 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1621 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001622 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001623 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001624 }
Mathias Agopian86303202012-07-24 22:46:10 -07001625}
1626
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001627// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001628void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001629 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630 // Clear the drawing state so that the logic inside of
1631 // handleTransactionLocked will fire. It will determine the delta between
1632 // mCurrentState and mDrawingState and re-apply all changes when we make the
1633 // transition.
1634 mDrawingState.displays.clear();
1635 mDisplays.clear();
1636}
1637
Steven Thomas050b2c82017-03-06 11:45:16 -08001638void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001639 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001640 if (!mVrFlinger)
1641 return;
1642 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001643 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001644 return;
1645 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001646
Lloyd Pique441d5042018-10-18 16:49:51 -07001647 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001648 ALOGE("Vr flinger is only supported for remote hardware composer"
1649 " service connections. Ignoring request to transition to vr"
1650 " flinger.");
1651 mVrFlingerRequestsDisplay = false;
1652 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001653 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001654
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001655 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001656
Steven Thomas0123ac62018-07-12 11:32:34 -07001657 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001658 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001659
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001660 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001661
1662 // Clear out all the output layers from the composition engine for all
1663 // displays before destroying the hardware composer interface. This ensures
1664 // any HWC layers are destroyed through that interface before it becomes
1665 // invalid.
1666 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001667 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001668 }
1669
Steven Thomas0123ac62018-07-12 11:32:34 -07001670 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1671 // called below. Clear the reference now so we don't accidentally use it
1672 // later.
1673 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001674
Steven Thomasb02664d2017-07-26 18:48:28 -07001675 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001678
Steven Thomasb02664d2017-07-26 18:48:28 -07001679 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001680 // Delete the current instance before creating the new one
1681 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1682 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1683 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1684 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685
Lloyd Pique441d5042018-10-18 16:49:51 -07001686 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001687 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001688
1689 if (vrFlingerRequestsDisplay) {
1690 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001691 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001692
1693 mVisibleRegionsDirty = true;
1694 invalidateHwcGeometry();
1695
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001696 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001697 display = getDefaultDisplayDeviceLocked();
1698 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001699 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001700
Steven Thomasb02664d2017-07-26 18:48:28 -07001701 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001702 const nsecs_t vsyncPeriod = getVsyncPeriod();
1703 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001704
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001705 // The present fences returned from vr_hwc are not an accurate
1706 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001707 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001708
Steven Thomasb02664d2017-07-26 18:48:28 -07001709 // Use phase of 0 since phase is not known.
1710 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001711 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001712 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001713
Ana Krulecc2870422019-01-29 19:00:58 -08001714 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001715
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001716 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001718}
1719
Ady Abraham11579302019-09-19 12:35:58 -07001720bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1721 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001722 // We are storing the last 2 present fences. If sf's phase offset is to be
1723 // woken up before the actual vsync but targeting the next vsync, we need to check
1724 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001725 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1726 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001727
Ady Abraham11579302019-09-19 12:35:58 -07001728 if (fence == Fence::NO_FENCE) {
1729 return false;
1730 }
1731
1732 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1733 fence->wait(graceTimeMs);
1734 }
1735
1736 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001737}
1738
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001739void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001740 DisplayStatInfo stats;
1741 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001742 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001743 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001744 mExpectedPresentTime.store(
1745 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001746}
1747
Dominik Laskowski22488f62019-03-28 09:53:04 -07001748void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001749 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001750 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001751 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001752 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001753 // calculate the expected present time once and use the cached
1754 // value throughout this frame to make sure all layers are
1755 // seeing this same value.
1756 populateExpectedPresentTime();
1757
Ady Abraham11579302019-09-19 12:35:58 -07001758 // When Backpressure propagation is enabled we want to give a small grace period
1759 // for the present fence to fire instead of just giving up on this frame to handle cases
1760 // where present fence is just about to get signaled.
1761 const int graceTimeForPresentFenceMs =
1762 (mPropagateBackpressure &&
1763 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1764 ? 1
1765 : 0;
1766 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1767 previousFrameMissed(
1768 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001769 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1770 mHadDeviceComposition && frameMissed};
1771 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1772 mHadClientComposition && frameMissed};
1773
Alec Mouricc0fc602019-02-26 21:45:19 -08001774 if (frameMissed) {
1775 mFrameMissedCount++;
1776 mTimeStats->incrementMissedFrames();
1777 }
1778
Alec Mouri40189b02019-03-05 15:07:54 -08001779 if (hwcFrameMissed) {
1780 mHwcFrameMissedCount++;
1781 }
1782
1783 if (gpuFrameMissed) {
1784 mGpuFrameMissedCount++;
1785 }
1786
Ady Abrahamadb9a992019-09-19 21:21:55 +00001787 if (frameMissed && mPropagateBackpressure) {
1788 if ((hwcFrameMissed && !gpuFrameMissed) ||
1789 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001790 signalLayerUpdate();
1791 break;
1792 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001793 }
Dan Stoza50182882016-07-08 12:02:20 -07001794
Steven Thomas050b2c82017-03-06 11:45:16 -08001795 // Now that we're going to make it to the handleMessageTransaction()
1796 // call below it's safe to call updateVrFlinger(), which will
1797 // potentially trigger a display handoff.
1798 updateVrFlinger();
1799
Dan Stoza6b9454d2014-11-07 16:00:59 -08001800 bool refreshNeeded = handleMessageTransaction();
1801 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001802
Ana Krulecc84d09b2019-11-02 23:10:29 +01001803 // Layers need to get updated (in the previous line) before we can use them for
1804 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001805 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1806 // and may eventually call to ~Layer() if it holds the last reference
1807 {
1808 Mutex::Autolock _l(mStateLock);
1809 mScheduler->chooseRefreshRateForContent();
1810 }
1811
Ana Krulecc84d09b2019-11-02 23:10:29 +01001812 if (performSetActiveConfig()) {
1813 break;
1814 }
1815
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001816 updateCursorAsync();
1817 updateInputFlinger();
1818
Dan Stoza58784442014-12-02 16:58:17 -08001819 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001820 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001821 // Signal a refresh if a transaction modified the window state,
1822 // a new buffer was latched, or if HWC has requested a full
1823 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001824 if (mFrameStartTime <= 0) {
1825 // We should only use the time of the first invalidate
1826 // message that signals a refresh as the beginning of the
1827 // frame. Otherwise the real frame time will be
1828 // underestimated.
1829 mFrameStartTime = frameStart;
1830 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001831 signalRefresh();
1832 }
1833 break;
1834 }
1835 case MessageQueue::REFRESH: {
1836 handleMessageRefresh();
1837 break;
1838 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001839 }
1840}
1841
Dan Stoza6b9454d2014-11-07 16:00:59 -08001842bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001843 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001844 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001845
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001846 bool flushedATransaction = flushTransactionQueues();
1847
1848 bool runHandleTransaction = transactionFlags &&
1849 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1850
1851 if (runHandleTransaction) {
1852 handleTransaction(eTransactionMask);
1853 } else {
1854 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001855 }
1856
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001857 if (transactionFlushNeeded()) {
1858 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001859 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001860
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001861 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001862}
1863
Mathias Agopian4fec8732012-06-29 14:12:52 -07001864void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001865 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001866
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001867 mRefreshPending = false;
1868
Lloyd Piqueab039b52019-02-13 14:22:42 -08001869 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001870 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001871 for (const auto& [_, display] : mDisplays) {
1872 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1873 }
1874 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001875 if (auto layerFE = layer->getCompositionEngineLayerFE())
1876 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001877 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001878 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1879 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001880 if (auto layerFE = layer->getCompositionEngineLayerFE())
1881 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001882 }
1883
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001884 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001885 refreshArgs.outputColorSetting = useColorManagement
1886 ? mDisplayColorSetting
1887 : compositionengine::OutputColorSetting::kUnmanaged;
1888 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1889 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001890
1891 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1892 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001893
1894 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1895 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1896 mDrawingState.colorMatrixChanged = false;
1897 }
1898
1899 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1900
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001901 if (mDebugRegion != 0) {
1902 refreshArgs.devOptFlashDirtyRegionsDelay =
1903 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1904 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001905
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001906 mGeometryInvalid = false;
1907
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001908 // Store the present time just before calling to the composition engine so we could notify
1909 // the scheduler.
1910 const auto presentTime = systemTime();
1911
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001912 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001913 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1914 // Reset the frame start time now that we've recorded this frame.
1915 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001916
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001917 mScheduler->onDisplayRefreshed(presentTime);
1918
David Sodmanfa9b2af2017-12-24 13:28:59 -08001919 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001920 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001921
Lloyd Pique66d68602019-02-13 14:23:31 -08001922 mHadClientComposition =
1923 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1924 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001925 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1926 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001927 });
1928 mHadDeviceComposition =
1929 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1930 auto& displayDevice = tokenDisplayPair.second;
1931 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1932 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001933 mReusedClientComposition =
1934 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1935 auto& displayDevice = tokenDisplayPair.second;
1936 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1937 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001938
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001939 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001940
David Sodman7e4ae112018-02-09 15:02:28 -08001941 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001942 if (mVisibleRegionsDirty) {
1943 mVisibleRegionsDirty = false;
1944 if (mTracingEnabled) {
1945 mTracing.notify("visibleRegionsDirty");
1946 }
1947 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001948
1949 if (mCompositionEngine->needsAnotherUpdate()) {
1950 signalLayerUpdate();
1951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001953
David Sodmanfa9b2af2017-12-24 13:28:59 -08001954
1955bool SurfaceFlinger::handleMessageInvalidate() {
1956 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001957 bool refreshNeeded = handlePageFlip();
1958
Vishnu Nair4351ad52019-02-11 14:13:02 -08001959 if (mVisibleRegionsDirty) {
1960 computeLayerBounds();
1961 }
1962
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001963 for (auto& layer : mLayersPendingRefresh) {
1964 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001965 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001966 invalidateLayerStack(layer, visibleReg);
1967 }
1968 mLayersPendingRefresh.clear();
1969 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001970}
1971
Ana Krulece588e312018-09-18 12:32:24 -07001972void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1973 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974 // Update queue of past composite+present times and determine the
1975 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001976 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001978 while (!getBE().mCompositePresentTimes.empty()) {
1979 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980 // Cached values should have been updated before calling this method,
1981 // which helps avoid duplicate syscalls.
1982 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1983 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1984 break;
1985 }
1986 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001987 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988 }
1989
1990 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001991 while (getBE().mCompositePresentTimes.size() > 16) {
1992 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001993 }
1994
Ana Krulece588e312018-09-18 12:32:24 -07001995 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001996}
1997
Ana Krulece588e312018-09-18 12:32:24 -07001998void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1999 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002000 // Integer division and modulo round toward 0 not -inf, so we need to
2001 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002002 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2003 ? (stats.vsyncPeriod -
2004 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2005 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002006
Ady Abraham9e16a482019-12-03 17:19:41 -08002007 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002008 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002009 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002010 }
2011
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002012 // Snap the latency to a value that removes scheduling jitter from the
2013 // composition and present times, which often have >1ms of jitter.
2014 // Reducing jitter is important if an app attempts to extrapolate
2015 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002016 // Snapping also allows an app to precisely calculate
2017 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002018 nsecs_t bias = stats.vsyncPeriod / 2;
2019 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2020 nsecs_t snappedCompositeToPresentLatency =
2021 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002022
David Sodman99974d22017-11-28 12:04:33 -08002023 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002024 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2025 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002026 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002027}
2028
David Sodman2b406362017-12-15 13:33:47 -08002029void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002030{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 ATRACE_CALL();
2032 ALOGV("postComposition");
2033
Brian Andersonf6386862016-10-31 16:34:13 -07002034 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002035 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002036 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002037 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002038 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002039 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040
David Sodman73beded2017-11-15 11:56:06 -08002041 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002042 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002043 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002044 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002045 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2046 ->getRenderSurface()
2047 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002048 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002049 } else {
2050 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2051 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002052
David Sodman73beded2017-11-15 11:56:06 -08002053 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002054 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2055 mPreviousPresentFences[0] = displayDevice
2056 ? getHwComposer().getPresentFence(*displayDevice->getId())
2057 : Fence::NO_FENCE;
2058 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002059 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002060
Ana Krulece588e312018-09-18 12:32:24 -07002061 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002062 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063
Lloyd Piqueab039b52019-02-13 14:22:42 -08002064 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2065 // be sampled a little later than when we started doing work for this frame,
2066 // but that should be okay since updateCompositorTiming has snapping logic.
2067 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2068 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002069 CompositorTiming compositorTiming;
2070 {
David Sodman99974d22017-11-28 12:04:33 -08002071 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2072 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002073 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002074
Edgar Arriaga844fa672020-01-16 14:21:42 -08002075 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002076 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2077 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002078 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002079 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002080 }
Robert Carr2047fae2016-11-28 14:09:09 -08002081 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002083 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002084 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002085 }
2086
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002087 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002088 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2089 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002090 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002091 }
2092 }
2093
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002094 if (mAnimCompositionPending) {
2095 mAnimCompositionPending = false;
2096
Brian Anderson4e606e32017-03-16 15:34:57 -07002097 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002098 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002099 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002100 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002101 // The HWC doesn't support present fences, so use the refresh
2102 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002103 const nsecs_t presentTime =
2104 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002105 mAnimFrameTracker.setActualPresentTime(presentTime);
2106 }
2107 mAnimFrameTracker.advanceFrame();
2108 }
Dan Stozab90cf072015-03-05 11:05:59 -08002109
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002110 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002111 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002112 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002113 }
2114
Vishnu Nair9b079a22020-01-21 14:36:08 -08002115 if (mReusedClientComposition) {
2116 mTimeStats->incrementClientCompositionReusedFrames();
2117 }
2118
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002119 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002120
Alec Mouri717bcb62020-02-10 17:07:19 -08002121 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2122 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2123 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2124
Lloyd Pique32cbe282018-10-19 13:09:22 -07002125 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2126 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002127 return;
2128 }
2129
2130 nsecs_t currentTime = systemTime();
2131 if (mHasPoweredOff) {
2132 mHasPoweredOff = false;
2133 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002134 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002135 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002136 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2137 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002138 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002139 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002140 }
David Sodman4a36e932017-11-07 14:29:47 -08002141 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002142 }
David Sodman4a36e932017-11-07 14:29:47 -08002143 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002144
2145 {
2146 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002147 if (mTexturePool.size() < mTexturePoolSize) {
2148 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002149 const size_t offset = mTexturePool.size();
2150 mTexturePool.resize(mTexturePoolSize);
2151 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2152 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002153 } else if (mTexturePool.size() > mTexturePoolSize) {
2154 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2155 const size_t offset = mTexturePoolSize;
2156 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2157 mTexturePool.resize(mTexturePoolSize);
2158 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002159 }
2160 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002161
Ady Abrahambe0f9482019-04-24 15:41:53 -07002162 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002163 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002164
Kevin DuBois413287f2019-02-25 08:46:47 -08002165 if (mLumaSampling && mRegionSamplingThread) {
2166 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002167 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002168
2169 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2170 // side-effect of getTotalSize(), so we check that again here
2171 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002172 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002173 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2174 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002175}
2176
Vishnu Nair4351ad52019-02-11 14:13:02 -08002177void SurfaceFlinger::computeLayerBounds() {
2178 for (const auto& pair : mDisplays) {
2179 const auto& displayDevice = pair.second;
2180 const auto display = displayDevice->getCompositionDisplay();
2181 for (const auto& layer : mDrawingState.layersSortedByZ) {
2182 // only consider the layers on the given layer stack
2183 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002184 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002185 }
2186
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002187 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2188 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002189 }
2190 }
2191}
2192
David Sodmanfa9b2af2017-12-24 13:28:59 -08002193void SurfaceFlinger::postFrame()
2194{
2195 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002196 const auto display = getDefaultDisplayDeviceLocked();
2197 if (display && getHwComposer().isConnected(*display->getId())) {
2198 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002199 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2200 logFrameStats();
2201 }
2202 }
2203}
2204
Mathias Agopian87baae12012-07-31 12:38:26 -07002205void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002206{
Mathias Agopian841cde52012-03-01 15:44:37 -08002207 ATRACE_CALL();
2208
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002209 // here we keep a copy of the drawing state (that is the state that's
2210 // going to be overwritten by handleTransactionLocked()) outside of
2211 // mStateLock so that the side-effects of the State assignment
2212 // don't happen with mStateLock held (which can cause deadlocks).
2213 State drawingState(mDrawingState);
2214
Mathias Agopianca4d3602011-05-19 15:38:14 -07002215 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002216 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217
Mathias Agopianca4d3602011-05-19 15:38:14 -07002218 // Here we're guaranteed that some transaction flags are set
2219 // so we can call handleTransactionLocked() unconditionally.
2220 // We call getTransactionFlags(), which will also clear the flags,
2221 // with mStateLock held to guarantee that mCurrentState won't change
2222 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002223
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002224 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002225 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002226 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002227
Mathias Agopianca4d3602011-05-19 15:38:14 -07002228 mDebugInTransaction = 0;
2229 invalidateHwcGeometry();
2230 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002231}
2232
Lloyd Piqueba04e622017-12-14 17:11:26 -08002233void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2234 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002235 const std::optional<DisplayIdentificationInfo> info =
2236 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002237
Dominik Laskowski075d3172018-05-24 15:50:06 -07002238 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002239 continue;
2240 }
2241
Lloyd Piqueba04e622017-12-14 17:11:26 -08002242 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002243 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002244 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002245 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2246 initScheduler(info->id);
2247 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 mPhysicalDisplayTokens[info->id] = new BBinder();
2249 DisplayDeviceState state;
2250 state.displayId = info->id;
2251 state.isSecure = true; // All physical displays are currently considered secure.
2252 state.displayName = info->name;
2253 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2254 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002255 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002256 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002257 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002258
Dominik Laskowski075d3172018-05-24 15:50:06 -07002259 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2260 if (index >= 0) {
2261 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2262 mInterceptor->saveDisplayDeletion(state.sequenceId);
2263 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002264 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002266 }
2267
2268 processDisplayChangesLocked();
2269 }
2270
2271 mPendingHotplugEvents.clear();
2272}
2273
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002274void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002275 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2276 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002277}
2278
Lloyd Pique99d3da52018-01-22 17:48:03 -08002279sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002281 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002282 const sp<IGraphicBufferProducer>& producer) {
2283 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002284 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002285 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002286 creationArgs.isSecure = state.isSecure;
2287 creationArgs.displaySurface = dispSurface;
2288 creationArgs.hasWideColorGamut = false;
2289 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002290 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002291
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002292 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 creationArgs.isPrimary = isInternalDisplay;
2294
2295 if (useColorManagement && displayId) {
2296 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002297 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002298 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002299 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301
Dominik Laskowski7e045462018-05-30 13:02:02 -07002302 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002303 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002304 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305 }
tangrobin6753a022018-08-10 10:58:54 +08002306 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002307
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 if (displayId) {
2309 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002310 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002311 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002312 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002313
Lloyd Pique90c115d2018-09-18 21:39:42 -07002314 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002316 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318 // Make sure that composition can never be stalled by a virtual display
2319 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002320 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002321 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2323 }
2324
Dominik Laskowski718f9602019-11-09 20:01:35 -08002325 creationArgs.physicalOrientation =
2326 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002327
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002329 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330
Lloyd Pique90c115d2018-09-18 21:39:42 -07002331 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
2333 if (maxFrameBufferAcquiredBuffers >= 3) {
2334 nativeWindowSurface->preallocateBuffers();
2335 }
2336
2337 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002339 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002340 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002341 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002342 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002343 display->getCompositionDisplay()->setColorProfile(
2344 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2345 RenderIntent::COLORIMETRIC,
2346 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002347 if (!state.isVirtual()) {
2348 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002349 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2350 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002351 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002352
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 display->setLayerStack(state.layerStack);
2354 display->setProjection(state.orientation, state.viewport, state.frame);
2355 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002357 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358}
2359
Lloyd Pique347200f2017-12-14 17:00:15 -08002360void SurfaceFlinger::processDisplayChangesLocked() {
2361 // here we take advantage of Vector's copy-on-write semantics to
2362 // improve performance by skipping the transaction entirely when
2363 // know that the lists are identical
2364 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2365 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2366 if (!curr.isIdenticalTo(draw)) {
2367 mVisibleRegionsDirty = true;
2368 const size_t cc = curr.size();
2369 size_t dc = draw.size();
2370
2371 // find the displays that were removed
2372 // (ie: in drawing state but not in current state)
2373 // also handle displays that changed
2374 // (ie: displays that are in both lists)
2375 for (size_t i = 0; i < dc;) {
2376 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2377 if (j < 0) {
2378 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002380 // Save display ID before disconnecting.
2381 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002382 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002383
2384 if (!display->isVirtual()) {
2385 LOG_ALWAYS_FATAL_IF(!displayId);
2386 dispatchDisplayHotplugEvent(displayId->value, false);
2387 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002388 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002389
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002390 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002391 } else {
2392 // this display is in both lists. see if something changed.
2393 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002394 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002395 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2396 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2397 if (state_binder != draw_binder) {
2398 // changing the surface is like destroying and
2399 // recreating the DisplayDevice, so we just remove it
2400 // from the drawing state, so that it get re-added
2401 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002402 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002403 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002404 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002405 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 mDrawingState.displays.removeItemsAt(i);
2407 dc--;
2408 // at this point we must loop to the next item
2409 continue;
2410 }
2411
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002413 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002414 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002415 }
2416 if ((state.orientation != draw[i].orientation) ||
2417 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002418 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002419 }
2420 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002421 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002422 if (display->isPrimary()) {
2423 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2424 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 }
2426 }
2427 }
2428 ++i;
2429 }
2430
2431 // find displays that were added
2432 // (ie: in current state but not in drawing state)
2433 for (size_t i = 0; i < cc; i++) {
2434 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2435 const DisplayDeviceState& state(curr[i]);
2436
Lloyd Pique542307f2018-10-19 13:24:08 -07002437 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 sp<IGraphicBufferProducer> producer;
2439 sp<IGraphicBufferProducer> bqProducer;
2440 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002441 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442
Dominik Laskowski075d3172018-05-24 15:50:06 -07002443 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002444 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 // Virtual displays without a surface are dormant:
2446 // they have external state (layer stack, projection,
2447 // etc.) but no internal state (i.e. a DisplayDevice).
2448 if (state.surface != nullptr) {
2449 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002451 int width = 0;
2452 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2453 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2454 int height = 0;
2455 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2456 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2457 int intFormat = 0;
2458 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2459 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002460 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002461
Dominik Laskowski075d3172018-05-24 15:50:06 -07002462 displayId =
2463 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 }
2465
2466 // TODO: Plumb requested format back up to consumer
2467
2468 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002470 bqProducer, bqConsumer,
2471 state.displayName);
2472
2473 dispSurface = vds;
2474 producer = vds;
2475 }
2476 } else {
2477 ALOGE_IF(state.surface != nullptr,
2478 "adding a supported display, but rendering "
2479 "surface is provided (%p), ignoring it",
2480 state.surface.get());
2481
Dominik Laskowski075d3172018-05-24 15:50:06 -07002482 displayId = state.displayId;
2483 LOG_ALWAYS_FATAL_IF(!displayId);
2484 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 producer = bqProducer;
2486 }
2487
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002489 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002490 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002491 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002492 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002493 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002494 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002495 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002497
2498 const auto displayDevice = mDisplays[displayToken];
2499 if (displayDevice->isPrimary()) {
2500 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2501 displayDevice->getHeight());
2502 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 }
2504 }
2505 }
2506 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002507
2508 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002509}
2510
Mathias Agopian87baae12012-07-31 12:38:26 -07002511void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002512{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002513 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2514
Dan Stoza7dde5992015-05-22 09:51:44 -07002515 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002516 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002517 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002518 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 /*
2521 * Traversal of the children
2522 * (perform the transaction for each of them if needed)
2523 */
2524
Marissa Wall06255332019-03-27 13:48:27 -07002525 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002526 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002528 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529
2530 const uint32_t flags = layer->doTransaction(0);
2531 if (flags & Layer::eVisibleRegion)
2532 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002533
2534 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002535 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002536 }
Robert Carr2047fae2016-11-28 14:09:09 -08002537 });
Marissa Wall06255332019-03-27 13:48:27 -07002538 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 }
2540
2541 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002542 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 */
2544
Mathias Agopiane57f2922012-08-09 16:29:12 -07002545 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002546 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002547 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002550 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002551 // The transform hint might have changed for some layers
2552 // (either because a display has changed, or because a layer
2553 // as changed).
2554 //
2555 // Walk through all the layers in currentLayers,
2556 // and update their transform hint.
2557 //
2558 // If a layer is visible only on a single display, then that
2559 // display is used to calculate the hint, otherwise we use the
2560 // default display.
2561 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002562 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002563 // the hint is set before we acquire a buffer from the surface texture.
2564 //
2565 // NOTE: layer transactions have taken place already, so we use their
2566 // drawing state. However, SurfaceFlinger's own transaction has not
2567 // happened yet, so we must use the current state layer list
2568 // (soon to become the drawing state list).
2569 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002570 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002571 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002572 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002573 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002574 // NOTE: we rely on the fact that layers are sorted by
2575 // layerStack first (so we don't have to traverse the list
2576 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002577 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002578 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002579 currentlayerStack = layerStack;
2580 // figure out if this layerstack is mirrored
2581 // (more than one display) if so, pick the default display,
2582 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002583 hintDisplay = nullptr;
2584 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002585 if (display->getCompositionDisplay()
2586 ->belongsInOutput(layer->getLayerStack(),
2587 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002588 if (hintDisplay) {
2589 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002590 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002591 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002592 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002593 }
2594 }
2595 }
2596 }
Chet Haase91d25932013-04-11 15:24:55 -07002597
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002598 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002599 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2600 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002601
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002602 // could be null when this layer is using a layerStack
2603 // that is not visible on any display. Also can occur at
2604 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002605 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002606 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002607
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002608 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002609 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002610 if (hintDisplay) {
2611 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002612 }
Robert Carr2047fae2016-11-28 14:09:09 -08002613
2614 first = false;
2615 });
Mathias Agopian84300952012-11-21 16:02:13 -08002616 }
2617
2618
Mathias Agopian3559b072012-08-15 13:46:03 -07002619 /*
2620 * Perform our own transaction if needed
2621 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002622
2623 if (mLayersAdded) {
2624 mLayersAdded = false;
2625 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002626 mVisibleRegionsDirty = true;
2627 }
2628
2629 // some layers might have been removed, so
2630 // we need to update the regions they're exposing.
2631 if (mLayersRemoved) {
2632 mLayersRemoved = false;
2633 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002634 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002636 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002638 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002639 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002640 }
Robert Carr2047fae2016-11-28 14:09:09 -08002641 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 }
2643
Vishnu Nairec0ab382019-02-13 15:32:56 -08002644 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002646}
2647
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002648void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002649 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002650 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002651 return;
2652 }
2653
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002654 if (mVisibleRegionsDirty || mInputInfoChanged) {
2655 mInputInfoChanged = false;
2656 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002657 } else if (mInputWindowCommands.syncInputWindows) {
2658 // If the caller requested to sync input windows, but there are no
2659 // changes to input windows, notify immediately.
2660 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002661 }
2662
Arthur Hung6cbb9752019-09-05 16:38:18 +08002663 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002664}
2665
2666void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002667 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002668
2669 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2670 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002671 // When calculating the screen bounds we ignore the transparent region since it may
2672 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002673 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002674 }
2675 });
chaviw291d88a2019-02-14 10:33:58 -08002676
2677 mInputFlinger->setInputWindows(inputHandles,
2678 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2679 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002680}
2681
Vishnu Nairec0ab382019-02-13 15:32:56 -08002682void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002683 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002684 mPendingInputWindowCommands.clear();
2685}
2686
Riley Andrews03414a12014-07-01 14:22:59 -07002687void SurfaceFlinger::updateCursorAsync()
2688{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002689 compositionengine::CompositionRefreshArgs refreshArgs;
2690 for (const auto& [_, display] : mDisplays) {
2691 if (display->getId()) {
2692 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002693 }
2694 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002695
2696 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002697}
2698
Ady Abraham2139f732019-11-13 18:56:40 -08002699void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002700 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2701 // If this is called from the main thread mStateLock must be locked before
2702 // Currently the only way to call this function from the main thread is from
2703 // Sheduler::chooseRefreshRateForContent
2704
2705 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002706 changeRefreshRateLocked(refreshRate, event);
2707}
2708
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002709void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2710 if (mScheduler) {
2711 // In practice it's not allowed to hotplug in/out the primary display once it's been
2712 // connected during startup, but some tests do it, so just warn and return.
2713 ALOGW("Can't re-init scheduler");
2714 return;
2715 }
2716
Ady Abraham2139f732019-11-13 18:56:40 -08002717 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002718 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002719 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002720 primaryDisplayId),
2721 currentConfig);
2722 mRefreshRateStats =
2723 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2724 currentConfig, HWC_POWER_MODE_OFF);
2725 mRefreshRateStats->setConfigMode(currentConfig);
2726
Ady Abraham9e16a482019-12-03 17:19:41 -08002727 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2728
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002729 // start the EventThread
2730 mScheduler =
2731 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002732 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002733 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002734 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002735 impl::EventThread::InterceptVSyncsCallback());
2736 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002737 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002738 [this](nsecs_t timestamp) {
2739 mInterceptor->saveVSyncEvent(timestamp);
2740 });
2741
2742 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2743 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002744 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002745
2746 mRegionSamplingThread =
2747 new RegionSamplingThread(*this, *mScheduler,
2748 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002749 // Dispatch a config change request for the primary display on scheduler
2750 // initialization, so that the EventThreads always contain a reference to a
2751 // prior configuration.
2752 //
2753 // This is a bit hacky, but this avoids a back-pointer into the main SF
2754 // classes from EventThread, and there should be no run-time binder cost
2755 // anyway since there are no connected apps at this point.
2756 const nsecs_t vsyncPeriod =
2757 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2758 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2759 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002760}
2761
Mathias Agopian4fec8732012-06-29 14:12:52 -07002762void SurfaceFlinger::commitTransaction()
2763{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002764 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002765
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002766 mTransactionPending = false;
2767 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002768 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769}
2770
Lloyd Pique58e24a32019-08-01 15:50:14 -07002771void SurfaceFlinger::commitTransactionLocked() {
2772 if (!mLayersPendingRemoval.isEmpty()) {
2773 // Notify removed layers now that they can't be drawn from
2774 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002775 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002776
2777 // Ensure any buffers set to display on any children are released.
2778 if (l->isRemovedFromCurrentState()) {
2779 l->latchAndReleaseBuffer();
2780 }
2781
2782 // If the layer has been removed and has no parent, then it will not be reachable
2783 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2784 // ensure we can copy its current to drawing state.
2785 if (!l->getParent()) {
2786 mOffscreenLayers.emplace(l.get());
2787 }
2788 }
2789 mLayersPendingRemoval.clear();
2790 }
2791
2792 // If this transaction is part of a window animation then the next frame
2793 // we composite should be considered an animation as well.
2794 mAnimCompositionPending = mAnimTransactionPending;
2795
2796 mDrawingState = mCurrentState;
2797 // clear the "changed" flags in current state
2798 mCurrentState.colorMatrixChanged = false;
2799
Edgar Arriaga844fa672020-01-16 14:21:42 -08002800 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002801 layer->commitChildList();
2802
2803 // If the layer can be reached when traversing mDrawingState, then the layer is no
2804 // longer offscreen. Remove the layer from the offscreenLayer set.
2805 if (mOffscreenLayers.count(layer)) {
2806 mOffscreenLayers.erase(layer);
2807 }
2808 });
2809
2810 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002811 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002812}
2813
Nataniel Borges2b796da2019-02-15 13:32:18 -08002814void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2815 if (mTracingEnabledChanged) {
2816 mTracingEnabled = mTracing.isEnabled();
2817 mTracingEnabledChanged = false;
2818 }
2819
2820 // Synchronize with Tracing thread
2821 std::unique_lock<std::mutex> lock;
2822 if (mTracingEnabled) {
2823 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2824 }
2825
2826 lockedOperation();
2827
2828 // Synchronize with Tracing thread
2829 if (mTracingEnabled) {
2830 lock.unlock();
2831 }
2832}
2833
chaviw74d90ad2019-04-26 14:45:26 -07002834void SurfaceFlinger::commitOffscreenLayers() {
2835 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002836 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002837 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2838 if (!trFlags) return;
2839
2840 layer->doTransaction(0);
2841 layer->commitChildList();
2842 });
2843 }
2844}
2845
Chia-I Wuab0c3192017-08-01 11:29:00 -07002846void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002847 for (const auto& [token, displayDevice] : mDisplays) {
2848 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002849 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002850 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002851 }
2852 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002853}
2854
Dan Stoza6b9454d2014-11-07 16:00:59 -08002855bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856{
Ady Abraham09bd3922019-04-08 10:44:56 -07002857 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858 ALOGV("handlePageFlip");
2859
Brian Andersond6927fb2016-07-23 23:37:30 -07002860 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861
Mathias Agopian4fec8732012-06-29 14:12:52 -07002862 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002863 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002864 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002865
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002866 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2867
Eric Penner51c59cd2014-07-28 19:51:58 -07002868 // Store the set of layers that need updates. This set must not change as
2869 // buffers are being latched, as this could result in a deadlock.
2870 // Example: Two producers share the same command stream and:
2871 // 1.) Layer 0 is latched
2872 // 2.) Layer 0 gets a new frame
2873 // 2.) Layer 1 gets a new frame
2874 // 3.) Layer 1 is latched.
2875 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2876 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002877 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002878 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002879 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002880 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002881 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002882 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002883 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002884 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002886 } else {
2887 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002888 }
Robert Carr2047fae2016-11-28 14:09:09 -08002889 });
2890
chaviw49a108c2019-08-12 11:23:06 -07002891 // The client can continue submitting buffers for offscreen layers, but they will not
2892 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2893 // layers to ensure dequeueBuffer doesn't block indefinitely.
2894 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002895 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002896 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2897 }
2898
Lloyd Piquef2c79392018-12-20 16:23:33 -08002899 if (!mLayersWithQueuedFrames.empty()) {
2900 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2901 // writes to Layer current state. See also b/119481871
2902 Mutex::Autolock lock(mStateLock);
2903
2904 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002905 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002906 mLayersPendingRefresh.push_back(layer);
2907 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002908 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002909 if (layer->isBufferLatched()) {
2910 newDataLatched = true;
2911 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002912 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002913 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002914
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002915 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916
2917 // If we will need to wake up at some time in the future to deal with a
2918 // queued frame that shouldn't be displayed during this vsync period, wake
2919 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002920 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002921 signalLayerUpdate();
2922 }
2923
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002924 // enter boot animation on first buffer latch
2925 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2926 ALOGI("Enter boot animation");
2927 mBootStage = BootStage::BOOTANIMATION;
2928 }
2929
Edgar Arriaga844fa672020-01-16 14:21:42 -08002930 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002931
Dan Stoza6b9454d2014-11-07 16:00:59 -08002932 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002933 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934}
2935
Mathias Agopianad456f92011-01-13 17:53:01 -08002936void SurfaceFlinger::invalidateHwcGeometry()
2937{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002938 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002939}
2940
Robert Carrc0df3122019-04-11 13:18:21 -07002941status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2942 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2943 const sp<IBinder>& parentHandle,
2944 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002945 // add this layer to the current state list
2946 {
2947 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002948 sp<Layer> parent;
2949 if (parentHandle != nullptr) {
2950 parent = fromHandle(parentHandle);
2951 if (parent == nullptr) {
2952 return NAME_NOT_FOUND;
2953 }
2954 } else {
2955 parent = parentLayer;
2956 }
2957
Robert Carr1f0a16a2016-10-24 16:27:39 -07002958 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002959 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002960 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002961 return NO_MEMORY;
2962 }
Robert Carrc0df3122019-04-11 13:18:21 -07002963
2964 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2965
Robert Carrb89ea9d2018-12-10 13:01:14 -08002966 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002967 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002968 } else if (parent == nullptr) {
2969 lbc->onRemovedFromCurrentState();
2970 } else if (parent->isRemovedFromCurrentState()) {
2971 parent->addChild(lbc);
2972 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002973 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002974 parent->addChild(lbc);
2975 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002976
Yiwei Zhang243b3782018-05-15 17:40:04 -07002977 if (gbc != nullptr) {
2978 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2979 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2980 mMaxGraphicBufferProducerListSize,
2981 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2982 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002983 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002984 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002985 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002986 }
2987
Mathias Agopian96f08192010-06-02 23:28:45 -07002988 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002989 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002990
Dan Stoza7d89d062015-04-30 13:29:25 -07002991 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002992}
2993
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002994uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002995 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002996}
2997
Mathias Agopian3f844832013-08-07 21:24:32 -07002998uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002999 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000}
3001
Mathias Agopian3f844832013-08-07 21:24:32 -07003002uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003003 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003004}
3005
3006uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003007 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003008 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003009 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003010 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003011 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012 }
3013 return old;
3014}
3015
Marissa Wall713b63f2018-10-17 15:42:43 -07003016bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003017 // to prevent onHandleDestroyed from being called while the lock is held,
3018 // we must keep a copy of the transactions (specifically the composer
3019 // states) around outside the scope of the lock
3020 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003021 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003022 {
3023 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003024
Valerie Haufce31b82019-04-30 16:41:14 -07003025 auto it = mTransactionQueues.begin();
3026 while (it != mTransactionQueues.end()) {
3027 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003028
Valerie Haufce31b82019-04-30 16:41:14 -07003029 while (!transactionQueue.empty()) {
3030 const auto& transaction = transactionQueue.front();
3031 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003032 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003033 transaction.states)) {
3034 setTransactionFlags(eTransactionFlushNeeded);
3035 break;
3036 }
3037 transactions.push_back(transaction);
3038 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3039 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003040 transaction.buffer, transaction.postTime,
3041 transaction.privileged, transaction.hasListenerCallbacks,
3042 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003043 transactionQueue.pop();
3044 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003045 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003046
Valerie Haufce31b82019-04-30 16:41:14 -07003047 if (transactionQueue.empty()) {
3048 it = mTransactionQueues.erase(it);
3049 mTransactionCV.broadcast();
3050 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003051 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003052 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003053 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003054 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003055 return flushedATransaction;
3056}
3057
3058bool SurfaceFlinger::transactionFlushNeeded() {
3059 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003060}
3061
chaviwca27f252018-02-06 16:46:39 -08003062
Marissa Wall17b4e452018-12-26 16:32:34 -08003063bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003064 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003065 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003066 if (!useCachedExpectedPresentTime)
3067 populateExpectedPresentTime();
3068
3069 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003070 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3071 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3072 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3073 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3074 return false;
3075 }
3076
Marissa Wall713b63f2018-10-17 15:42:43 -07003077 for (const ComposerState& state : states) {
3078 const layer_state_t& s = state.state;
3079 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3080 continue;
3081 }
3082 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003083 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003084 }
3085 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003086 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003087}
3088
Valerie Hau9dab9732019-08-20 09:29:25 -07003089void SurfaceFlinger::setTransactionState(
3090 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3091 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3092 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3093 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003094 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003095
Valerie Haubc6ddb12019-03-08 11:10:15 -08003096 const int64_t postTime = systemTime();
3097
Robert Carr14167e02019-02-13 13:50:55 -08003098 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3099
Mathias Agopian698c0872011-06-28 19:09:31 -07003100 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003101
Marissa Wall713b63f2018-10-17 15:42:43 -07003102 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003103 auto itr = mTransactionQueues.find(applyToken);
3104 // if this is an animation frame, wait until prior animation frame has
3105 // been applied by SF
3106 if (flags & eAnimation) {
3107 while (itr != mTransactionQueues.end()) {
3108 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3109 if (CC_UNLIKELY(err != NO_ERROR)) {
3110 ALOGW_IF(err == TIMED_OUT,
3111 "setTransactionState timed out "
3112 "waiting for animation frame to apply");
3113 break;
3114 }
3115 itr = mTransactionQueues.find(applyToken);
3116 }
3117 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003118
3119 // Expected present time is computed and cached on invalidate, so it may be stale.
3120 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3121 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003122 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003123 uncacheBuffer, postTime, privileged,
3124 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003125 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003126 return;
3127 }
3128
Valerie Haubc6ddb12019-03-08 11:10:15 -08003129 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003130 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3131 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003132}
3133
Valerie Hau9dab9732019-08-20 09:29:25 -07003134void SurfaceFlinger::applyTransactionState(
3135 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3136 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3137 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3138 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3139 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003140 uint32_t transactionFlags = 0;
3141
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003142 if (flags & eAnimation) {
3143 // For window updates that are part of an animation we must wait for
3144 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003145 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003146 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003147 if (CC_UNLIKELY(err != NO_ERROR)) {
3148 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003149 // caller after a few seconds.
3150 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3151 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003152 mAnimTransactionPending = false;
3153 break;
3154 }
3155 }
3156 }
3157
chaviwca27f252018-02-06 16:46:39 -08003158 for (const DisplayState& display : displays) {
3159 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003160 }
3161
Valerie Hau9dab9732019-08-20 09:29:25 -07003162 // start and end registration for listeners w/ no surface so they can get their callback. Note
3163 // that listeners with SurfaceControls will start registration during setClientStateLocked
3164 // below.
3165 for (const auto& listener : listenerCallbacks) {
3166 mTransactionCompletedThread.startRegistration(listener);
3167 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003168 }
3169
Valerie Hau9dab9732019-08-20 09:29:25 -07003170 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003171 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003172 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003173 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3174 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003175 }
3176
Valerie Hau9dab9732019-08-20 09:29:25 -07003177 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003178 mTransactionCompletedThread.endRegistration(listenerCallback);
3179 }
3180
Marissa Walle2ffb422018-10-12 11:33:52 -07003181 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003182 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003183 mTransactionCompletedThread.sendCallbacks();
3184 }
3185 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003186
chaviw273171b2018-12-26 11:46:30 -08003187 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3188
Marissa Wall947d34e2019-03-29 14:03:53 -07003189 if (uncacheBuffer.isValid()) {
3190 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003191 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003192 }
3193
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003194 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3195 // anyway. This can be used as a flush mechanism for previous async transactions.
3196 // Empty animation transaction can be used to simulate back-pressure, so also force a
3197 // transaction for empty animation transactions.
3198 if (transactionFlags == 0 &&
3199 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003200 transactionFlags = eTransactionNeeded;
3201 }
3202
Marissa Wall06255332019-03-27 13:48:27 -07003203 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3204 // so we don't have to wake up again next frame to preform an uneeded traversal.
3205 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3206 transactionFlags = transactionFlags & (~eTraversalNeeded);
3207 mTraversalNeededMainThread = true;
3208 }
3209
Mathias Agopian386aa982011-11-07 21:58:03 -08003210 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003211 if (mInterceptor->isEnabled()) {
3212 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003213 }
Irvel468051e2016-06-13 16:44:44 -07003214
Mathias Agopian386aa982011-11-07 21:58:03 -08003215 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003216 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3217 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003218 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003219
3220 // if this is a synchronous transaction, wait for it to take effect
3221 // before returning.
3222 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003223 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003224 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003225 if (flags & eAnimation) {
3226 mAnimTransactionPending = true;
3227 }
chaviw4fe36852019-04-15 16:25:49 -07003228 if (mPendingInputWindowCommands.syncInputWindows) {
3229 mPendingSyncInputWindows = true;
3230 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003231
3232 // applyTransactionState can be called by either the main SF thread or by
3233 // another process through setTransactionState. While a given process may wish
3234 // to wait on synchronous transactions, the main SF thread should never
3235 // be blocked. Therefore, we only wait if isMainThread is false.
3236 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003237 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3238 if (CC_UNLIKELY(err != NO_ERROR)) {
3239 // just in case something goes wrong in SF, return to the
3240 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003241 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3242 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003243 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003244 break;
3245 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003246 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247 }
3248}
3249
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003250uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3251 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3252 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003253
Mathias Agopiane57f2922012-08-09 16:29:12 -07003254 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003255 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3256
3257 const uint32_t what = s.what;
3258 if (what & DisplayState::eSurfaceChanged) {
3259 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3260 state.surface = s.surface;
3261 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003262 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003263 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003264 if (what & DisplayState::eLayerStackChanged) {
3265 if (state.layerStack != s.layerStack) {
3266 state.layerStack = s.layerStack;
3267 flags |= eDisplayTransactionNeeded;
3268 }
3269 }
3270 if (what & DisplayState::eDisplayProjectionChanged) {
3271 if (state.orientation != s.orientation) {
3272 state.orientation = s.orientation;
3273 flags |= eDisplayTransactionNeeded;
3274 }
3275 if (state.frame != s.frame) {
3276 state.frame = s.frame;
3277 flags |= eDisplayTransactionNeeded;
3278 }
3279 if (state.viewport != s.viewport) {
3280 state.viewport = s.viewport;
3281 flags |= eDisplayTransactionNeeded;
3282 }
3283 }
3284 if (what & DisplayState::eDisplaySizeChanged) {
3285 if (state.width != s.width) {
3286 state.width = s.width;
3287 flags |= eDisplayTransactionNeeded;
3288 }
3289 if (state.height != s.height) {
3290 state.height = s.height;
3291 flags |= eDisplayTransactionNeeded;
3292 }
3293 }
3294
Mathias Agopiane57f2922012-08-09 16:29:12 -07003295 return flags;
3296}
3297
Robert Carr14167e02019-02-13 13:50:55 -08003298bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003299 IPCThreadState* ipc = IPCThreadState::self();
3300 const int pid = ipc->getCallingPid();
3301 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003302 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003303 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003304 return false;
3305 }
3306 return true;
3307}
3308
Marissa Wall3dad52d2019-03-22 14:03:19 -07003309uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003310 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3311 bool privileged,
3312 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003313 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003314
Valerie Hau9dab9732019-08-20 09:29:25 -07003315 for (auto& listener : s.listeners) {
3316 // note that startRegistration will not re-register if the listener has
3317 // already be registered for a prior surface control
3318 mTransactionCompletedThread.startRegistration(listener);
3319 listenerCallbacks.insert(listener);
3320 }
3321
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003322 sp<Layer> layer = nullptr;
3323 if (s.surface) {
3324 layer = fromHandle(s.surface);
3325 } else {
3326 // The client may provide us a null handle. Treat it as if the layer was removed.
3327 ALOGW("Attempt to set client state with a null layer handle");
3328 }
chaviw8b3871a2017-11-01 17:41:01 -07003329 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003330 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003331 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003332 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003333 }
chaviw8b3871a2017-11-01 17:41:01 -07003334 return 0;
3335 }
3336
chaviw8b3871a2017-11-01 17:41:01 -07003337 uint32_t flags = 0;
3338
Garfield Tan8a3083e2018-12-03 13:21:07 -08003339 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003340
3341 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3342 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003343 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003344 layer->pushPendingState();
3345 }
3346
Valerie Hau871d6352020-01-29 08:44:02 -08003347 // Only set by BLAST adapter layers
3348 if (what & layer_state_t::eProducerDisconnect) {
3349 layer->onDisconnect();
3350 }
3351
chaviw8b3871a2017-11-01 17:41:01 -07003352 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003353 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003354 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003355 }
chaviw8b3871a2017-11-01 17:41:01 -07003356 }
3357 if (what & layer_state_t::eLayerChanged) {
3358 // NOTE: index needs to be calculated before we update the state
3359 const auto& p = layer->getParent();
3360 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003361 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003362 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 mCurrentState.layersSortedByZ.removeAt(idx);
3364 mCurrentState.layersSortedByZ.add(layer);
3365 // we need traversal (state changed)
3366 // AND transaction (list changed)
3367 flags |= eTransactionNeeded|eTraversalNeeded;
3368 }
chaviw8b3871a2017-11-01 17:41:01 -07003369 } else {
3370 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003371 flags |= eTransactionNeeded|eTraversalNeeded;
3372 }
3373 }
chaviw8b3871a2017-11-01 17:41:01 -07003374 }
3375 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003376 // NOTE: index needs to be calculated before we update the state
3377 const auto& p = layer->getParent();
3378 if (p == nullptr) {
3379 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3380 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3381 mCurrentState.layersSortedByZ.removeAt(idx);
3382 mCurrentState.layersSortedByZ.add(layer);
3383 // we need traversal (state changed)
3384 // AND transaction (list changed)
3385 flags |= eTransactionNeeded|eTraversalNeeded;
3386 }
3387 } else {
3388 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3389 flags |= eTransactionNeeded|eTraversalNeeded;
3390 }
chaviw8b3871a2017-11-01 17:41:01 -07003391 }
3392 }
3393 if (what & layer_state_t::eSizeChanged) {
3394 if (layer->setSize(s.w, s.h)) {
3395 flags |= eTraversalNeeded;
3396 }
3397 }
3398 if (what & layer_state_t::eAlphaChanged) {
3399 if (layer->setAlpha(s.alpha))
3400 flags |= eTraversalNeeded;
3401 }
3402 if (what & layer_state_t::eColorChanged) {
3403 if (layer->setColor(s.color))
3404 flags |= eTraversalNeeded;
3405 }
Peiyong Lind3788632018-09-18 16:01:31 -07003406 if (what & layer_state_t::eColorTransformChanged) {
3407 if (layer->setColorTransform(s.colorTransform)) {
3408 flags |= eTraversalNeeded;
3409 }
3410 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003411 if (what & layer_state_t::eBackgroundColorChanged) {
3412 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3413 flags |= eTraversalNeeded;
3414 }
3415 }
chaviw8b3871a2017-11-01 17:41:01 -07003416 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003417 // TODO: b/109894387
3418 //
3419 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3420 // rotation. To see the problem observe that if we have a square parent, and a child
3421 // of the same size, then we rotate the child 45 degrees around it's center, the child
3422 // must now be cropped to a non rectangular 8 sided region.
3423 //
3424 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3425 // private API, and the WindowManager only uses rotation in one case, which is on a top
3426 // level layer in which cropping is not an issue.
3427 //
3428 // However given that abuse of rotation matrices could lead to surfaces extending outside
3429 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3430 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3431 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003432 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003433 flags |= eTraversalNeeded;
3434 }
3435 if (what & layer_state_t::eTransparentRegionChanged) {
3436 if (layer->setTransparentRegionHint(s.transparentRegion))
3437 flags |= eTraversalNeeded;
3438 }
3439 if (what & layer_state_t::eFlagsChanged) {
3440 if (layer->setFlags(s.flags, s.mask))
3441 flags |= eTraversalNeeded;
3442 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003443 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003444 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003445 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003446 if (what & layer_state_t::eCornerRadiusChanged) {
3447 if (layer->setCornerRadius(s.cornerRadius))
3448 flags |= eTraversalNeeded;
3449 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003450 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3451 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 if (what & layer_state_t::eLayerStackChanged) {
3454 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3455 // We only allow setting layer stacks for top level layers,
3456 // everything else inherits layer stack from its parent.
3457 if (layer->hasParent()) {
3458 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003459 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003460 } else if (idx < 0) {
3461 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003462 "that also does not appear in the top level layer list. Something"
3463 " has gone wrong.",
3464 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003465 } else if (layer->setLayerStack(s.layerStack)) {
3466 mCurrentState.layersSortedByZ.removeAt(idx);
3467 mCurrentState.layersSortedByZ.add(layer);
3468 // we need traversal (state changed)
3469 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003470 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003471 }
3472 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003473 if (what & layer_state_t::eDeferTransaction_legacy) {
3474 if (s.barrierHandle_legacy != nullptr) {
3475 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3476 } else if (s.barrierGbp_legacy != nullptr) {
3477 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003478 if (authenticateSurfaceTextureLocked(gbp)) {
3479 const auto& otherLayer =
3480 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003481 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003482 } else {
3483 ALOGE("Attempt to defer transaction to to an"
3484 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003485 }
3486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 // We don't trigger a traversal here because if no other state is
3488 // changed, we don't want this to cause any more work
3489 }
chaviw8b3871a2017-11-01 17:41:01 -07003490 if (what & layer_state_t::eReparentChildren) {
3491 if (layer->reparentChildren(s.reparentHandle)) {
3492 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003494 }
chaviw8b3871a2017-11-01 17:41:01 -07003495 if (what & layer_state_t::eDetachChildren) {
3496 layer->detachChildren();
3497 }
3498 if (what & layer_state_t::eOverrideScalingModeChanged) {
3499 layer->setOverrideScalingMode(s.overrideScalingMode);
3500 // We don't trigger a traversal here because if no other state is
3501 // changed, we don't want this to cause any more work
3502 }
Marissa Wall61c58622018-07-18 10:12:20 -07003503 if (what & layer_state_t::eTransformChanged) {
3504 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3505 }
3506 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3507 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3508 flags |= eTraversalNeeded;
3509 }
3510 if (what & layer_state_t::eCropChanged) {
3511 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3512 }
Marissa Wall861616d2018-10-22 12:52:23 -07003513 if (what & layer_state_t::eFrameChanged) {
3514 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3515 }
Marissa Wall61c58622018-07-18 10:12:20 -07003516 if (what & layer_state_t::eAcquireFenceChanged) {
3517 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3518 }
3519 if (what & layer_state_t::eDataspaceChanged) {
3520 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eHdrMetadataChanged) {
3523 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3524 }
3525 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3526 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3527 }
3528 if (what & layer_state_t::eApiChanged) {
3529 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3530 }
3531 if (what & layer_state_t::eSidebandStreamChanged) {
3532 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3533 }
Robert Carr720e5062018-07-30 17:45:14 -07003534 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003535 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003536 layer->setInputInfo(s.inputInfo);
3537 flags |= eTraversalNeeded;
3538 } else {
3539 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3540 }
Robert Carr720e5062018-07-30 17:45:14 -07003541 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003542 if (what & layer_state_t::eMetadataChanged) {
3543 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3544 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003545 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3546 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3547 flags |= eTraversalNeeded;
3548 }
3549 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003550 if (what & layer_state_t::eShadowRadiusChanged) {
3551 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3552 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003553 if (what & layer_state_t::eFrameRateSelectionPriority) {
3554 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3555 flags |= eTraversalNeeded;
3556 }
3557 }
Steven Thomas3172e202020-01-06 19:25:30 -08003558 if (what & layer_state_t::eFrameRateChanged) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003559 if (layer->setFrameRate(
3560 Layer::FrameRate(s.frameRate, Layer::FrameRateCompatibility::Default)))
3561 flags |= eTraversalNeeded;
Steven Thomas3172e202020-01-06 19:25:30 -08003562 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003563 // This has to happen after we reparent children because when we reparent to null we remove
3564 // child layers from current state and remove its relative z. If the children are reparented in
3565 // the same transaction, then we have to make sure we reparent the children first so we do not
3566 // lose its relative z order.
3567 if (what & layer_state_t::eReparent) {
3568 bool hadParent = layer->hasParent();
3569 if (layer->reparent(s.parentHandleForChild)) {
3570 if (!hadParent) {
3571 mCurrentState.layersSortedByZ.remove(layer);
3572 }
3573 flags |= eTransactionNeeded | eTraversalNeeded;
3574 }
3575 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003576 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003577 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3578 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003579 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3580 }
3581 }
Marissa Wall78b72202019-03-15 14:58:34 -07003582 bool bufferChanged = what & layer_state_t::eBufferChanged;
3583 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3584 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003585 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003586 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003587 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3588 if (success) {
3589 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3590 success = ClientCache::getInstance()
3591 .registerErasedRecipient(s.cachedBuffer,
3592 wp<ClientCache::ErasedRecipient>(this));
3593 if (!success) {
3594 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3595 }
3596 }
Marissa Wall78b72202019-03-15 14:58:34 -07003597 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003598 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003599 } else if (bufferChanged) {
3600 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003601 }
Marissa Wall78b72202019-03-15 14:58:34 -07003602 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003603 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3604 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003605 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003606 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003607 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003608 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3609 // Do not put anything that updates layer state or modifies flags after
3610 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003611 return flags;
3612}
3613
chaviw273171b2018-12-26 11:46:30 -08003614uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3615 uint32_t flags = 0;
3616 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3617 flags |= eTraversalNeeded;
3618 }
3619
chaviwa911b102019-02-14 10:18:33 -08003620 if (inputWindowCommands.syncInputWindows) {
3621 flags |= eTraversalNeeded;
3622 }
3623
Vishnu Nairec0ab382019-02-13 15:32:56 -08003624 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003625 return flags;
3626}
3627
chaviwfe94a222019-08-21 13:52:59 -07003628status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3629 sp<IBinder>* outHandle) {
3630 if (!mirrorFromHandle) {
3631 return NAME_NOT_FOUND;
3632 }
3633
3634 sp<Layer> mirrorLayer;
3635 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003636 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003637
3638 {
3639 Mutex::Autolock _l(mStateLock);
3640 mirrorFrom = fromHandle(mirrorFromHandle);
3641 if (!mirrorFrom) {
3642 return NAME_NOT_FOUND;
3643 }
3644
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003645 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3646 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003647 if (result != NO_ERROR) {
3648 return result;
3649 }
3650
3651 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3652 }
3653
3654 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3655}
3656
Marissa Wall2d814fb2019-04-09 18:52:57 +00003657status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3658 uint32_t h, PixelFormat format, uint32_t flags,
3659 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003660 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003661 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3662 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003663 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003664 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003665 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003667 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003668
Robert Carrc0df3122019-04-11 13:18:21 -07003669 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3670 "Expected only one of parentLayer or parentHandle to be non-null. "
3671 "Programmer error?");
3672
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003673 status_t result = NO_ERROR;
3674
3675 sp<Layer> layer;
3676
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003677 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003678
Evan Roskya1f1e152019-01-24 16:17:46 -08003679 bool primaryDisplayOnly = false;
3680
3681 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3682 // TODO b/64227542
3683 if (metadata.has(METADATA_WINDOW_TYPE)) {
3684 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3685 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003686 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003687 primaryDisplayOnly = true;
3688 }
3689 }
3690
Mathias Agopian3165cc22012-08-08 19:42:09 -07003691 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003692 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003693 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3694 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003696 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003697 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003698 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003699 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003700 break;
chaviw13fdc492017-06-27 12:40:18 -07003701 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003702 // check if buffer size is set for color layer.
3703 if (w > 0 || h > 0) {
3704 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3705 int(w), int(h));
3706 return BAD_VALUE;
3707 }
3708
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003709 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3710 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003711 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003712 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003713 // check if buffer size is set for container layer.
3714 if (w > 0 || h > 0) {
3715 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3716 int(w), int(h));
3717 return BAD_VALUE;
3718 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003719 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3720 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003721 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003722 default:
3723 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724 break;
3725 }
3726
Dan Stoza7d89d062015-04-30 13:29:25 -07003727 if (result != NO_ERROR) {
3728 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003730
Evan Roskya1f1e152019-01-24 16:17:46 -08003731 if (primaryDisplayOnly) {
3732 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003733 }
3734
Robert Carrb89ea9d2018-12-10 13:01:14 -08003735 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003736 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3737 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003738 if (result != NO_ERROR) {
3739 return result;
3740 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003741 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003742
3743 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003745}
3746
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003747std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3748 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003749
3750 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003751 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003752
Dan Stoza436ccf32018-06-21 12:10:12 -07003753 // Grab the state lock since we're accessing mCurrentState
3754 Mutex::Autolock lock(mStateLock);
3755
Cody Northropbc755282017-03-31 12:00:08 -06003756 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003757 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003758 while (matchFound) {
3759 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003760 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003761 if (layer->getName() == uniqueName) {
3762 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003763 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003764 }
3765 });
3766 }
3767
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003768 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003769 return uniqueName;
3770}
3771
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003772status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003773 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003774 LayerMetadata metadata, PixelFormat& format,
3775 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003776 sp<IGraphicBufferProducer>* gbp,
3777 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003778 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003779 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003780 case PIXEL_FORMAT_TRANSPARENT:
3781 case PIXEL_FORMAT_TRANSLUCENT:
3782 format = PIXEL_FORMAT_RGBA_8888;
3783 break;
3784 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003785 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003786 break;
3787 }
3788
chaviwb4c6e582019-08-16 14:35:07 -07003789 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003790 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003791 args.textureName = getNewTexture();
3792 {
3793 // Grab the SF state lock during this since it's the only safe way to access
3794 // RenderEngine when creating a BufferLayerConsumer
3795 // TODO: Check if this lock is still needed here
3796 Mutex::Autolock lock(mStateLock);
3797 layer = getFactory().createBufferQueueLayer(args);
3798 }
3799
Marissa Wallfd668622018-05-10 10:21:13 -07003800 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003801 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003802 *handle = layer->getHandle();
3803 *gbp = layer->getProducer();
3804 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003806
Marissa Wallfd668622018-05-10 10:21:13 -07003807 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003808 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809}
3810
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003811status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003812 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003813 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003814 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003815 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003816 args.displayDevice = getDefaultDisplayDevice();
3817 args.textureName = getNewTexture();
3818 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003819 if (outTransformHint) {
3820 *outTransformHint = layer->getTransformHint();
3821 }
Marissa Wall61c58622018-07-18 10:12:20 -07003822 *handle = layer->getHandle();
3823 *outLayer = layer;
3824
3825 return NO_ERROR;
3826}
3827
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003828status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003829 uint32_t h, uint32_t flags, LayerMetadata metadata,
3830 sp<IBinder>* handle, sp<Layer>* outLayer) {
3831 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003832 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003833 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003834 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003835}
3836
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003837status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003838 uint32_t w, uint32_t h, uint32_t flags,
3839 LayerMetadata metadata, sp<IBinder>* handle,
3840 sp<Layer>* outLayer) {
3841 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003842 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003843 *handle = (*outLayer)->getHandle();
3844 return NO_ERROR;
3845}
3846
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003847void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003848 mLayersPendingRemoval.add(layer);
3849 mLayersRemoved = true;
3850 setTransactionFlags(eTransactionNeeded);
3851}
3852
Robert Carr695d5282018-12-18 15:27:58 -08003853void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003854{
Robert Carr2e102c92018-10-23 12:11:15 -07003855 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003856 // If a layer has a parent, we allow it to out-live it's handle
3857 // with the idea that the parent holds a reference and will eventually
3858 // be cleaned up. However no one cleans up the top-level so we do so
3859 // here.
3860 if (layer->getParent() == nullptr) {
3861 mCurrentState.layersSortedByZ.remove(layer);
3862 }
3863 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003864
3865 auto it = mLayersByLocalBinderToken.begin();
3866 while (it != mLayersByLocalBinderToken.end()) {
3867 if (it->second == layer) {
3868 it = mLayersByLocalBinderToken.erase(it);
3869 } else {
3870 it++;
3871 }
3872 }
3873
Robert Carr695d5282018-12-18 15:27:58 -08003874 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003875}
3876
Mathias Agopianb60314a2012-04-10 22:09:54 -07003877// ---------------------------------------------------------------------------
3878
Andy McFadden13a082e2012-08-24 10:16:42 -07003879void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003880 const auto display = getDefaultDisplayDeviceLocked();
3881 if (!display) return;
3882
3883 const sp<IBinder> token = display->getDisplayToken().promote();
3884 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003885
Jesse Hall01e29052013-02-19 16:13:35 -08003886 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003887 Vector<ComposerState> state;
3888 Vector<DisplayState> displays;
3889 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003890 d.what = DisplayState::eDisplayProjectionChanged |
3891 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003892 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003893 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003894 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003895 d.frame.makeInvalid();
3896 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003897 d.width = 0;
3898 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003899 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003900 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3901 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003902
Dominik Laskowskie9774092018-12-11 10:04:24 -08003903 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003904
Dominik Laskowski83b88212018-12-11 13:34:06 -08003905 const nsecs_t vsyncPeriod = getVsyncPeriod();
3906 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003907
Brian Andersond0010582017-03-07 13:20:31 -08003908 // Use phase of 0 since phase is not known.
3909 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003910 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003911 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003912}
3913
3914void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003915 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003916 postMessageAsync(
3917 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003918}
3919
Ady Abraham27c70212019-06-11 10:52:26 -07003920void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3921 if (mHWCVsyncState != enabled) {
3922 getHwComposer().setVsyncEnabled(displayId, enabled);
3923 mHWCVsyncState = enabled;
3924 }
3925}
3926
Dominik Laskowskie9774092018-12-11 10:04:24 -08003927void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003928 if (display->isVirtual()) {
3929 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003930 return;
3931 }
3932
Dominik Laskowski075d3172018-05-24 15:50:06 -07003933 const auto displayId = display->getId();
3934 LOG_ALWAYS_FATAL_IF(!displayId);
3935
Dominik Laskowski34157762018-10-31 13:07:19 -07003936 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003937
3938 int currentMode = display->getPowerMode();
3939 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003940 return;
3941 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003943 display->setPowerMode(mode);
3944
Lloyd Pique4dccc412018-01-22 17:21:36 -08003945 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003946 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003947 }
3948
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003949 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003950 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003952 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003953 mScheduler->onScreenAcquired(mAppConnectionHandle);
3954 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003955 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003956
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003957 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003958 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003959 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003960
3961 struct sched_param param = {0};
3962 param.sched_priority = 1;
3963 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3964 ALOGW("Couldn't set SCHED_FIFO on display on");
3965 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003966 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003967 // Turn off the display
3968 struct sched_param param = {0};
3969 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3970 ALOGW("Couldn't set SCHED_OTHER on display off");
3971 }
3972
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003973 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003974 mScheduler->disableHardwareVsync(true);
3975 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003976 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003977
Ady Abraham27c70212019-06-11 10:52:26 -07003978 // Make sure HWVsync is disabled before turning off the display
3979 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3980
Dominik Laskowski075d3172018-05-24 15:50:06 -07003981 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003982 mVisibleRegionsDirty = true;
3983 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003984 } else if (mode == HWC_POWER_MODE_DOZE ||
3985 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003986 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003987 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003988 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003989 mScheduler->onScreenAcquired(mAppConnectionHandle);
3990 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003991 }
3992 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3993 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003995 mScheduler->disableHardwareVsync(true);
3996 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003997 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003998 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003999 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004000 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004001 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004003
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004004 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004005 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004006 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004007 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004008 }
4009
Dominik Laskowski34157762018-10-31 13:07:19 -07004010 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004011}
4012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004013void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004014 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004015 const auto display = getDisplayDevice(displayToken);
4016 if (!display) {
4017 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4018 displayToken.get());
4019 } else if (display->isVirtual()) {
4020 ALOGW("Attempt to set power mode %d for virtual display", mode);
4021 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004022 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004023 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004024 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004025}
4026
4027// ---------------------------------------------------------------------------
4028
Dominik Laskowskic2867142019-01-21 11:33:38 -08004029status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4030 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004031 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004032
Mathias Agopianbd115332013-04-18 16:41:04 -07004033 IPCThreadState* ipc = IPCThreadState::self();
4034 const int pid = ipc->getCallingPid();
4035 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004036
Mathias Agopianbd115332013-04-18 16:41:04 -07004037 if ((uid != AID_SHELL) &&
4038 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004039 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4040 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004042 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004043 // (this would indicate SF is stuck, but we want to be able to
4044 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004045 status_t err = mStateLock.timedLock(s2ns(1));
4046 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004047 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004048 StringAppendF(&result,
4049 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4050 "(no locks held)\n",
4051 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004052 }
4053
Dominik Laskowskic2867142019-01-21 11:33:38 -08004054 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004055 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004056 {"--dispsync"s,
4057 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004058 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004059 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4060 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4061 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4062 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4063 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4064 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004065 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004066 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4067 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004068
Dominik Laskowskic2867142019-01-21 11:33:38 -08004069 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004070
Dominik Laskowski46470112019-08-02 13:13:11 -07004071 const auto it = dumpers.find(flag);
4072 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004073 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004074 } else if (!asProto) {
4075 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004076 }
4077
Mathias Agopian9795c422009-08-26 16:36:26 -07004078 if (locked) {
4079 mStateLock.unlock();
4080 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004081
Dominik Laskowski46470112019-08-02 13:13:11 -07004082 if (it == dumpers.end()) {
4083 const LayersProto layersProto = dumpProtoFromMainThread();
4084 if (asProto) {
4085 result.append(layersProto.SerializeAsString());
4086 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004087 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004088 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4089 result.append(LayerProtoParser::layerTreeToString(layerTree));
4090 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004091 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004092 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004093 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004095 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004096 return NO_ERROR;
4097}
4098
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004099status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4100 if (asProto && mTracing.isEnabled()) {
4101 mTracing.writeToFileAsync();
4102 }
4103
4104 return doDump(fd, DumpArgs(), asProto);
4105}
4106
Dominik Laskowskic2867142019-01-21 11:33:38 -08004107void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004108 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004109 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004110}
4111
Dominik Laskowskic2867142019-01-21 11:33:38 -08004112void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004113 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004114
Dominik Laskowskic2867142019-01-21 11:33:38 -08004115 if (args.size() > 1) {
4116 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004117 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004118 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004119 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004120 }
Robert Carr2047fae2016-11-28 14:09:09 -08004121 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004122 } else {
4123 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004124 }
4125}
4126
Dominik Laskowskic2867142019-01-21 11:33:38 -08004127void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004128 const bool clearAll = args.size() < 2;
4129 const auto name = clearAll ? String8() : String8(args[1]);
4130
Edgar Arriaga844fa672020-01-16 14:21:42 -08004131 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004132 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004133 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004134 }
Robert Carr2047fae2016-11-28 14:09:09 -08004135 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004136
Svetoslavd85084b2014-03-20 10:28:31 -07004137 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004138}
4139
Dominik Laskowskic2867142019-01-21 11:33:38 -08004140void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4141 mTimeStats->parseArgs(asProto, args, result);
4142}
4143
Jamie Gennis6547ff42013-07-16 20:12:42 -07004144// This should only be called from the main thread. Otherwise it would need
4145// the lock and should use mCurrentState rather than mDrawingState.
4146void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004147 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004148 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004149 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004150
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004151 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004152}
4153
Yiwei Zhang5434a782018-12-05 18:06:32 -08004154void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004155 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004156
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004157 if (isLayerTripleBufferingDisabled())
4158 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004159
Yiwei Zhang5434a782018-12-05 18:06:32 -08004160 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4161 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4162 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4163 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4164 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4165 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004166 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004167}
4168
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004169void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004170 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004171
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004172 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004173 result.append("\n");
4174
Ady Abraham9e16a482019-12-03 17:19:41 -08004175 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004176 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004177 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004178 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004179
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004180 HwcConfigIndexType defaultConfig;
4181 float minFps, maxFps;
4182 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004183 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004184 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004185 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004186 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004187 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4188 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004189
Ana Krulecc2870422019-01-29 19:00:58 -08004190 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004191}
4192
Yiwei Zhang5434a782018-12-05 18:06:32 -08004193void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4194 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004195 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4196 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004197 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004198 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004199 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004200 }
David Sodman4a36e932017-11-07 14:29:47 -08004201 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004202 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004203 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004204 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4205 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004206}
4207
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004208void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4209 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004210 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4211 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004212 for (const auto& segment : history) {
4213 if (!segment.usedThirdBuffer) {
4214 stats.twoBufferTime += segment.totalTime;
4215 }
4216 if (segment.occupancyAverage < 1.0f) {
4217 stats.doubleBufferedTime += segment.totalTime;
4218 } else if (segment.occupancyAverage < 2.0f) {
4219 stats.tripleBufferedTime += segment.totalTime;
4220 }
4221 ++stats.numSegments;
4222 stats.totalTime += segment.totalTime;
4223 }
4224}
4225
Yiwei Zhang5434a782018-12-05 18:06:32 -08004226void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4227 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004228
4229 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4230 const size_t count = currentLayers.size();
4231 for (size_t i=0 ; i<count ; i++) {
4232 currentLayers[i]->dumpFrameEvents(result);
4233 }
4234}
4235
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004237 result.append("Buffering stats:\n");
4238 result.append(" [Layer name] <Active time> <Two buffer> "
4239 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004240 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004241 typedef std::tuple<std::string, float, float, float> BufferTuple;
4242 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004243 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004244 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004245 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004246 if (stats.numSegments == 0) {
4247 continue;
4248 }
4249 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4250 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4251 stats.totalTime;
4252 float doubleBufferRatio = static_cast<float>(
4253 stats.doubleBufferedTime) / stats.totalTime;
4254 float tripleBufferRatio = static_cast<float>(
4255 stats.tripleBufferedTime) / stats.totalTime;
4256 sorted.insert({activeTime, {name, twoBufferRatio,
4257 doubleBufferRatio, tripleBufferRatio}});
4258 }
4259 for (const auto& sortedPair : sorted) {
4260 float activeTime = sortedPair.first;
4261 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004262 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4263 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004264 }
4265 result.append("\n");
4266}
4267
Yiwei Zhang5434a782018-12-05 18:06:32 -08004268void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004269 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004270 const auto displayId = display->getId();
4271 if (!displayId) {
4272 continue;
4273 }
4274 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004275 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004276 continue;
4277 }
4278
Yiwei Zhang5434a782018-12-05 18:06:32 -08004279 StringAppendF(&result,
4280 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4281 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004282 uint8_t port;
4283 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004284 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004285 result.append("no identification data\n");
4286 continue;
4287 }
4288
4289 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004290 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004291 continue;
4292 }
4293
4294 const auto edid = parseEdid(data);
4295 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004296 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004297 continue;
4298 }
4299
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004301 result.append(edid->displayName.data(), edid->displayName.length());
4302 result.append("\"\n");
4303 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004304}
4305
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004306void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4307 std::string& result) const {
4308 hwc2_display_t hwcDisplayId;
4309 uint8_t port;
4310 DisplayIdentificationData data;
4311
4312 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4313 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4314 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4315 }
4316}
4317
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004319 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004320 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4321 StringAppendF(&result, "DisplayColorSetting: %s\n",
4322 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004323
4324 // TODO: print out if wide-color mode is active or not
4325
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004326 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004327 const auto displayId = display->getId();
4328 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004329 continue;
4330 }
4331
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004333 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004334 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004335 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004336 }
4337
Lloyd Pique32cbe282018-10-19 13:09:22 -07004338 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004339 StringAppendF(&result, " Current color mode: %s (%d)\n",
4340 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004341 }
4342 result.append("\n");
4343}
4344
Vishnu Nair8406fd72019-07-30 11:29:31 -07004345LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004346 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004347 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4348 layer->writeToProto(layersProto, traceFlags);
4349 }
chaviw1d044282017-09-27 12:19:28 -07004350 return layersProto;
4351}
4352
Vishnu Nair0f085c62019-08-30 08:49:12 -07004353void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4354 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4355 // it.
4356 LayerProto* rootProto = layersProto.add_layers();
4357 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4358 rootProto->set_id(offscreenRootLayerId);
4359 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004360 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004361
4362 for (Layer* offscreenLayer : mOffscreenLayers) {
4363 // Add layer as child of the fake root
4364 rootProto->add_children(offscreenLayer->sequence);
4365
4366 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004367 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004368 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004369 }
4370}
4371
Vishnu Nair8406fd72019-07-30 11:29:31 -07004372LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4373 LayersProto layersProto;
4374 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4375 return layersProto;
4376}
4377
Vishnu Nair0f085c62019-08-30 08:49:12 -07004378void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4379 result.append("Offscreen Layers:\n");
4380 postMessageSync(new LambdaMessage([&]() {
4381 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004382 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004383 layer->dumpCallingUidPid(result);
4384 });
4385 }
4386 }));
4387}
4388
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4390 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004391 Colorizer colorizer(colorize);
4392
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393 // figure out if we're stuck somewhere
4394 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4397
4398 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004399 * Dump library configuration.
4400 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004401
4402 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004403 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004404 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004405 appendSfConfigString(result);
4406 appendUiConfigString(result);
4407 appendGuiConfigString(result);
4408 result.append("\n");
4409
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004410 result.append("\nDisplay identification data:\n");
4411 dumpDisplayIdentificationData(result);
4412
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004413 result.append("\nWide-Color information:\n");
4414 dumpWideColorInfo(result);
4415
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004417 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004418 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004419 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004420 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004421
Andy McFadden41d67d72014-04-25 16:58:34 -07004422 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004423 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004424 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004425 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004426 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004427
Dan Stozab90cf072015-03-05 11:05:59 -08004428 dumpStaticScreenStats(result);
4429 result.append("\n");
4430
Alec Mouri40189b02019-03-05 15:07:54 -08004431 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4432 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4433 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004434
Dan Stozae77c7662016-05-13 11:37:28 -07004435 dumpBufferingStats(result);
4436
Andy McFadden4803b742012-09-24 19:07:20 -07004437 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004438 * Dump the visible layer list
4439 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004440 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004441 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4443 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004444 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004445
Chia-I Wu2f884132018-09-13 15:17:58 -07004446 {
Lloyd Pique207def92019-02-28 16:09:52 -08004447 StringAppendF(&result, "Composition layers\n");
4448 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004449 auto* compositionState = layer->getCompositionState();
4450 if (!compositionState) return;
4451
4452 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4453 layer->getDebugName() ? layer->getDebugName()
4454 : "<unknown>");
4455 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004456 });
4457 }
4458
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004460 * Dump Display state
4461 */
4462
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004463 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004464 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004465 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004466 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004467 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004468 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004469 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004470
4471 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004472 * Dump CompositionEngine state
4473 */
4474
4475 mCompositionEngine->dump(result);
4476
4477 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004478 * Dump SurfaceFlinger global state
4479 */
4480
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004481 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004482 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004483 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004485 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004486
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004487 DebugEGLImageTracker::getInstance()->dump(result);
4488
Dominik Laskowski075d3172018-05-24 15:50:06 -07004489 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004490 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4491 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004492 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4493 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004494 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495 StringAppendF(&result,
4496 " transaction-flags : %08x\n"
4497 " gpu_to_cpu_unsupported : %d\n",
4498 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004500 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004501 displayId && getHwComposer().isConnected(*displayId)) {
4502 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503 StringAppendF(&result,
4504 " refresh-rate : %f fps\n"
4505 " x-dpi : %f\n"
4506 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004507 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4508 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004509 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004512
Dan Stozae22aec72016-08-01 13:20:59 -07004513 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004514 * Tracing state
4515 */
4516 mTracing.dump(result);
4517 result.append("\n");
4518
4519 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004520 * HWC layer minidump
4521 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004522 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004523 const auto displayId = display->getId();
4524 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004525 continue;
4526 }
4527
Yiwei Zhang5434a782018-12-05 18:06:32 -08004528 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004529 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004530 const sp<DisplayDevice> displayDevice = display;
4531 mCurrentState.traverseInZOrder(
4532 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004533 result.append("\n");
4534 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535
4536 /*
4537 * Dump HWComposer state
4538 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004539 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004540 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004541 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004542 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004544 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004545
4546 /*
4547 * Dump gralloc state
4548 */
4549 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4550 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004551
4552 /*
4553 * Dump VrFlinger state if in use.
4554 */
4555 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4556 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004557 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004558 result.append("\n");
4559 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004560
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004561 result.append(mTimeStats->miniDump());
4562 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563}
4564
Chia-I Wu28f320b2018-05-03 11:02:56 -07004565void SurfaceFlinger::updateColorMatrixLocked() {
4566 mat4 colorMatrix;
4567 if (mGlobalSaturationFactor != 1.0f) {
4568 // Rec.709 luma coefficients
4569 float3 luminance{0.213f, 0.715f, 0.072f};
4570 luminance *= 1.0f - mGlobalSaturationFactor;
4571 mat4 saturationMatrix = mat4(
4572 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4573 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4574 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4575 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4576 );
4577 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4578 } else {
4579 colorMatrix = mClientColorMatrix * mDaltonizer();
4580 }
4581
4582 if (mCurrentState.colorMatrix != colorMatrix) {
4583 mCurrentState.colorMatrix = colorMatrix;
4584 mCurrentState.colorMatrixChanged = true;
4585 setTransactionFlags(eTransactionNeeded);
4586 }
4587}
4588
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004589status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004590#pragma clang diagnostic push
4591#pragma clang diagnostic error "-Wswitch-enum"
4592 switch (static_cast<ISurfaceComposerTag>(code)) {
4593 // These methods should at minimum make sure that the client requested
4594 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004595 case BOOT_FINISHED:
4596 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004597 case CREATE_DISPLAY:
4598 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004599 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004600 case GET_ANIMATION_FRAME_STATS:
4601 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004602 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004603 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004604 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004605 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4606 case SET_AUTO_LOW_LATENCY_MODE:
4607 case GET_GAME_CONTENT_TYPE_SUPPORT:
4608 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004609 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004610 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004611 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004612 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004613 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004614 case NOTIFY_POWER_HINT:
4615 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004616 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4617 IPCThreadState* ipc = IPCThreadState::self();
4618 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4619 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004620 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004621 }
Robert Carr1db73f62016-12-21 12:58:51 -08004622 return OK;
4623 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004624 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004625 IPCThreadState* ipc = IPCThreadState::self();
4626 const int pid = ipc->getCallingPid();
4627 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004628 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4629 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004630 return PERMISSION_DENIED;
4631 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004632 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004633 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004634 // Used by apps to hook Choreographer to SurfaceFlinger.
4635 case CREATE_DISPLAY_EVENT_CONNECTION:
4636 // The following calls are currently used by clients that do not
4637 // request necessary permissions. However, they do not expose any secret
4638 // information, so it is OK to pass them.
4639 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004640 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004641 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004642 case GET_PHYSICAL_DISPLAY_IDS:
4643 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004644 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004645 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004646 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004647 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004648 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004649 case GET_DISPLAY_STATS:
4650 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4651 // Calling setTransactionState is safe, because you need to have been
4652 // granted a reference to Client* and Handle* to do anything with it.
4653 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004654 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004655 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004656 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004657 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004658 case IS_WIDE_COLOR_DISPLAY:
4659 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4660 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004661 return OK;
4662 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004663 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004664 case CAPTURE_SCREEN:
4665 case ADD_REGION_SAMPLING_LISTENER:
4666 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004667 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004668 IPCThreadState* ipc = IPCThreadState::self();
4669 const int pid = ipc->getCallingPid();
4670 const int uid = ipc->getCallingUid();
4671 if ((uid != AID_GRAPHICS) &&
4672 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4673 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4674 return PERMISSION_DENIED;
4675 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004676 return OK;
4677 }
chaviw93df2ea2019-04-30 16:45:12 -07004678 case CAPTURE_SCREEN_BY_ID: {
4679 IPCThreadState* ipc = IPCThreadState::self();
4680 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004681 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004682 return OK;
4683 }
4684 return PERMISSION_DENIED;
4685 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004687
4688 // These codes are used for the IBinder protocol to either interrogate the recipient
4689 // side of the transaction for its canonical interface descriptor or to dump its state.
4690 // We let them pass by default.
4691 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4692 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4693 code == IBinder::SYSPROPS_TRANSACTION) {
4694 return OK;
4695 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004696 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004697 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004698 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004699 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4700 return OK;
4701 }
4702 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4703 return PERMISSION_DENIED;
4704#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004705}
4706
Ana Krulec13be8ad2018-08-21 02:43:56 +00004707status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4708 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004709 status_t credentialCheck = CheckTransactCodeCredentials(code);
4710 if (credentialCheck != OK) {
4711 return credentialCheck;
4712 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4715 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004716 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004717 IPCThreadState* ipc = IPCThreadState::self();
4718 const int uid = ipc->getCallingUid();
4719 if (CC_UNLIKELY(uid != AID_SYSTEM
4720 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004721 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004722 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004723 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004724 return PERMISSION_DENIED;
4725 }
4726 int n;
4727 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004728 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004729 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004730 return NO_ERROR;
4731 case 1002: // SHOW_UPDATES
4732 n = data.readInt32();
4733 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004734 invalidateHwcGeometry();
4735 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004737 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004738 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004739 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004740 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004741 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004742 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004743 setTransactionFlags(
4744 eTransactionNeeded|
4745 eDisplayTransactionNeeded|
4746 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004747 return NO_ERROR;
4748 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004749 case 1006:{ // send empty update
4750 signalRefresh();
4751 return NO_ERROR;
4752 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004753 case 1008: // toggle use of hw composer
4754 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004755 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004756 invalidateHwcGeometry();
4757 repaintEverything();
4758 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004759 case 1009: // toggle use of transform hint
4760 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004761 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004762 invalidateHwcGeometry();
4763 repaintEverything();
4764 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004765 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004766 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004767 reply->writeInt32(0);
4768 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004769 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004770 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004771 return NO_ERROR;
4772 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004773 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004774 if (!display) {
4775 return NAME_NOT_FOUND;
4776 }
4777
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004778 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004779 return NO_ERROR;
4780 }
4781 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004782 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004783 // daltonize
4784 n = data.readInt32();
4785 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004786 case 1:
4787 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4788 break;
4789 case 2:
4790 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4791 break;
4792 case 3:
4793 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4794 break;
4795 default:
4796 mDaltonizer.setType(ColorBlindnessType::None);
4797 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004798 }
4799 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004800 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004801 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004802 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004803 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004804
4805 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004806 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004807 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004808 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004809 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004810 // apply a color matrix
4811 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004812 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004813 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004814 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004815 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004816 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004817 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004818 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004819 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004820 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004821 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004822
4823 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4824 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004825 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004826 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4827 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4828 }
4829
Chia-I Wu28f320b2018-05-03 11:02:56 -07004830 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004831 return NO_ERROR;
4832 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004833 case 1016: { // Unused.
4834 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004835 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004836 case 1017: {
4837 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004838 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004839 return NO_ERROR;
4840 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004841 case 1018: { // Modify Choreographer's phase offset
4842 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004843 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004844 return NO_ERROR;
4845 }
4846 case 1019: { // Modify SurfaceFlinger's phase offset
4847 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004848 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004849 return NO_ERROR;
4850 }
Irvel468051e2016-06-13 16:44:44 -07004851 case 1020: { // Layer updates interceptor
4852 n = data.readInt32();
4853 if (n) {
4854 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004855 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004856 }
4857 else{
4858 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004859 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004860 }
4861 return NO_ERROR;
4862 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004863 case 1021: { // Disable HWC virtual displays
4864 n = data.readInt32();
4865 mUseHwcVirtualDisplays = !n;
4866 return NO_ERROR;
4867 }
Romain Guy0147a172017-06-01 13:53:56 -07004868 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004870 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004871
Chia-I Wu28f320b2018-05-03 11:02:56 -07004872 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004873 return NO_ERROR;
4874 }
Romain Guy54f154a2017-10-24 21:40:32 +01004875 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004876 int32_t colorMode;
4877
Chia-I Wu0d711262018-05-21 15:19:35 -07004878 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004879 if (data.readInt32(&colorMode) == NO_ERROR) {
4880 mForceColorMode = static_cast<ColorMode>(colorMode);
4881 }
Romain Guy54f154a2017-10-24 21:40:32 +01004882 invalidateHwcGeometry();
4883 repaintEverything();
4884 return NO_ERROR;
4885 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004886 // Deprecate, use 1030 to check whether the device is color managed.
4887 case 1024: {
4888 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004889 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004890 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004891 n = data.readInt32();
4892 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004893 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004894 Mutex::Autolock lock(mStateLock);
4895 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004896 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004897 reply->writeInt32(NO_ERROR);
4898 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004899 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004900 bool writeFile = false;
4901 {
4902 Mutex::Autolock lock(mStateLock);
4903 mTracingEnabledChanged = true;
4904 writeFile = mTracing.disable();
4905 }
4906
4907 if (writeFile) {
4908 reply->writeInt32(mTracing.writeToFile());
4909 } else {
4910 reply->writeInt32(NO_ERROR);
4911 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004912 }
4913 return NO_ERROR;
4914 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004915 case 1026: { // Get layer tracing status
4916 reply->writeBool(mTracing.isEnabled());
4917 return NO_ERROR;
4918 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004919 // Is a DisplayColorSetting supported?
4920 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004921 const auto display = getDefaultDisplayDevice();
4922 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004923 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004924 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004925
4926 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4927 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004928 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004929 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004930 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004931 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004932 reply->writeBool(true);
4933 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004934 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004935 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004936 break;
4937 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004938 reply->writeBool(
4939 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004940 break;
4941 }
4942 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004943 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004944 // Is VrFlinger active?
4945 case 1028: {
4946 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004947 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004948 return NO_ERROR;
4949 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004950 // Set buffer size for SF tracing (value in KB)
4951 case 1029: {
4952 n = data.readInt32();
4953 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4954 ALOGW("Invalid buffer size: %d KB", n);
4955 reply->writeInt32(BAD_VALUE);
4956 return BAD_VALUE;
4957 }
4958
4959 ALOGD("Updating trace buffer to %d KB", n);
4960 mTracing.setBufferSize(n * 1024);
4961 reply->writeInt32(NO_ERROR);
4962 return NO_ERROR;
4963 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004964 // Is device color managed?
4965 case 1030: {
4966 reply->writeBool(useColorManagement);
4967 return NO_ERROR;
4968 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004969 // Override default composition data space
4970 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4971 // && adb shell stop zygote && adb shell start zygote
4972 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4973 // adb shell stop zygote && adb shell start zygote
4974 case 1031: {
4975 Mutex::Autolock _l(mStateLock);
4976 n = data.readInt32();
4977 if (n) {
4978 n = data.readInt32();
4979 if (n) {
4980 Dataspace dataspace = static_cast<Dataspace>(n);
4981 if (!validateCompositionDataspace(dataspace)) {
4982 return BAD_VALUE;
4983 }
4984 mDefaultCompositionDataspace = dataspace;
4985 }
4986 n = data.readInt32();
4987 if (n) {
4988 Dataspace dataspace = static_cast<Dataspace>(n);
4989 if (!validateCompositionDataspace(dataspace)) {
4990 return BAD_VALUE;
4991 }
4992 mWideColorGamutCompositionDataspace = dataspace;
4993 }
4994 } else {
4995 // restore composition data space.
4996 mDefaultCompositionDataspace = defaultCompositionDataspace;
4997 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4998 }
4999 return NO_ERROR;
5000 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005001 // Set trace flags
5002 case 1033: {
5003 n = data.readUint32();
5004 ALOGD("Updating trace flags to 0x%x", n);
5005 mTracing.setTraceFlags(n);
5006 reply->writeInt32(NO_ERROR);
5007 return NO_ERROR;
5008 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005009 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005010 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005011 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005012 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005013 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5014 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005015 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005016 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005017 } else {
5018 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005019 }
5020 return NO_ERROR;
5021 }
Ady Abraham34392f72019-04-10 11:29:27 -07005022 case 1035: {
5023 n = data.readInt32();
5024 mDebugDisplayConfigSetByBackdoor = false;
5025 if (n >= 0) {
5026 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005027 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005028 if (result != NO_ERROR) {
5029 return result;
5030 }
5031 mDebugDisplayConfigSetByBackdoor = true;
5032 }
5033 return NO_ERROR;
5034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 }
5036 }
5037 return err;
5038}
5039
Steven Thomas6d8110b2017-08-31 18:24:21 -07005040void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005041 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005042 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005043}
5044
Ana Krulec7d1d6832018-12-27 11:10:09 -08005045void SurfaceFlinger::repaintEverythingForHWC() {
5046 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005047 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005048}
5049
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005050// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5051class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005052public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005053 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5054 ~WindowDisconnector() {
5055 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005056 }
5057
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005058private:
5059 ANativeWindow* mWindow;
5060 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005061};
5062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005063status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005064 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005065 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5066 const Rect& sourceCrop, uint32_t reqWidth,
5067 uint32_t reqHeight, bool useIdentityTransform,
5068 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005069 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005071 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005072
Dominik Laskowski718f9602019-11-09 20:01:35 -08005073 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5074 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5075 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5076 renderAreaRotation = ui::Transform::ROT_0;
5077 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005078
Chia-I Wu20261cb2018-08-23 12:55:44 -07005079 sp<DisplayDevice> display;
5080 {
5081 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005082
Chia-I Wu20261cb2018-08-23 12:55:44 -07005083 display = getDisplayDeviceLocked(displayToken);
5084 if (!display) return BAD_VALUE;
5085
Chia-I Wucb023152018-08-28 12:57:23 -07005086 // set the requested width/height to the logical display viewport size
5087 // by default
5088 if (reqWidth == 0 || reqHeight == 0) {
5089 reqWidth = uint32_t(display->getViewport().width());
5090 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005091 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005092 }
5093
Peiyong Lin0e003c92018-09-17 11:09:51 -07005094 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005095 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005096
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005097 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5098 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005099 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005100 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005101}
5102
chaviw93df2ea2019-04-30 16:45:12 -07005103static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5104 switch (colorMode) {
5105 case ColorMode::DISPLAY_P3:
5106 case ColorMode::BT2100_PQ:
5107 case ColorMode::BT2100_HLG:
5108 case ColorMode::DISPLAY_BT2020:
5109 return Dataspace::DISPLAY_P3;
5110 default:
5111 return Dataspace::V0_SRGB;
5112 }
5113}
5114
5115const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5116 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5117 if (displayToken) {
5118 return getDisplayDeviceLocked(displayToken);
5119 }
5120 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5121 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005122 return getDisplayByLayerStack(displayOrLayerStack);
5123}
5124
5125const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005126 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005127 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005128 return display;
5129 }
5130 }
5131 return nullptr;
5132}
5133
5134status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5135 sp<GraphicBuffer>* outBuffer) {
5136 sp<DisplayDevice> display;
5137 uint32_t width;
5138 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005139 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005140 {
5141 Mutex::Autolock _l(mStateLock);
5142 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5143 if (!display) {
5144 return BAD_VALUE;
5145 }
5146
5147 width = uint32_t(display->getViewport().width());
5148 height = uint32_t(display->getViewport().height());
5149
Dominik Laskowski718f9602019-11-09 20:01:35 -08005150 const auto orientation = display->getOrientation();
5151 captureOrientation = ui::Transform::toRotationFlags(orientation);
5152
5153 switch (captureOrientation) {
5154 case ui::Transform::ROT_90:
5155 captureOrientation = ui::Transform::ROT_270;
5156 break;
5157
5158 case ui::Transform::ROT_270:
5159 captureOrientation = ui::Transform::ROT_90;
5160 break;
5161
5162 case ui::Transform::ROT_INVALID:
5163 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5164 captureOrientation = ui::Transform::ROT_0;
5165 break;
5166
5167 default:
5168 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005169 }
chaviw93df2ea2019-04-30 16:45:12 -07005170 *outDataspace =
5171 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5172 }
5173
5174 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5175 false /* captureSecureLayers */);
5176
5177 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5178 std::placeholders::_1);
5179 bool ignored = false;
5180 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5181 false /* useIdentityTransform */,
5182 ignored /* outCapturedSecureLayers */);
5183}
5184
Robert Carr866455f2019-04-02 16:28:26 -07005185status_t SurfaceFlinger::captureLayers(
5186 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5187 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5188 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5189 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005190 ATRACE_CALL();
5191
5192 class LayerRenderArea : public RenderArea {
5193 public:
Robert Carr578038f2018-03-09 12:25:24 -08005194 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005195 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005196 bool childrenOnly, const Rect& displayViewport)
5197 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005198 mLayer(layer),
5199 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005200 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005201 mFlinger(flinger),
5202 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005203 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005204 Rect getBounds() const override {
5205 const Layer::State& layerState(mLayer->getDrawingState());
5206 return mLayer->getBufferSize(layerState);
5207 }
Marissa Wall61c58622018-07-18 10:12:20 -07005208 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005209 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005210 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005211 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005212 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005213 }
chaviwa76b2712017-09-20 12:02:26 -07005214 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005215 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005216 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005217 Rect getSourceCrop() const override {
5218 if (mCrop.isEmpty()) {
5219 return getBounds();
5220 } else {
5221 return mCrop;
5222 }
5223 }
Robert Carr578038f2018-03-09 12:25:24 -08005224 class ReparentForDrawing {
5225 public:
5226 const sp<Layer>& oldParent;
5227 const sp<Layer>& newParent;
5228
Vishnu Nair4351ad52019-02-11 14:13:02 -08005229 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5230 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005231 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005232 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005233 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5234 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005235 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005236 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005237 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005238 };
5239
5240 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005241 const Rect sourceCrop = getSourceCrop();
5242 // no need to check rotation because there is none
5243 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5244 sourceCrop.height() != getReqHeight();
5245
Robert Carr578038f2018-03-09 12:25:24 -08005246 if (!mChildrenOnly) {
5247 mTransform = mLayer->getTransform().inverse();
5248 drawLayers();
5249 } else {
5250 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005251 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5252 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005253 // In the "childrenOnly" case we reparent the children to a screenshot
5254 // layer which has no properties set and which does not draw.
5255 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005256 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5257 "Screenshot Parent"s, w, h, 0,
5258 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005259
Vishnu Nair4351ad52019-02-11 14:13:02 -08005260 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005261 drawLayers();
5262 }
5263 }
chaviwa76b2712017-09-20 12:02:26 -07005264
chaviwa76b2712017-09-20 12:02:26 -07005265 private:
chaviw7206d492017-11-10 16:16:12 -08005266 const sp<Layer> mLayer;
5267 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005268
Peiyong Linefefaac2018-08-17 12:27:51 -07005269 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005270 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005271
5272 SurfaceFlinger* mFlinger;
5273 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005274 };
5275
Robert Carrc0df3122019-04-11 13:18:21 -07005276 int reqWidth = 0;
5277 int reqHeight = 0;
5278 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005279 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005280 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005281 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005282 {
5283 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005284
Robert Carrc0df3122019-04-11 13:18:21 -07005285 parent = fromHandle(layerHandleBinder);
5286 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5287 ALOGE("captureLayers called with an invalid or removed parent");
5288 return NAME_NOT_FOUND;
5289 }
5290
5291 const int uid = IPCThreadState::self()->getCallingUid();
5292 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5293 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5294 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5295 return PERMISSION_DENIED;
5296 }
5297
Vishnu Nairefc42e22019-12-03 17:36:12 -08005298 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005299 if (sourceCrop.width() <= 0) {
5300 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005301 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005302 }
5303
5304 if (sourceCrop.height() <= 0) {
5305 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005306 crop.bottom = parentSourceBounds.getHeight();
5307 }
5308
5309 if (crop.isEmpty() || frameScale <= 0.0f) {
5310 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5311 // crop was not specified, or an invalid frame scale was provided.
5312 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005313 }
5314 reqWidth = crop.width() * frameScale;
5315 reqHeight = crop.height() * frameScale;
5316
5317 for (const auto& handle : excludeHandles) {
5318 sp<Layer> excludeLayer = fromHandle(handle);
5319 if (excludeLayer != nullptr) {
5320 excludeLayers.emplace(excludeLayer);
5321 } else {
5322 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5323 return NAME_NOT_FOUND;
5324 }
5325 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005326
5327 auto display = getDisplayByLayerStack(parent->getLayerStack());
5328 if (!display) {
5329 return BAD_VALUE;
5330 }
5331
5332 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005333 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005334
Chia-I Wu20261cb2018-08-23 12:55:44 -07005335 // really small crop or frameScale
5336 if (reqWidth <= 0) {
5337 reqWidth = 1;
5338 }
5339 if (reqHeight <= 0) {
5340 reqHeight = 1;
5341 }
5342
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005343 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5344 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005345 auto traverseLayers = [parent, childrenOnly,
5346 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005347 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5348 if (!layer->isVisible()) {
5349 return;
Robert Carr578038f2018-03-09 12:25:24 -08005350 } else if (childrenOnly && layer == parent.get()) {
5351 return;
chaviwa76b2712017-09-20 12:02:26 -07005352 }
Robert Carr866455f2019-04-02 16:28:26 -07005353
5354 sp<Layer> p = layer;
5355 while (p != nullptr) {
5356 if (excludeLayers.count(p) != 0) {
5357 return;
5358 }
5359 p = p->getParent();
5360 }
5361
chaviwa76b2712017-09-20 12:02:26 -07005362 visitor(layer);
5363 });
5364 };
Robert Carr108b2c72019-04-02 16:32:58 -07005365
5366 bool outCapturedSecureLayers = false;
5367 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5368 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005369}
5370
5371status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5372 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005373 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005374 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005375 bool useIdentityTransform,
5376 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005377 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005378
Peiyong Lin0e003c92018-09-17 11:09:51 -07005379 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005380 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5381 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005382 *outBuffer =
5383 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5384 static_cast<android_pixel_format>(reqPixelFormat), 1,
5385 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005386
Robert Carr108b2c72019-04-02 16:32:58 -07005387 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5388 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005389}
5390
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005391status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5392 TraverseLayersFunction traverseLayers,
5393 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005394 bool useIdentityTransform,
5395 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005396 // This mutex protects syncFd and captureResult for communication of the return values from the
5397 // main thread back to this Binder thread
5398 std::mutex captureMutex;
5399 std::condition_variable captureCondition;
5400 std::unique_lock<std::mutex> captureLock(captureMutex);
5401 int syncFd = -1;
5402 std::optional<status_t> captureResult;
5403
Robert Carr03480e22018-01-04 16:02:06 -08005404 const int uid = IPCThreadState::self()->getCallingUid();
5405 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5406
Dominik Laskowski8c001672018-05-30 16:52:06 -07005407 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005408 // If there is a refresh pending, bug out early and tell the binder thread to try again
5409 // after the refresh.
5410 if (mRefreshPending) {
5411 ATRACE_NAME("Skipping screenshot for now");
5412 std::unique_lock<std::mutex> captureLock(captureMutex);
5413 captureResult = std::make_optional<status_t>(EAGAIN);
5414 captureCondition.notify_one();
5415 return;
5416 }
5417
5418 status_t result = NO_ERROR;
5419 int fd = -1;
5420 {
5421 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005422 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005423 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005424 useIdentityTransform, forSystem, &fd,
5425 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005426 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005427 }
5428
5429 {
5430 std::unique_lock<std::mutex> captureLock(captureMutex);
5431 syncFd = fd;
5432 captureResult = std::make_optional<status_t>(result);
5433 captureCondition.notify_one();
5434 }
5435 });
5436
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005437 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005438 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005439 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005440 while (*captureResult == EAGAIN) {
5441 captureResult.reset();
5442 result = postMessageAsync(message);
5443 if (result != NO_ERROR) {
5444 return result;
5445 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005446 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005447 }
5448 result = *captureResult;
5449 }
5450
5451 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005452 sync_wait(syncFd, -1);
5453 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005454 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005455
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005456 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005457}
5458
chaviwa76b2712017-09-20 12:02:26 -07005459void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005460 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005461 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5462 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005464
chaviwa76b2712017-09-20 12:02:26 -07005465 const auto reqWidth = renderArea.getReqWidth();
5466 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005467 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005468 const auto transform = renderArea.getTransform();
5469 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005470 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005471
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005472 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005473 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005474
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005475 // assume that bounds are never offset, and that they are the same as the
5476 // buffer bounds.
5477 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005478 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005479 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005480
5481 // Now take into account the rotation flag. We append a transform that
5482 // rotates the layer stack about the origin, then translate by buffer
5483 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005484 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005485 int displacementX = 0;
5486 int displacementY = 0;
5487 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5488 switch (rotation) {
5489 case ui::Transform::ROT_90:
5490 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005491 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005492 break;
5493 case ui::Transform::ROT_180:
5494 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005495 displacementY = renderArea.getBounds().getWidth();
5496 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005497 break;
5498 case ui::Transform::ROT_270:
5499 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005500 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005501 break;
5502 default:
5503 break;
5504 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005505
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005506 // We need to transform the clipping window into the right spot.
5507 // First, rotate the clipping rectangle by the rotation hint to get the
5508 // right orientation
5509 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5510 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5511 const vec4 rotClipTL = rotMatrix * clipTL;
5512 const vec4 rotClipBR = rotMatrix * clipBR;
5513 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5514 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5515 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5516 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5517
5518 // Now reposition the clipping rectangle with the displacement vector
5519 // computed above.
5520 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005521 clientCompositionDisplay.clip =
5522 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5523 newClipRight + displacementX, newClipBottom + displacementY);
5524
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005525 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005526 clientCompositionDisplay.globalTransform =
5527 clipTransform * clientCompositionDisplay.globalTransform;
5528
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005529 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5530 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005531
chaviw50da5042018-04-09 13:49:37 -07005532 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005533
Vishnu Nair9b079a22020-01-21 14:36:08 -08005534 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005535 fillLayer.source.buffer.buffer = nullptr;
5536 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5537 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5538 fillLayer.alpha = half(alpha);
5539 clientCompositionLayers.push_back(fillLayer);
5540
5541 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005542 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005543 const bool supportProtectedContent = false;
5544 Region clip(renderArea.getBounds());
5545 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5546 clip,
5547 useIdentityTransform,
5548 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5549 renderArea.isSecure(),
5550 supportProtectedContent,
5551 clearRegion,
5552 };
5553 auto result = layer->prepareClientComposition(targetSettings);
5554 if (result) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08005555 std::optional<compositionengine::LayerFE::LayerSettings> shadowLayer =
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005556 layer->prepareShadowClientComposition(*result, displayViewport,
5557 clientCompositionDisplay.outputDataspace);
5558 if (shadowLayer) {
5559 clientCompositionLayers.push_back(*shadowLayer);
5560 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005561 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005562 }
chaviwa76b2712017-09-20 12:02:26 -07005563 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005564
Vishnu Nair9b079a22020-01-21 14:36:08 -08005565 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5566 clientCompositionLayers.reserve(clientCompositionLayers.size());
5567 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5568 std::back_inserter(clientCompositionLayerPointers),
5569 [](compositionengine::LayerFE::LayerSettings& settings)
5570 -> renderengine::LayerSettings* { return &settings; });
5571
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005572 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005573 // Use an empty fence for the buffer fence, since we just created the buffer so
5574 // there is no need for synchronization with the GPU.
5575 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005576 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005577 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005578 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005579 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005580
5581 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005582}
5583
chaviwa76b2712017-09-20 12:02:26 -07005584status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5585 TraverseLayersFunction traverseLayers,
5586 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005587 bool useIdentityTransform, bool forSystem,
5588 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005589 ATRACE_CALL();
5590
chaviwa76b2712017-09-20 12:02:26 -07005591 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005592 outCapturedSecureLayers =
5593 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005594 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005595
Robert Carr03480e22018-01-04 16:02:06 -08005596 // We allow the system server to take screenshots of secure layers for
5597 // use in situations like the Screen-rotation animation and place
5598 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005599 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005600 ALOGW("FB is protected: PERMISSION_DENIED");
5601 return PERMISSION_DENIED;
5602 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005603 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005604 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005605}
5606
chaviw95ef3c42019-02-14 10:55:09 -08005607void SurfaceFlinger::setInputWindowsFinished() {
5608 Mutex::Autolock _l(mStateLock);
5609
5610 mPendingSyncInputWindows = false;
5611 mTransactionCV.broadcast();
5612}
chaviw5f21a5e2019-02-14 10:00:34 -08005613
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005614// ---------------------------------------------------------------------------
5615
Edgar Arriaga844fa672020-01-16 14:21:42 -08005616void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5617 layersSortedByZ.traverse(visitor);
5618}
5619
Dan Stoza412903f2017-04-27 13:42:17 -07005620void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5621 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005622}
5623
Dan Stoza412903f2017-04-27 13:42:17 -07005624void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5625 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005626}
5627
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005628void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005629 const LayerVector::Visitor& visitor) {
5630 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005631 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005632 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005633 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005634 continue;
5635 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005636 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005637 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005638 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005639 return;
5640 }
chaviwa76b2712017-09-20 12:02:26 -07005641 if (!layer->isVisible()) {
5642 return;
5643 }
5644 visitor(layer);
5645 });
5646 }
5647}
5648
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005649status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5650 HwcConfigIndexType defaultConfig,
5651 float minRefreshRate,
5652 float maxRefreshRate) {
5653 Mutex::Autolock lock(mStateLock);
5654
Dominik Laskowski22488f62019-03-28 09:53:04 -07005655 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005656 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5657 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5658 // it should go thru setDesiredActiveConfig, similar to primary display.
5659 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5660 const auto displayId = display->getId();
5661 LOG_ALWAYS_FATAL_IF(!displayId);
5662
5663 HWC2::VsyncPeriodChangeConstraints constraints;
5664 constraints.desiredTimeNanos = systemTime();
5665 constraints.seamlessRequired = false;
5666
5667 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005668 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5669 constraints, &timeline) < 0) {
5670 return BAD_VALUE;
5671 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005672 if (timeline.refreshRequired) {
5673 repaintEverythingForHWC();
5674 }
5675
Ady Abrahamdfa37362020-01-21 18:02:39 -08005676 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005677 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005678 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5679 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005680 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005681 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005682 }
5683
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005684 if (mDebugDisplayConfigSetByBackdoor) {
5685 // ignore this request as config is overridden by backdoor
5686 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005687 }
5688
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005689 bool policyChanged;
5690 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5691 &policyChanged) < 0) {
5692 return BAD_VALUE;
5693 }
5694 if (!policyChanged) {
5695 return NO_ERROR;
5696 }
5697
5698 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5699 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005700
5701 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5702 // that listeners that care about a change in allowed configs can get the notification.
5703 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005704 const nsecs_t vsyncPeriod =
5705 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005706 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005707 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005708
Ana Krulec3f6a2062020-01-23 15:48:01 -08005709 auto configId = mScheduler->getPreferredConfigId();
5710 auto preferredRefreshRate = configId
5711 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5712 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5713 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5714 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5715 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5716
5717 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5718 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5719 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005720 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005721 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005722 }
5723
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005724 return NO_ERROR;
5725}
5726
Ana Krulec0782b882019-10-15 17:34:54 -07005727status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005728 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005729 float maxRefreshRate) {
5730 ATRACE_CALL();
5731
5732 if (!displayToken) {
5733 return BAD_VALUE;
5734 }
5735
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005736 status_t result = NO_ERROR;
5737
Ana Krulec234bb162019-11-10 22:55:55 +01005738 postMessageSync(new LambdaMessage([&]() {
5739 const auto display = getDisplayDeviceLocked(displayToken);
5740 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005741 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005742 ALOGE("Attempt to set desired display configs for invalid display token %p",
5743 displayToken.get());
5744 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005745 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005746 ALOGW("Attempt to set desired display configs for virtual display");
5747 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005748 result =
5749 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5750 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005751 }
5752 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005753
5754 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005755}
5756
5757status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005758 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005759 float* outMinRefreshRate,
5760 float* outMaxRefreshRate) {
5761 ATRACE_CALL();
5762
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005763 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005764 return BAD_VALUE;
5765 }
5766
5767 Mutex::Autolock lock(mStateLock);
5768 const auto display = getDisplayDeviceLocked(displayToken);
5769 if (!display) {
5770 return NAME_NOT_FOUND;
5771 }
5772
5773 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005774 HwcConfigIndexType defaultConfig;
5775 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5776 *outDefaultConfig = defaultConfig.value();
5777 return NO_ERROR;
5778 } else if (display->isVirtual()) {
5779 return BAD_VALUE;
5780 } else {
5781 const auto displayId = display->getId();
5782 if (!displayId) {
5783 return BAD_VALUE;
5784 }
5785 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5786 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5787 *outMinRefreshRate = 1e9f / vsyncPeriod;
5788 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5789 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005790 }
Ana Krulec0782b882019-10-15 17:34:54 -07005791}
5792
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005793void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005794 mFlinger->setInputWindowsFinished();
5795}
5796
Robert Carrc0df3122019-04-11 13:18:21 -07005797sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005798 BBinder* b = nullptr;
5799 if (handle) {
5800 b = handle->localBinder();
5801 }
Robert Carrc0df3122019-04-11 13:18:21 -07005802 if (b == nullptr) {
5803 return nullptr;
5804 }
5805 auto it = mLayersByLocalBinderToken.find(b);
5806 if (it != mLayersByLocalBinderToken.end()) {
5807 return it->second.promote();
5808 }
5809 return nullptr;
5810}
5811
Dominik Laskowski75848362019-11-11 17:57:20 -08005812void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005813 mNumLayers++;
5814 mScheduler->registerLayer(layer);
5815}
5816
5817void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5818 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005819 removeFromOffscreenLayers(layer);
5820}
5821
5822// WARNING: ONLY CALL THIS FROM LAYER DTOR
5823// Here we add children in the current state to offscreen layers and remove the
5824// layer itself from the offscreen layer list. Since
5825// this is the dtor, it is safe to access the current state. This keeps us
5826// from dangling children layers such that they are not reachable from the
5827// Drawing state nor the offscreen layer list
5828// See b/141111965
5829void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5830 for (auto& child : layer->getCurrentChildren()) {
5831 mOffscreenLayers.emplace(child.get());
5832 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005833 mOffscreenLayers.erase(layer);
5834}
5835
Alec Mouri4545a8a2019-08-08 20:05:32 -07005836void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5837 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5838}
5839
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005840status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5841 float lightPosY, float lightPosZ,
5842 float lightRadius) {
5843 Mutex::Autolock _l(mStateLock);
5844 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5845 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5846 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5847 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5848 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5849
5850 // these values are overridden when calculating the shadow settings for a layer.
5851 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5852 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005853 return NO_ERROR;
5854}
5855
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005856} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005857
Mathias Agopian3f844832013-08-07 21:24:32 -07005858#if defined(__gl_h_)
5859#error "don't include gl/gl.h in this file"
5860#endif
5861
5862#if defined(__gl2_h_)
5863#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005864#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005865
5866// TODO(b/129481165): remove the #pragma below and fix conversion issues
5867#pragma clang diagnostic pop // ignored "-Wconversion"