blob: f81179a3e2da42cdb044d6dc03692edfeef6e587 [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;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800231bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700232
Kalle Raitaa099a242017-01-11 11:17:29 -0800233std::string getHwcServiceName() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.hwc_service_name", value, "default");
236 ALOGI("Using HWComposer service: '%s'", value);
237 return std::string(value);
238}
239
240bool useTrebleTestingOverride() {
241 char value[PROPERTY_VALUE_MAX] = {};
242 property_get("debug.sf.treble_testing_override", value, "false");
243 ALOGI("Treble testing override: '%s'", value);
244 return std::string(value) == "true";
245}
246
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800247std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
248 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800249 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800251 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700252 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800253 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700254 return std::string("Enhanced");
255 default:
256 return std::string("Unknown ") +
257 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259}
260
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800262
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
264 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700265 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700266 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700267 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700268 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700269 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800270 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
271 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800274 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800275
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800283
Steven Thomas050b2c82017-03-06 11:45:16 -0800284 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900285 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800286
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 mDefaultCompositionDataspace =
294 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700295 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
296 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 defaultCompositionDataspace = mDefaultCompositionDataspace;
298 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
299 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
300 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
301 wideColorGamutCompositionPixelFormat =
302 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700303
Yichi Chenda901bf2019-06-28 14:58:27 +0800304 mColorSpaceAgnosticDataspace =
305 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800308
Dominik Laskowski718f9602019-11-09 20:01:35 -0800309 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
310 switch (primary_display_orientation(Values::ORIENTATION_0)) {
311 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800312 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800313 case Values::ORIENTATION_90:
314 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800315 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800316 case Values::ORIENTATION_180:
317 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800319 case Values::ORIENTATION_270:
320 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
322 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800323 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800324
Sundong Ahn85131bd2019-02-18 15:51:53 +0900325 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800326
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327 // debugging stuff...
328 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700329
Mathias Agopianb4b17302013-03-20 18:36:41 -0700330 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700331 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333 property_get("debug.sf.showupdates", value, "0");
334 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700335
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700336 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000337
338 // DDMS debugging deprecated (b/120782499)
339 property_get("debug.sf.ddms", value, "0");
340 int debugDdms = atoi(value);
341 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700342
343 property_get("debug.sf.disable_backpressure", value, "0");
344 mPropagateBackpressure = !atoi(value);
345 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700346
Ady Abrahamadb9a992019-09-19 21:21:55 +0000347 property_get("debug.sf.enable_gl_backpressure", value, "0");
348 mPropagateBackpressureClientComposition = atoi(value);
349 ALOGI_IF(mPropagateBackpressureClientComposition,
350 "Enabling backpressure propagation for Client Composition");
351
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800352 property_get("debug.sf.enable_hwc_vds", value, "0");
353 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800354 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800355
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800356 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800357 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800358 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700359
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800360 property_get("ro.surface_flinger.supports_background_blur", value, "0");
361 bool supportsBlurs = atoi(value);
362 property_get("debug.sf.disableBlurs", value, "0");
363 bool disableBlurs = atoi(value);
364 mEnableBlurs = supportsBlurs && !disableBlurs;
365 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
366 disableBlurs);
367
Yiwei Zhang243b3782018-05-15 17:40:04 -0700368 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700369 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
370 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
371
Dan Stozaec460082018-12-17 15:35:09 -0800372 property_get("debug.sf.luma_sampling", value, "1");
373 mLumaSampling = atoi(value);
374
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800375 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800376 mDisableClientCompositionCache = atoi(value);
377
Romain Guy11d63f42017-07-20 12:47:14 -0700378 // We should be reading 'persist.sys.sf.color_saturation' here
379 // but since /data may be encrypted, we need to wait until after vold
380 // comes online to attempt to read the property. The property is
381 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800382
383 if (useTrebleTestingOverride()) {
384 // Without the override SurfaceFlinger cannot connect to HIDL
385 // services that are not listed in the manifests. Considered
386 // deriving the setting from the set service name, but it
387 // would be brittle if the name that's not 'default' is used
388 // for production purposes later on.
389 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
390 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800391
392 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395void SurfaceFlinger::onFirstRef()
396{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800397 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700400SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401
Dan Stozac7014012014-02-14 15:03:43 -0800402void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403{
404 // the window manager died on us. prepare its eulogy.
405
Andy McFadden13a082e2012-08-24 10:16:42 -0700406 // restore initial conditions (default device unblank, etc)
407 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408
409 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700410 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Robert Carr1db73f62016-12-21 12:58:51 -0800413static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700414 status_t err = client->initCheck();
415 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800416 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 }
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return nullptr;
419}
420
421sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
422 return initClient(new Client(this));
423}
424
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700425sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
426 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427{
428 class DisplayToken : public BBinder {
429 sp<SurfaceFlinger> flinger;
430 virtual ~DisplayToken() {
431 // no more references, this display must be terminated
432 Mutex::Autolock _l(flinger->mStateLock);
433 flinger->mCurrentState.displays.removeItem(this);
434 flinger->setTransactionFlags(eDisplayTransactionNeeded);
435 }
436 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700437 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 : flinger(flinger) {
439 }
440 };
441
442 sp<BBinder> token = new DisplayToken(this);
443
444 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 // Display ID is assigned when virtual display is allocated by HWC.
446 DisplayDeviceState state;
447 state.isSecure = secure;
448 state.displayName = displayName;
449 mCurrentState.displays.add(token, state);
450 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 return token;
452}
453
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 Mutex::Autolock _l(mStateLock);
456
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
458 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 return;
461 }
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
464 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 ALOGE("destroyDisplay called for non-virtual display");
466 return;
467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 mInterceptor->saveDisplayDeletion(state.sequenceId);
469 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 setTransactionFlags(eDisplayTransactionNeeded);
471}
472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
474 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800476 const auto internalDisplayId = getInternalDisplayIdLocked();
477 if (!internalDisplayId) {
478 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 }
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 std::vector<PhysicalDisplayId> displayIds;
482 displayIds.reserve(mPhysicalDisplayTokens.size());
483 displayIds.push_back(internalDisplayId->value);
484
485 for (const auto& [id, token] : mPhysicalDisplayTokens) {
486 if (id != *internalDisplayId) {
487 displayIds.push_back(id.value);
488 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 return displayIds;
492}
493
494sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
495 Mutex::Autolock lock(mStateLock);
496 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497}
498
Ady Abraham37965d42018-11-01 13:43:32 -0700499status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
500 if (!outGetColorManagement) {
501 return BAD_VALUE;
502 }
503 *outGetColorManagement = useColorManagement;
504 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700505}
506
Lloyd Pique441d5042018-10-18 16:49:51 -0700507HWComposer& SurfaceFlinger::getHwComposer() const {
508 return mCompositionEngine->getHwComposer();
509}
510
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700511renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
512 return mCompositionEngine->getRenderEngine();
513}
514
Lloyd Pique70d91362018-10-18 16:02:55 -0700515compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
516 return *mCompositionEngine.get();
517}
518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519void SurfaceFlinger::bootFinished()
520{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700521 if (mStartPropertySetThread->join() != NO_ERROR) {
522 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 const nsecs_t now = systemTime();
525 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000526 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527
Mikael Pessa90092f42019-08-26 17:22:04 -0700528 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000529 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700530
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531 // wait patiently for the window manager death
532 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700533 mWindowManager = defaultServiceManager()->getService(name);
534 if (mWindowManager != 0) {
535 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 }
Robert Carr720e5062018-07-30 17:45:14 -0700537 sp<IBinder> input(defaultServiceManager()->getService(
538 String16("inputflinger")));
539 if (input == nullptr) {
540 ALOGE("Failed to link to input service");
541 } else {
542 mInputFlinger = interface_cast<IInputFlinger>(input);
543 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544
Steven Thomas050b2c82017-03-06 11:45:16 -0800545 if (mVrFlinger) {
546 mVrFlinger->OnBootFinished();
547 }
548
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700550 // formerly we would just kill the process, but we now ask it to exit so it
551 // can choose where to stop the animation.
552 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700553
554 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
555 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
556 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700557
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800559 readPersistentProperties();
560 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800561
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
563 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
564 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
565 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800566 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800567}
568
Dan Stoza436ccf32018-06-21 12:10:12 -0700569uint32_t SurfaceFlinger::getNewTexture() {
570 {
571 std::lock_guard lock(mTexturePoolMutex);
572 if (!mTexturePool.empty()) {
573 uint32_t name = mTexturePool.back();
574 mTexturePool.pop_back();
575 ATRACE_INT("TexturePoolSize", mTexturePool.size());
576 return name;
577 }
578
579 // The pool was too small, so increase it for the future
580 ++mTexturePoolSize;
581 }
582
583 // The pool was empty, so we need to get a new texture name directly using a
584 // blocking call to the main thread
585 uint32_t name = 0;
586 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
587 return name;
588}
589
Mathias Agopian3f844832013-08-07 21:24:32 -0700590void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700591 std::lock_guard lock(mTexturePoolMutex);
592 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
593 // to actually delete this or not based on mTexturePoolSize
594 mTexturePool.push_back(texture);
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700596}
597
Wei Wangf9b05ee2017-07-19 20:59:39 -0700598// Do not call property_set on main thread which will be blocked by init
599// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700600void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700601 ALOGI( "SurfaceFlinger's main thread ready to run. "
602 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700606 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800607 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700608 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
609 renderengine::RenderEngineCreationArgs::Builder()
610 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
611 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
612 .setUseColorManagerment(useColorManagement)
613 .setEnableProtectedContext(enable_protected_contents(false))
614 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800615 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700616 .setContextPriority(useContextPriority
617 ? renderengine::RenderEngine::ContextPriority::HIGH
618 : renderengine::RenderEngine::ContextPriority::MEDIUM)
619 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800620 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700621
622 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
623 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700624 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
625 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800626 // Process any initial hotplug and resulting display changes.
627 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700628 const auto display = getDefaultDisplayDeviceLocked();
629 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700630 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700631 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800632
Steven Thomas050b2c82017-03-06 11:45:16 -0800633 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700634 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700635 // This callback is called from the vr flinger dispatch thread. We
636 // need to call signalTransaction(), which requires holding
637 // mStateLock when we're not on the main thread. Acquiring
638 // mStateLock from the vr flinger dispatch thread might trigger a
639 // deadlock in surface flinger (see b/66916578), so post a message
640 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700641 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700642 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
643 mVrFlingerRequestsDisplay = requestDisplay;
644 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700645 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
648 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700649 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700650 .value_or(0),
651 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 if (!mVrFlinger) {
653 ALOGE("Failed to start vrflinger");
654 }
655 }
656
Mathias Agopian92a979a2012-08-02 18:32:23 -0700657 // initialize our drawing state
658 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700659
Andy McFadden13a082e2012-08-24 10:16:42 -0700660 // set initial conditions (e.g. unblank default device)
661 initializeDisplays();
662
Steven Thomas137d4bc2019-07-25 16:55:14 -0700663 char primeShaderCache[PROPERTY_VALUE_MAX];
664 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
665 if (atoi(primeShaderCache)) {
666 getRenderEngine().primeCache();
667 }
Dan Stoza4e637772016-07-28 13:31:51 -0700668
Wei Wangf9b05ee2017-07-19 20:59:39 -0700669 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700670
671 const bool presentFenceReliable =
672 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
673 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700674
675 if (mStartPropertySetThread->Start() != NO_ERROR) {
676 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800677 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800678
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700680}
681
Romain Guy11d63f42017-07-20 12:47:14 -0700682void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700683 Mutex::Autolock _l(mStateLock);
684
Romain Guy11d63f42017-07-20 12:47:14 -0700685 char value[PROPERTY_VALUE_MAX];
686
687 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800688 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700689 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100691
692 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700693 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800694
695 property_get("persist.sys.sf.color_mode", value, "0");
696 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700697}
698
Mathias Agopiana67e4182012-06-19 17:26:12 -0700699void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800700 // Start boot animation service by setting a property mailbox
701 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700702 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800703 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 if (mStartPropertySetThread->join() != NO_ERROR) {
705 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700710 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
Mathias Agopian875d8e12013-06-07 15:35:48 -0700713size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700714 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700715}
716
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800718
Jamie Gennis582270d2011-08-17 18:19:00 -0700719bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800721 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800722 return authenticateSurfaceTextureLocked(bufferProducer);
723}
724
725bool SurfaceFlinger::authenticateSurfaceTextureLocked(
726 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800727 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800728 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800729}
730
Brian Anderson6b376712017-04-04 10:51:39 -0700731status_t SurfaceFlinger::getSupportedFrameTimestamps(
732 std::vector<FrameEvent>* outSupported) const {
733 *outSupported = {
734 FrameEvent::REQUESTED_PRESENT,
735 FrameEvent::ACQUIRE,
736 FrameEvent::LATCH,
737 FrameEvent::FIRST_REFRESH_START,
738 FrameEvent::LAST_REFRESH_START,
739 FrameEvent::GPU_COMPOSITION_DONE,
740 FrameEvent::DEQUEUE_READY,
741 FrameEvent::RELEASE,
742 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700743 ConditionalLock _l(mStateLock,
744 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700745 if (!getHwComposer().hasCapability(
746 HWC2::Capability::PresentFenceIsNotReliable)) {
747 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
748 }
749 return NO_ERROR;
750}
751
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800752status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
753 if (!displayToken || !state) {
754 return BAD_VALUE;
755 }
756
757 Mutex::Autolock lock(mStateLock);
758
759 const auto display = getDisplayDeviceLocked(displayToken);
760 if (!display) {
761 return NAME_NOT_FOUND;
762 }
763
764 state->layerStack = display->getLayerStack();
765 state->orientation = display->getOrientation();
766
767 const Rect viewport = display->getViewport();
768 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
769
770 return NO_ERROR;
771}
772
773status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
774 if (!displayToken || !info) {
775 return BAD_VALUE;
776 }
777
778 Mutex::Autolock lock(mStateLock);
779
780 const auto display = getDisplayDeviceLocked(displayToken);
781 if (!display) {
782 return NAME_NOT_FOUND;
783 }
784
785 if (display->isVirtual()) {
786 return INVALID_OPERATION;
787 }
788
789 if (mEmulatedDisplayDensity) {
790 info->density = mEmulatedDisplayDensity;
791 } else {
792 info->density = display->isPrimary() ? mInternalDisplayDensity : FALLBACK_DENSITY;
793 }
794
795 info->secure = display->isSecure();
796
797 return NO_ERROR;
798}
799
Dominik Laskowski22488f62019-03-28 09:53:04 -0700800status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800801 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700802 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 return BAD_VALUE;
804 }
805
Dominik Laskowski22488f62019-03-28 09:53:04 -0700806 Mutex::Autolock lock(mStateLock);
807
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800808 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700809 if (!displayId) {
810 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700811 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800813 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700814
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700816
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800818 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700819
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800820 auto width = hwConfig->getWidth();
821 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700822
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800823 auto xDpi = hwConfig->getDpiX();
824 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700825
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826 if (isInternal &&
827 (internalDisplayOrientation == ui::ROTATION_90 ||
828 internalDisplayOrientation == ui::ROTATION_270)) {
829 std::swap(width, height);
830 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 }
832
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800833 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800834
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 if (mEmulatedDisplayDensity) {
836 config.xDpi = mEmulatedDisplayDensity;
837 config.yDpi = mEmulatedDisplayDensity;
838 } else {
839 config.xDpi = xDpi;
840 config.yDpi = yDpi;
841 }
842
843 const nsecs_t period = hwConfig->getVsyncPeriod();
844 config.refreshRate = 1e9f / period;
845
846 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
847 config.appVsyncOffset = offsets.late.app;
848 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800849
Andy McFadden91b2ca82014-06-13 14:04:23 -0700850 // This is how far in advance a buffer must be queued for
851 // presentation at a given time. If you want a buffer to appear
852 // on the screen at time N, you must submit the buffer before
853 // (N - presentationDeadline).
854 //
855 // Normally it's one full refresh period (to give SF a chance to
856 // latch the buffer), but this can be reduced by configuring a
857 // DispSync offset. Any additional delays introduced by the hardware
858 // composer or panel must be accounted for here.
859 //
860 // We add an additional 1ms to allow for processing time and
861 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700863
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800864 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700865 }
866
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 return NO_ERROR;
868}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700869
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700870status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
871 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700872 return BAD_VALUE;
873 }
874
Ana Krulecc2870422019-01-29 19:00:58 -0800875 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700876 return NO_ERROR;
877}
878
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700879int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
880 const auto display = getDisplayDevice(displayToken);
881 if (!display) {
882 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800883 return BAD_VALUE;
884 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700885
Steven Thomasc9098452019-09-30 17:15:05 -0700886 if (display->isPrimary()) {
887 std::lock_guard<std::mutex> lock(mActiveConfigLock);
888 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800889 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700890 }
Steven Thomasc9098452019-09-30 17:15:05 -0700891 }
Ady Abraham2139f732019-11-13 18:56:40 -0800892
893 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Ady Abraham03b02dd2019-03-21 15:40:11 -0700896void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800897 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800898 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
899 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800900
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800901 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800902 // config twice. However event generation config might have changed so we need to update it
903 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800904 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700905 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
906 mDesiredActiveConfig = info;
907 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800908
909 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800910 // This will trigger HWC refresh without resetting the idle timer.
911 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700912 // Start receiving vsync samples now, so that we can detect a period
913 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800914 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700915 // As we called to set period, we will call to onRefreshRateChangeCompleted once
916 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700917 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800918
Ady Abraham9e16a482019-12-03 17:19:41 -0800919 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
920 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800921 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800922 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700923
924 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800925 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700926 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800927}
928
929status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
930 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800931
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100932 if (!displayToken) {
933 return BAD_VALUE;
934 }
Ady Abraham838de062019-02-04 10:24:03 -0800935
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100936 status_t result = NO_ERROR;
937
938 postMessageSync(new LambdaMessage([&]() {
939 const auto display = getDisplayDeviceLocked(displayToken);
940 if (!display) {
941 ALOGE("Attempt to set allowed display configs for invalid display token %p",
942 displayToken.get());
943 result = BAD_VALUE;
944 } else if (display->isVirtual()) {
945 ALOGW("Attempt to set allowed display configs for virtual display");
946 result = BAD_VALUE;
947 } else {
948 HwcConfigIndexType config(mode);
949 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
950 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
951 refreshRate.fps);
952 }
953 }));
954
955 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956}
957
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958void SurfaceFlinger::setActiveConfigInternal() {
959 ATRACE_CALL();
960
Dominik Laskowski22488f62019-03-28 09:53:04 -0700961 const auto display = getDefaultDisplayDeviceLocked();
962 if (!display) {
963 return;
964 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965
Dominik Laskowski22488f62019-03-28 09:53:04 -0700966 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800967 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700968 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 display->setActiveConfig(mUpcomingActiveConfig.configId);
970
Ady Abraham2139f732019-11-13 18:56:40 -0800971 auto refreshRate =
972 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800973 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
974 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800975 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700976
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800977 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700978 const nsecs_t vsyncPeriod =
979 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
980 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800981 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700982 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800983 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
Ady Abraham53852a52019-05-28 18:07:44 -0700986void SurfaceFlinger::desiredActiveConfigChangeDone() {
987 std::lock_guard<std::mutex> lock(mActiveConfigLock);
988 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
989 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700990
Kevin DuBois5988f482020-01-17 09:03:32 -0800991 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800992 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800993 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800994 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
995 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700996}
997
Dominik Laskowski22488f62019-03-28 09:53:04 -0700998bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800999 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001000 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001001 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001002 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001003 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001004 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001005 return true;
1006 }
1007
1008 // We received the present fence from the HWC, so we assume it successfully updated
1009 // the config, hence we update SF.
1010 mCheckPendingFence = false;
1011 setActiveConfigInternal();
1012 }
1013
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001014 // Store the local variable to release the lock.
1015 ActiveConfigInfo desiredActiveConfig;
1016 {
1017 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018 if (!mDesiredActiveConfigChanged) {
1019 return false;
1020 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001021 desiredActiveConfig = mDesiredActiveConfig;
1022 }
1023
Ady Abraham2139f732019-11-13 18:56:40 -08001024 auto refreshRate =
1025 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1026 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1027 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001028 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001029 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1030 // display is not valid or we are already in the requested mode
1031 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001032 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001033 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001034 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035
Ady Abraham838de062019-02-04 10:24:03 -08001036 // Desired active config was set, it is different than the config currently in use, however
1037 // allowed configs might have change by the time we process the refresh.
1038 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001039 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001040 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001041 return false;
1042 }
Alec Mouri7f015182019-07-11 13:56:22 -07001043
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044 mUpcomingActiveConfig = desiredActiveConfig;
1045 const auto displayId = display->getId();
1046 LOG_ALWAYS_FATAL_IF(!displayId);
1047
Ady Abraham2139f732019-11-13 18:56:40 -08001048 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001050 // TODO(b/142753666) use constrains
1051 HWC2::VsyncPeriodChangeConstraints constraints;
1052 constraints.desiredTimeNanos = systemTime();
1053 constraints.seamlessRequired = false;
1054
1055 HWC2::VsyncPeriodChangeTimeline outTimeline;
1056 auto status =
1057 getHwComposer().setActiveConfigWithConstraints(*displayId,
1058 mUpcomingActiveConfig.configId.value(),
1059 constraints, &outTimeline);
1060 if (status != NO_ERROR) {
1061 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1062 return false;
1063 }
1064
1065 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1066 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001067 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001068 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001069}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1072 Vector<ColorMode>* outColorModes) {
1073 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001074 return BAD_VALUE;
1075 }
1076
Peiyong Lina52f0292018-03-14 17:26:31 -07001077 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001078 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001079 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001080 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1081
1082 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1083 if (!displayId) {
1084 return NAME_NOT_FOUND;
1085 }
1086
Dominik Laskowski075d3172018-05-24 15:50:06 -07001087 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001088 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001089 }
Michael Wright28f24d02016-07-12 13:30:53 -07001090 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001091
1092 // If it's built-in display and the configuration claims it's not wide color capable,
1093 // filter out all wide color modes. The typical reason why this happens is that the
1094 // hardware is not good enough to support GPU composition of wide color, and thus the
1095 // OEMs choose to disable this capability.
1096 if (isInternalDisplay && !hasWideColorDisplay) {
1097 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1098 isWideColorMode);
1099 } else {
1100 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1101 }
Michael Wright28f24d02016-07-12 13:30:53 -07001102
1103 return NO_ERROR;
1104}
1105
Daniel Solomon42d04562019-01-20 21:03:19 -08001106status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1107 ui::DisplayPrimaries &primaries) {
1108 if (!displayToken) {
1109 return BAD_VALUE;
1110 }
1111
1112 // Currently we only support this API for a single internal display.
1113 if (getInternalDisplayToken() != displayToken) {
1114 return BAD_VALUE;
1115 }
1116
1117 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1118 return NO_ERROR;
1119}
1120
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1122 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001123 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001124 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001125 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001126}
1127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001129 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130 Vector<ColorMode> modes;
1131 getDisplayColorModes(displayToken, &modes);
1132 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1133 if (mode < ColorMode::NATIVE || !exists) {
1134 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1135 decodeColorMode(mode).c_str(), mode, displayToken.get());
1136 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001137 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001138 const auto display = getDisplayDevice(displayToken);
1139 if (!display) {
1140 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1141 decodeColorMode(mode).c_str(), mode, displayToken.get());
1142 } else if (display->isVirtual()) {
1143 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1144 decodeColorMode(mode).c_str(), mode);
1145 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001146 display->getCompositionDisplay()->setColorProfile(
1147 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1148 RenderIntent::COLORIMETRIC,
1149 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150 }
1151 }));
1152
Michael Wright28f24d02016-07-12 13:30:53 -07001153 return NO_ERROR;
1154}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001155
Galia Peycheva5492cb52019-10-30 14:13:16 +01001156status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1157 bool* outSupport) const {
1158 Mutex::Autolock _l(mStateLock);
1159
1160 if (!displayToken) {
1161 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1162 return BAD_VALUE;
1163 }
1164 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1165 if (!displayId) {
1166 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1167 displayToken.get());
1168 return NAME_NOT_FOUND;
1169 }
1170 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1171 HWC2::DisplayCapability::AutoLowLatencyMode);
1172 return NO_ERROR;
1173}
1174
1175void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1176 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1177}
1178
1179void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1180 if (!displayToken) {
1181 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1182 return;
1183 }
1184 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1185 if (!displayId) {
1186 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1187 displayToken.get());
1188 return;
1189 }
1190
1191 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1192}
1193
1194status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1195 bool* outSupport) const {
1196 Mutex::Autolock _l(mStateLock);
1197
1198 if (!displayToken) {
1199 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1200 return BAD_VALUE;
1201 }
1202 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1203 if (!displayId) {
1204 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1205 displayToken.get());
1206 return NAME_NOT_FOUND;
1207 }
1208
1209 std::vector<HWC2::ContentType> outSupportedContentTypes;
1210 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1211 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1212 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1213 return NO_ERROR;
1214}
1215
1216void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1217 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1218}
1219
1220void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1221 if (!displayToken) {
1222 ALOGE("setGameContentType() failed. Missing display token.");
1223 return;
1224 }
1225 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1226 if (!displayId) {
1227 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1228 displayToken.get());
1229 return;
1230 }
1231
1232 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1233 getHwComposer().setContentType(*displayId, type);
1234}
1235
Svetoslavd85084b2014-03-20 10:28:31 -07001236status_t SurfaceFlinger::clearAnimationFrameStats() {
1237 Mutex::Autolock _l(mStateLock);
1238 mAnimFrameTracker.clearStats();
1239 return NO_ERROR;
1240}
1241
1242status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1243 Mutex::Autolock _l(mStateLock);
1244 mAnimFrameTracker.getStats(outStats);
1245 return NO_ERROR;
1246}
1247
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001248status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1249 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001250 Mutex::Autolock _l(mStateLock);
1251
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001252 const auto display = getDisplayDeviceLocked(displayToken);
1253 if (!display) {
1254 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001255 return BAD_VALUE;
1256 }
1257
Peiyong Linfb069302018-04-25 14:34:31 -07001258 // At this point the DisplayDeivce should already be set up,
1259 // meaning the luminance information is already queried from
1260 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001261 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001262 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1263 capabilities.getDesiredMaxLuminance(),
1264 capabilities.getDesiredMaxAverageLuminance(),
1265 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001266
1267 return NO_ERROR;
1268}
1269
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001270status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1271 ui::PixelFormat* outFormat,
1272 ui::Dataspace* outDataspace,
1273 uint8_t* outComponentMask) const {
1274 if (!outFormat || !outDataspace || !outComponentMask) {
1275 return BAD_VALUE;
1276 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001277 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001278 if (!display || !display->getId()) {
1279 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1280 return BAD_VALUE;
1281 }
1282 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1283 outDataspace, outComponentMask);
1284}
1285
Kevin DuBois74e53772018-11-19 10:52:38 -08001286status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1287 bool enable, uint8_t componentMask,
1288 uint64_t maxFrames) const {
1289 const auto display = getDisplayDevice(displayToken);
1290 if (!display || !display->getId()) {
1291 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1292 return BAD_VALUE;
1293 }
1294
1295 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1296 componentMask, maxFrames);
1297}
1298
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001299status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1300 uint64_t maxFrames, uint64_t timestamp,
1301 DisplayedFrameStats* outStats) const {
1302 const auto display = getDisplayDevice(displayToken);
1303 if (!display || !display->getId()) {
1304 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1305 return BAD_VALUE;
1306 }
1307
1308 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1309 outStats);
1310}
1311
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001312status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1313 if (!outSupported) {
1314 return BAD_VALUE;
1315 }
1316 *outSupported = getRenderEngine().supportsProtectedContent();
1317 return NO_ERROR;
1318}
1319
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001320status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1321 bool* outIsWideColorDisplay) const {
1322 if (!displayToken || !outIsWideColorDisplay) {
1323 return BAD_VALUE;
1324 }
1325 Mutex::Autolock _l(mStateLock);
1326 const auto display = getDisplayDeviceLocked(displayToken);
1327 if (!display) {
1328 return BAD_VALUE;
1329 }
Peiyong Linff84a152019-05-17 18:36:19 -07001330
1331 // Use hasWideColorDisplay to override built-in display.
1332 const auto displayId = display->getId();
1333 if (displayId && displayId == getInternalDisplayIdLocked()) {
1334 *outIsWideColorDisplay = hasWideColorDisplay;
1335 return NO_ERROR;
1336 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001337 *outIsWideColorDisplay = display->hasWideColorGamut();
1338 return NO_ERROR;
1339}
1340
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001341status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001342 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001343 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001344
Dominik Laskowski6505f792019-09-18 11:10:05 -07001345 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1346 mEventQueue->setEventConnection(
1347 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001348 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001349 }));
1350
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001351 return NO_ERROR;
1352}
1353
1354status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001355 Mutex::Autolock lock(mStateLock);
1356 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001357}
1358
Lloyd Pique755e3192018-01-31 16:46:15 -08001359status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1360 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001361 // Try to acquire a lock for 1s, fail gracefully
1362 const status_t err = mStateLock.timedLock(s2ns(1));
1363 const bool locked = (err == NO_ERROR);
1364 if (!locked) {
1365 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1366 return TIMED_OUT;
1367 }
1368
1369 outLayers->clear();
1370 mCurrentState.traverseInZOrder([&](Layer* layer) {
1371 outLayers->push_back(layer->getLayerDebugInfo());
1372 });
1373
1374 mStateLock.unlock();
1375 return NO_ERROR;
1376}
1377
Peiyong Linc6780972018-10-28 15:24:08 -07001378status_t SurfaceFlinger::getCompositionPreference(
1379 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1380 Dataspace* outWideColorGamutDataspace,
1381 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001382 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001383 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001384 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001385 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001386 return NO_ERROR;
1387}
1388
Dan Stozaec460082018-12-17 15:35:09 -08001389status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1390 const sp<IBinder>& stopLayerHandle,
1391 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001392 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001393 return BAD_VALUE;
1394 }
1395 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001396 return NO_ERROR;
1397}
1398
Dan Stozaec460082018-12-17 15:35:09 -08001399status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001400 if (!listener) {
1401 return BAD_VALUE;
1402 }
Dan Stozaec460082018-12-17 15:35:09 -08001403 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001404 return NO_ERROR;
1405}
Dan Gittik57e63c52019-01-18 16:37:54 +00001406
1407status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1408 bool* outSupport) const {
1409 if (!displayToken || !outSupport) {
1410 return BAD_VALUE;
1411 }
1412 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1413 if (!displayId) {
1414 return NAME_NOT_FOUND;
1415 }
1416 *outSupport =
1417 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1418 return NO_ERROR;
1419}
1420
1421status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1422 float brightness) const {
1423 if (!displayToken) {
1424 return BAD_VALUE;
1425 }
1426 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1427 if (!displayId) {
1428 return NAME_NOT_FOUND;
1429 }
1430 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1431}
1432
Ady Abraham8532d012019-05-08 14:50:56 -07001433status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1434 PowerHint powerHint = static_cast<PowerHint>(hintId);
1435
1436 if (powerHint == PowerHint::INTERACTION) {
1437 mScheduler->notifyTouchEvent();
1438 }
1439
1440 return NO_ERROR;
1441}
1442
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001443// ----------------------------------------------------------------------------
1444
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001445sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001446 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001447 const auto& handle =
1448 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001449
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001450 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001451}
1452
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001453// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454
1455void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001456 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457}
1458
1459void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001460 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001461 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001462}
1463
1464void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001465 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001466 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001467}
1468
1469void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001470 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001471 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001472}
1473
1474status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001475 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001476 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001477}
1478
1479status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001480 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001481 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001482 if (res == NO_ERROR) {
1483 msg->wait();
1484 }
1485 return res;
1486}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001487
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001488void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001489 do {
1490 waitForEvent();
1491 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001492}
1493
Dominik Laskowski83b88212018-12-11 13:34:06 -08001494nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001495 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001496 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1497 return 0;
1498 }
1499
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001500 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001501}
1502
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001503void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001504 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001505 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001506 ATRACE_NAME("SF onVsync");
1507
Steven Thomas3cfac282017-02-06 12:29:30 -08001508 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001509 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001510 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 return;
1512 }
1513
Dominik Laskowski075d3172018-05-24 15:50:06 -07001514 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001515 return;
1516 }
1517
Dominik Laskowski075d3172018-05-24 15:50:06 -07001518 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001519 // For now, we don't do anything with external display vsyncs.
1520 return;
1521 }
1522
Alec Mourif8e689c2019-05-20 18:32:22 -07001523 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001524 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001525 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001526 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001527 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001528}
1529
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001530void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001531 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1532 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533}
1534
Ady Abraham2139f732019-11-13 18:56:40 -08001535bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001536 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001537}
1538
Ady Abraham2139f732019-11-13 18:56:40 -08001539void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1540 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001541 const auto display = getDefaultDisplayDeviceLocked();
1542 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001543 return;
1544 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001545 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001546
Ana Krulec7d1d6832018-12-27 11:10:09 -08001547 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001548 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1549 ALOGV("Skipping config %d as it is not part of allowed configs",
1550 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001551 return;
1552 }
1553
Ady Abraham2139f732019-11-13 18:56:40 -08001554 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001555}
1556
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001557void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001558 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001559 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001560 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561
Lloyd Piqueba04e622017-12-14 17:11:26 -08001562 // Ignore events that do not have the right sequenceId.
1563 if (sequenceId != getBE().mComposerSequenceId) {
1564 return;
1565 }
1566
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 // Only lock if we're not on the main thread. This function is normally
1568 // called on a hwbinder thread, but for the primary display it's called on
1569 // the main thread with the state lock already held, so don't attempt to
1570 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001571 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001572
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001573 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001574
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001575 if (std::this_thread::get_id() == mMainThreadId) {
1576 // Process all pending hot plug events immediately if we are on the main thread.
1577 processDisplayHotplugEventsLocked();
1578 }
1579
Lloyd Piqueba04e622017-12-14 17:11:26 -08001580 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001581}
1582
Ady Abraham7159f572019-10-11 11:10:18 -07001583void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001584 int32_t sequenceId, hwc2_display_t /*display*/,
1585 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1586 Mutex::Autolock lock(mStateLock);
1587 if (sequenceId != getBE().mComposerSequenceId) {
1588 return;
1589 }
1590 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001591}
1592
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001593void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1594 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1595 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1596}
1597
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001598void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001599 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001600 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001601 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001602 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001603 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001604}
1605
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001606void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001607 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001608
1609 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1610 // display power state.
1611 postMessageAsync(new LambdaMessage(
1612 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1613}
1614
1615void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1616 ATRACE_CALL();
1617
Ady Abraham27c70212019-06-11 10:52:26 -07001618 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1619
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001620 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001621 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1622 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001623 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001624 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001625 }
Mathias Agopian86303202012-07-24 22:46:10 -07001626}
1627
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001628// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001629void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001630 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001631 // Clear the drawing state so that the logic inside of
1632 // handleTransactionLocked will fire. It will determine the delta between
1633 // mCurrentState and mDrawingState and re-apply all changes when we make the
1634 // transition.
1635 mDrawingState.displays.clear();
1636 mDisplays.clear();
1637}
1638
Steven Thomas050b2c82017-03-06 11:45:16 -08001639void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001640 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001641 if (!mVrFlinger)
1642 return;
1643 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001644 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001645 return;
1646 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001647
Lloyd Pique441d5042018-10-18 16:49:51 -07001648 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001649 ALOGE("Vr flinger is only supported for remote hardware composer"
1650 " service connections. Ignoring request to transition to vr"
1651 " flinger.");
1652 mVrFlingerRequestsDisplay = false;
1653 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001654 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001656 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001657
Steven Thomas0123ac62018-07-12 11:32:34 -07001658 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001659 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001660
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001661 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001662
1663 // Clear out all the output layers from the composition engine for all
1664 // displays before destroying the hardware composer interface. This ensures
1665 // any HWC layers are destroyed through that interface before it becomes
1666 // invalid.
1667 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001668 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001669 }
1670
Steven Thomas0123ac62018-07-12 11:32:34 -07001671 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1672 // called below. Clear the reference now so we don't accidentally use it
1673 // later.
1674 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001675
Steven Thomasb02664d2017-07-26 18:48:28 -07001676 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001677 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001678 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001679
Steven Thomasb02664d2017-07-26 18:48:28 -07001680 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001681 // Delete the current instance before creating the new one
1682 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1683 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1684 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1685 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001686
Lloyd Pique441d5042018-10-18 16:49:51 -07001687 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001688 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001689
1690 if (vrFlingerRequestsDisplay) {
1691 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001692 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001693
1694 mVisibleRegionsDirty = true;
1695 invalidateHwcGeometry();
1696
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001697 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001698 display = getDefaultDisplayDeviceLocked();
1699 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001700 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001701
Steven Thomasb02664d2017-07-26 18:48:28 -07001702 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001703 const nsecs_t vsyncPeriod = getVsyncPeriod();
1704 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001705
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001706 // The present fences returned from vr_hwc are not an accurate
1707 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001708 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001709
Steven Thomasb02664d2017-07-26 18:48:28 -07001710 // Use phase of 0 since phase is not known.
1711 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001712 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001713 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001714
Ana Krulecc2870422019-01-29 19:00:58 -08001715 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001716
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001717 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001718 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001719}
1720
Ady Abraham11579302019-09-19 12:35:58 -07001721bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1722 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001723 // We are storing the last 2 present fences. If sf's phase offset is to be
1724 // woken up before the actual vsync but targeting the next vsync, we need to check
1725 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001726 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1727 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001728
Ady Abraham11579302019-09-19 12:35:58 -07001729 if (fence == Fence::NO_FENCE) {
1730 return false;
1731 }
1732
1733 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1734 fence->wait(graceTimeMs);
1735 }
1736
1737 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001738}
1739
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001740void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001741 DisplayStatInfo stats;
1742 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001743 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001744 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001745 mExpectedPresentTime.store(
1746 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001747}
1748
Dominik Laskowski22488f62019-03-28 09:53:04 -07001749void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001750 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001751 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001752 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001753 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001754 // calculate the expected present time once and use the cached
1755 // value throughout this frame to make sure all layers are
1756 // seeing this same value.
1757 populateExpectedPresentTime();
1758
Ady Abraham11579302019-09-19 12:35:58 -07001759 // When Backpressure propagation is enabled we want to give a small grace period
1760 // for the present fence to fire instead of just giving up on this frame to handle cases
1761 // where present fence is just about to get signaled.
1762 const int graceTimeForPresentFenceMs =
1763 (mPropagateBackpressure &&
1764 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1765 ? 1
1766 : 0;
1767 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1768 previousFrameMissed(
1769 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001770 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1771 mHadDeviceComposition && frameMissed};
1772 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1773 mHadClientComposition && frameMissed};
1774
Alec Mouricc0fc602019-02-26 21:45:19 -08001775 if (frameMissed) {
1776 mFrameMissedCount++;
1777 mTimeStats->incrementMissedFrames();
1778 }
1779
Alec Mouri40189b02019-03-05 15:07:54 -08001780 if (hwcFrameMissed) {
1781 mHwcFrameMissedCount++;
1782 }
1783
1784 if (gpuFrameMissed) {
1785 mGpuFrameMissedCount++;
1786 }
1787
Ady Abrahamadb9a992019-09-19 21:21:55 +00001788 if (frameMissed && mPropagateBackpressure) {
1789 if ((hwcFrameMissed && !gpuFrameMissed) ||
1790 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001791 signalLayerUpdate();
1792 break;
1793 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001794 }
Dan Stoza50182882016-07-08 12:02:20 -07001795
Steven Thomas050b2c82017-03-06 11:45:16 -08001796 // Now that we're going to make it to the handleMessageTransaction()
1797 // call below it's safe to call updateVrFlinger(), which will
1798 // potentially trigger a display handoff.
1799 updateVrFlinger();
1800
Dan Stoza6b9454d2014-11-07 16:00:59 -08001801 bool refreshNeeded = handleMessageTransaction();
1802 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001803
Ana Krulecc84d09b2019-11-02 23:10:29 +01001804 // Layers need to get updated (in the previous line) before we can use them for
1805 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001806 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1807 // and may eventually call to ~Layer() if it holds the last reference
1808 {
1809 Mutex::Autolock _l(mStateLock);
1810 mScheduler->chooseRefreshRateForContent();
1811 }
1812
Ana Krulecc84d09b2019-11-02 23:10:29 +01001813 if (performSetActiveConfig()) {
1814 break;
1815 }
1816
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001817 updateCursorAsync();
1818 updateInputFlinger();
1819
Dan Stoza58784442014-12-02 16:58:17 -08001820 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001821 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001822 // Signal a refresh if a transaction modified the window state,
1823 // a new buffer was latched, or if HWC has requested a full
1824 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001825 if (mFrameStartTime <= 0) {
1826 // We should only use the time of the first invalidate
1827 // message that signals a refresh as the beginning of the
1828 // frame. Otherwise the real frame time will be
1829 // underestimated.
1830 mFrameStartTime = frameStart;
1831 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001832 signalRefresh();
1833 }
1834 break;
1835 }
1836 case MessageQueue::REFRESH: {
1837 handleMessageRefresh();
1838 break;
1839 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001840 }
1841}
1842
Dan Stoza6b9454d2014-11-07 16:00:59 -08001843bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001844 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001845 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001846
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001847 bool flushedATransaction = flushTransactionQueues();
1848
1849 bool runHandleTransaction = transactionFlags &&
1850 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1851
1852 if (runHandleTransaction) {
1853 handleTransaction(eTransactionMask);
1854 } else {
1855 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001856 }
1857
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001858 if (transactionFlushNeeded()) {
1859 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001860 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001861
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001862 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001863}
1864
Mathias Agopian4fec8732012-06-29 14:12:52 -07001865void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001867
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001868 mRefreshPending = false;
1869
Lloyd Piqueab039b52019-02-13 14:22:42 -08001870 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001871 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001872 for (const auto& [_, display] : mDisplays) {
1873 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1874 }
1875 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001876 if (auto layerFE = layer->getCompositionEngineLayerFE())
1877 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001878 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001879 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1880 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001881 if (auto layerFE = layer->getCompositionEngineLayerFE())
1882 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001883 }
1884
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001885 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001886 refreshArgs.outputColorSetting = useColorManagement
1887 ? mDisplayColorSetting
1888 : compositionengine::OutputColorSetting::kUnmanaged;
1889 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1890 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001891
1892 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1893 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001894
1895 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1896 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1897 mDrawingState.colorMatrixChanged = false;
1898 }
1899
1900 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1901
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001902 if (mDebugRegion != 0) {
1903 refreshArgs.devOptFlashDirtyRegionsDelay =
1904 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1905 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001906
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001907 mGeometryInvalid = false;
1908
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001909 // Store the present time just before calling to the composition engine so we could notify
1910 // the scheduler.
1911 const auto presentTime = systemTime();
1912
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001913 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001914 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1915 // Reset the frame start time now that we've recorded this frame.
1916 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001917
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001918 mScheduler->onDisplayRefreshed(presentTime);
1919
David Sodmanfa9b2af2017-12-24 13:28:59 -08001920 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001921 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001922
Lloyd Pique66d68602019-02-13 14:23:31 -08001923 mHadClientComposition =
1924 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1925 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001926 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1927 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001928 });
1929 mHadDeviceComposition =
1930 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1931 auto& displayDevice = tokenDisplayPair.second;
1932 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1933 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001934 mReusedClientComposition =
1935 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1936 auto& displayDevice = tokenDisplayPair.second;
1937 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1938 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001939
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001940 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001941
David Sodman7e4ae112018-02-09 15:02:28 -08001942 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001943 if (mVisibleRegionsDirty) {
1944 mVisibleRegionsDirty = false;
1945 if (mTracingEnabled) {
1946 mTracing.notify("visibleRegionsDirty");
1947 }
1948 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001949
1950 if (mCompositionEngine->needsAnotherUpdate()) {
1951 signalLayerUpdate();
1952 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001953}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001954
David Sodmanfa9b2af2017-12-24 13:28:59 -08001955
1956bool SurfaceFlinger::handleMessageInvalidate() {
1957 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001958 bool refreshNeeded = handlePageFlip();
1959
Vishnu Nair4351ad52019-02-11 14:13:02 -08001960 if (mVisibleRegionsDirty) {
1961 computeLayerBounds();
1962 }
1963
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001964 for (auto& layer : mLayersPendingRefresh) {
1965 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001966 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001967 invalidateLayerStack(layer, visibleReg);
1968 }
1969 mLayersPendingRefresh.clear();
1970 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001971}
1972
Ana Krulece588e312018-09-18 12:32:24 -07001973void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1974 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975 // Update queue of past composite+present times and determine the
1976 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001977 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001979 while (!getBE().mCompositePresentTimes.empty()) {
1980 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981 // Cached values should have been updated before calling this method,
1982 // which helps avoid duplicate syscalls.
1983 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1984 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1985 break;
1986 }
1987 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001988 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001989 }
1990
1991 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001992 while (getBE().mCompositePresentTimes.size() > 16) {
1993 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001994 }
1995
Ana Krulece588e312018-09-18 12:32:24 -07001996 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001997}
1998
Ana Krulece588e312018-09-18 12:32:24 -07001999void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2000 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002001 // Integer division and modulo round toward 0 not -inf, so we need to
2002 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002003 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2004 ? (stats.vsyncPeriod -
2005 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2006 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002007
Ady Abraham9e16a482019-12-03 17:19:41 -08002008 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002009 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002010 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002011 }
2012
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002013 // Snap the latency to a value that removes scheduling jitter from the
2014 // composition and present times, which often have >1ms of jitter.
2015 // Reducing jitter is important if an app attempts to extrapolate
2016 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002017 // Snapping also allows an app to precisely calculate
2018 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002019 nsecs_t bias = stats.vsyncPeriod / 2;
2020 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2021 nsecs_t snappedCompositeToPresentLatency =
2022 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002023
David Sodman99974d22017-11-28 12:04:33 -08002024 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002025 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2026 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002027 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028}
2029
David Sodman2b406362017-12-15 13:33:47 -08002030void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 ATRACE_CALL();
2033 ALOGV("postComposition");
2034
Brian Andersonf6386862016-10-31 16:34:13 -07002035 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002036 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002037 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002038 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002039 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002040 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002044 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002045 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002046 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2047 ->getRenderSurface()
2048 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002049 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002050 } else {
2051 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2052 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002053
David Sodman73beded2017-11-15 11:56:06 -08002054 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002055 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2056 mPreviousPresentFences[0] = displayDevice
2057 ? getHwComposer().getPresentFence(*displayDevice->getId())
2058 : Fence::NO_FENCE;
2059 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002060 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061
Ana Krulece588e312018-09-18 12:32:24 -07002062 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002063 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064
Lloyd Piqueab039b52019-02-13 14:22:42 -08002065 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2066 // be sampled a little later than when we started doing work for this frame,
2067 // but that should be okay since updateCompositorTiming has snapping logic.
2068 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2069 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002070 CompositorTiming compositorTiming;
2071 {
David Sodman99974d22017-11-28 12:04:33 -08002072 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2073 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002074 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
Edgar Arriaga844fa672020-01-16 14:21:42 -08002076 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002077 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2078 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002079 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002080 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002081 }
Robert Carr2047fae2016-11-28 14:09:09 -08002082 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002083
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002084 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002085 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002086 }
2087
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002088 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002089 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2090 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002091 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002092 }
2093 }
2094
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002095 if (mAnimCompositionPending) {
2096 mAnimCompositionPending = false;
2097
Brian Anderson4e606e32017-03-16 15:34:57 -07002098 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002099 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002100 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 // The HWC doesn't support present fences, so use the refresh
2103 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 const nsecs_t presentTime =
2105 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 mAnimFrameTracker.setActualPresentTime(presentTime);
2107 }
2108 mAnimFrameTracker.advanceFrame();
2109 }
Dan Stozab90cf072015-03-05 11:05:59 -08002110
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002111 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002112 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002113 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002114 }
2115
Vishnu Nair9b079a22020-01-21 14:36:08 -08002116 if (mReusedClientComposition) {
2117 mTimeStats->incrementClientCompositionReusedFrames();
2118 }
2119
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002120 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002121
Lloyd Pique32cbe282018-10-19 13:09:22 -07002122 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2123 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002124 return;
2125 }
2126
2127 nsecs_t currentTime = systemTime();
2128 if (mHasPoweredOff) {
2129 mHasPoweredOff = false;
2130 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002131 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002132 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002133 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2134 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002135 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002136 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002137 }
David Sodman4a36e932017-11-07 14:29:47 -08002138 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002139 }
David Sodman4a36e932017-11-07 14:29:47 -08002140 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002141
2142 {
2143 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002144 if (mTexturePool.size() < mTexturePoolSize) {
2145 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002146 const size_t offset = mTexturePool.size();
2147 mTexturePool.resize(mTexturePoolSize);
2148 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2149 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002150 } else if (mTexturePool.size() > mTexturePoolSize) {
2151 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2152 const size_t offset = mTexturePoolSize;
2153 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2154 mTexturePool.resize(mTexturePoolSize);
2155 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002156 }
2157 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002158
Ady Abrahambe0f9482019-04-24 15:41:53 -07002159 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002160 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002161
Kevin DuBois413287f2019-02-25 08:46:47 -08002162 if (mLumaSampling && mRegionSamplingThread) {
2163 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002164 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002165
2166 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2167 // side-effect of getTotalSize(), so we check that again here
2168 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002169 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002170 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2171 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002172}
2173
Vishnu Nair4351ad52019-02-11 14:13:02 -08002174void SurfaceFlinger::computeLayerBounds() {
2175 for (const auto& pair : mDisplays) {
2176 const auto& displayDevice = pair.second;
2177 const auto display = displayDevice->getCompositionDisplay();
2178 for (const auto& layer : mDrawingState.layersSortedByZ) {
2179 // only consider the layers on the given layer stack
2180 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002181 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002182 }
2183
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002184 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2185 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002186 }
2187 }
2188}
2189
David Sodmanfa9b2af2017-12-24 13:28:59 -08002190void SurfaceFlinger::postFrame()
2191{
2192 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002193 const auto display = getDefaultDisplayDeviceLocked();
2194 if (display && getHwComposer().isConnected(*display->getId())) {
2195 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2197 logFrameStats();
2198 }
2199 }
2200}
2201
Mathias Agopian87baae12012-07-31 12:38:26 -07002202void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203{
Mathias Agopian841cde52012-03-01 15:44:37 -08002204 ATRACE_CALL();
2205
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002206 // here we keep a copy of the drawing state (that is the state that's
2207 // going to be overwritten by handleTransactionLocked()) outside of
2208 // mStateLock so that the side-effects of the State assignment
2209 // don't happen with mStateLock held (which can cause deadlocks).
2210 State drawingState(mDrawingState);
2211
Mathias Agopianca4d3602011-05-19 15:38:14 -07002212 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002213 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214
Mathias Agopianca4d3602011-05-19 15:38:14 -07002215 // Here we're guaranteed that some transaction flags are set
2216 // so we can call handleTransactionLocked() unconditionally.
2217 // We call getTransactionFlags(), which will also clear the flags,
2218 // with mStateLock held to guarantee that mCurrentState won't change
2219 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002220
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002221 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002222 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002223 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002224
Mathias Agopianca4d3602011-05-19 15:38:14 -07002225 mDebugInTransaction = 0;
2226 invalidateHwcGeometry();
2227 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002228}
2229
Lloyd Piqueba04e622017-12-14 17:11:26 -08002230void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2231 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002232 const std::optional<DisplayIdentificationInfo> info =
2233 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234
Dominik Laskowski075d3172018-05-24 15:50:06 -07002235 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002236 continue;
2237 }
2238
Lloyd Piqueba04e622017-12-14 17:11:26 -08002239 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002240 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002241 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002242 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2243 initScheduler(info->id);
2244 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 mPhysicalDisplayTokens[info->id] = new BBinder();
2246 DisplayDeviceState state;
2247 state.displayId = info->id;
2248 state.isSecure = true; // All physical displays are currently considered secure.
2249 state.displayName = info->name;
2250 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2251 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002252 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002253 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002254 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002255
Dominik Laskowski075d3172018-05-24 15:50:06 -07002256 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2257 if (index >= 0) {
2258 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2259 mInterceptor->saveDisplayDeletion(state.sequenceId);
2260 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002261 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263 }
2264
2265 processDisplayChangesLocked();
2266 }
2267
2268 mPendingHotplugEvents.clear();
2269}
2270
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002271void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002272 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2273 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002274}
2275
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002277 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002278 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 const sp<IGraphicBufferProducer>& producer) {
2280 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002281 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002282 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002283 creationArgs.isSecure = state.isSecure;
2284 creationArgs.displaySurface = dispSurface;
2285 creationArgs.hasWideColorGamut = false;
2286 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002287 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002289 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 creationArgs.isPrimary = isInternalDisplay;
2291
2292 if (useColorManagement && displayId) {
2293 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002295 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002296 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002297 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298
Dominik Laskowski7e045462018-05-30 13:02:02 -07002299 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002301 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002302 }
tangrobin6753a022018-08-10 10:58:54 +08002303 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 if (displayId) {
2306 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002307 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002309 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310
Lloyd Pique90c115d2018-09-18 21:39:42 -07002311 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002313 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 // Make sure that composition can never be stalled by a virtual display
2316 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002317 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002318 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2320 }
2321
Dominik Laskowski718f9602019-11-09 20:01:35 -08002322 creationArgs.physicalOrientation =
2323 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002324
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002326 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327
Lloyd Pique90c115d2018-09-18 21:39:42 -07002328 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329
2330 if (maxFrameBufferAcquiredBuffers >= 3) {
2331 nativeWindowSurface->preallocateBuffers();
2332 }
2333
2334 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002336 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002338 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002340 display->getCompositionDisplay()->setColorProfile(
2341 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2342 RenderIntent::COLORIMETRIC,
2343 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002344 if (!state.isVirtual()) {
2345 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002346 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2347 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002348 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002349
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 display->setLayerStack(state.layerStack);
2351 display->setProjection(state.orientation, state.viewport, state.frame);
2352 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355}
2356
Lloyd Pique347200f2017-12-14 17:00:15 -08002357void SurfaceFlinger::processDisplayChangesLocked() {
2358 // here we take advantage of Vector's copy-on-write semantics to
2359 // improve performance by skipping the transaction entirely when
2360 // know that the lists are identical
2361 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2362 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2363 if (!curr.isIdenticalTo(draw)) {
2364 mVisibleRegionsDirty = true;
2365 const size_t cc = curr.size();
2366 size_t dc = draw.size();
2367
2368 // find the displays that were removed
2369 // (ie: in drawing state but not in current state)
2370 // also handle displays that changed
2371 // (ie: displays that are in both lists)
2372 for (size_t i = 0; i < dc;) {
2373 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2374 if (j < 0) {
2375 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002377 // Save display ID before disconnecting.
2378 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002379 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002380
2381 if (!display->isVirtual()) {
2382 LOG_ALWAYS_FATAL_IF(!displayId);
2383 dispatchDisplayHotplugEvent(displayId->value, false);
2384 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002386
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002387 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002388 } else {
2389 // this display is in both lists. see if something changed.
2390 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002391 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2393 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2394 if (state_binder != draw_binder) {
2395 // changing the surface is like destroying and
2396 // recreating the DisplayDevice, so we just remove it
2397 // from the drawing state, so that it get re-added
2398 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002400 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002401 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002402 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403 mDrawingState.displays.removeItemsAt(i);
2404 dc--;
2405 // at this point we must loop to the next item
2406 continue;
2407 }
2408
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002409 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002410 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002411 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 }
2413 if ((state.orientation != draw[i].orientation) ||
2414 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416 }
2417 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002418 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002419 if (display->isPrimary()) {
2420 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2421 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 }
2423 }
2424 }
2425 ++i;
2426 }
2427
2428 // find displays that were added
2429 // (ie: in current state but not in drawing state)
2430 for (size_t i = 0; i < cc; i++) {
2431 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2432 const DisplayDeviceState& state(curr[i]);
2433
Lloyd Pique542307f2018-10-19 13:24:08 -07002434 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002435 sp<IGraphicBufferProducer> producer;
2436 sp<IGraphicBufferProducer> bqProducer;
2437 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002438 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002439
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002441 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 // Virtual displays without a surface are dormant:
2443 // they have external state (layer stack, projection,
2444 // etc.) but no internal state (i.e. a DisplayDevice).
2445 if (state.surface != nullptr) {
2446 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 int width = 0;
2449 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2450 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2451 int height = 0;
2452 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2453 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2454 int intFormat = 0;
2455 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2456 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002457 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002458
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 displayId =
2460 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 }
2462
2463 // TODO: Plumb requested format back up to consumer
2464
2465 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002466 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 bqProducer, bqConsumer,
2468 state.displayName);
2469
2470 dispSurface = vds;
2471 producer = vds;
2472 }
2473 } else {
2474 ALOGE_IF(state.surface != nullptr,
2475 "adding a supported display, but rendering "
2476 "surface is provided (%p), ignoring it",
2477 state.surface.get());
2478
Dominik Laskowski075d3172018-05-24 15:50:06 -07002479 displayId = state.displayId;
2480 LOG_ALWAYS_FATAL_IF(!displayId);
2481 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 producer = bqProducer;
2483 }
2484
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002487 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002488 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002490 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002492 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002494
2495 const auto displayDevice = mDisplays[displayToken];
2496 if (displayDevice->isPrimary()) {
2497 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2498 displayDevice->getHeight());
2499 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 }
2501 }
2502 }
2503 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002504
2505 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002506}
2507
Mathias Agopian87baae12012-07-31 12:38:26 -07002508void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002509{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002510 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2511
Dan Stoza7dde5992015-05-22 09:51:44 -07002512 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002513 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002514 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002515 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002516
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 /*
2518 * Traversal of the children
2519 * (perform the transaction for each of them if needed)
2520 */
2521
Marissa Wall06255332019-03-27 13:48:27 -07002522 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002523 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002525 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
2527 const uint32_t flags = layer->doTransaction(0);
2528 if (flags & Layer::eVisibleRegion)
2529 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002530
2531 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002532 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002533 }
Robert Carr2047fae2016-11-28 14:09:09 -08002534 });
Marissa Wall06255332019-03-27 13:48:27 -07002535 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536 }
2537
2538 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002539 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 */
2541
Mathias Agopiane57f2922012-08-09 16:29:12 -07002542 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002547 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002548 // The transform hint might have changed for some layers
2549 // (either because a display has changed, or because a layer
2550 // as changed).
2551 //
2552 // Walk through all the layers in currentLayers,
2553 // and update their transform hint.
2554 //
2555 // If a layer is visible only on a single display, then that
2556 // display is used to calculate the hint, otherwise we use the
2557 // default display.
2558 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002559 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002560 // the hint is set before we acquire a buffer from the surface texture.
2561 //
2562 // NOTE: layer transactions have taken place already, so we use their
2563 // drawing state. However, SurfaceFlinger's own transaction has not
2564 // happened yet, so we must use the current state layer list
2565 // (soon to become the drawing state list).
2566 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002567 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002568 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002569 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002570 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002571 // NOTE: we rely on the fact that layers are sorted by
2572 // layerStack first (so we don't have to traverse the list
2573 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002574 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002575 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002576 currentlayerStack = layerStack;
2577 // figure out if this layerstack is mirrored
2578 // (more than one display) if so, pick the default display,
2579 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002580 hintDisplay = nullptr;
2581 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002582 if (display->getCompositionDisplay()
2583 ->belongsInOutput(layer->getLayerStack(),
2584 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002585 if (hintDisplay) {
2586 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002587 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002588 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002589 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002590 }
2591 }
2592 }
2593 }
Chet Haase91d25932013-04-11 15:24:55 -07002594
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002595 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002596 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2597 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002598
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002599 // could be null when this layer is using a layerStack
2600 // that is not visible on any display. Also can occur at
2601 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002602 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002603 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002604
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002605 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002606 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 if (hintDisplay) {
2608 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002609 }
Robert Carr2047fae2016-11-28 14:09:09 -08002610
2611 first = false;
2612 });
Mathias Agopian84300952012-11-21 16:02:13 -08002613 }
2614
2615
Mathias Agopian3559b072012-08-15 13:46:03 -07002616 /*
2617 * Perform our own transaction if needed
2618 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619
2620 if (mLayersAdded) {
2621 mLayersAdded = false;
2622 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002623 mVisibleRegionsDirty = true;
2624 }
2625
2626 // some layers might have been removed, so
2627 // we need to update the regions they're exposing.
2628 if (mLayersRemoved) {
2629 mLayersRemoved = false;
2630 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002631 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002633 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002635 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002636 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002637 }
Robert Carr2047fae2016-11-28 14:09:09 -08002638 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 }
2640
Vishnu Nairec0ab382019-02-13 15:32:56 -08002641 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002643}
2644
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002645void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002646 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002647 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002648 return;
2649 }
2650
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002651 if (mVisibleRegionsDirty || mInputInfoChanged) {
2652 mInputInfoChanged = false;
2653 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002654 } else if (mInputWindowCommands.syncInputWindows) {
2655 // If the caller requested to sync input windows, but there are no
2656 // changes to input windows, notify immediately.
2657 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002658 }
2659
Arthur Hung6cbb9752019-09-05 16:38:18 +08002660 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002661}
2662
2663void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002664 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002665
2666 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2667 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002668 // When calculating the screen bounds we ignore the transparent region since it may
2669 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002670 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002671 }
2672 });
chaviw291d88a2019-02-14 10:33:58 -08002673
2674 mInputFlinger->setInputWindows(inputHandles,
2675 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2676 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002677}
2678
Vishnu Nairec0ab382019-02-13 15:32:56 -08002679void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002680 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002681 mPendingInputWindowCommands.clear();
2682}
2683
Riley Andrews03414a12014-07-01 14:22:59 -07002684void SurfaceFlinger::updateCursorAsync()
2685{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002686 compositionengine::CompositionRefreshArgs refreshArgs;
2687 for (const auto& [_, display] : mDisplays) {
2688 if (display->getId()) {
2689 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002690 }
2691 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002692
2693 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002694}
2695
Ady Abraham2139f732019-11-13 18:56:40 -08002696void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002697 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2698 // If this is called from the main thread mStateLock must be locked before
2699 // Currently the only way to call this function from the main thread is from
2700 // Sheduler::chooseRefreshRateForContent
2701
2702 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002703 changeRefreshRateLocked(refreshRate, event);
2704}
2705
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002706void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2707 if (mScheduler) {
2708 // In practice it's not allowed to hotplug in/out the primary display once it's been
2709 // connected during startup, but some tests do it, so just warn and return.
2710 ALOGW("Can't re-init scheduler");
2711 return;
2712 }
2713
Ady Abraham2139f732019-11-13 18:56:40 -08002714 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002715 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002716 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002717 primaryDisplayId),
2718 currentConfig);
2719 mRefreshRateStats =
2720 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2721 currentConfig, HWC_POWER_MODE_OFF);
2722 mRefreshRateStats->setConfigMode(currentConfig);
2723
Ady Abraham9e16a482019-12-03 17:19:41 -08002724 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2725
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002726 // start the EventThread
2727 mScheduler =
2728 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002729 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002730 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002731 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002732 impl::EventThread::InterceptVSyncsCallback());
2733 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002734 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002735 [this](nsecs_t timestamp) {
2736 mInterceptor->saveVSyncEvent(timestamp);
2737 });
2738
2739 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2740 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002741 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002742
2743 mRegionSamplingThread =
2744 new RegionSamplingThread(*this, *mScheduler,
2745 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002746 // Dispatch a config change request for the primary display on scheduler
2747 // initialization, so that the EventThreads always contain a reference to a
2748 // prior configuration.
2749 //
2750 // This is a bit hacky, but this avoids a back-pointer into the main SF
2751 // classes from EventThread, and there should be no run-time binder cost
2752 // anyway since there are no connected apps at this point.
2753 const nsecs_t vsyncPeriod =
2754 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2755 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2756 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002757}
2758
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759void SurfaceFlinger::commitTransaction()
2760{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002761 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002762
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002763 mTransactionPending = false;
2764 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002765 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766}
2767
Lloyd Pique58e24a32019-08-01 15:50:14 -07002768void SurfaceFlinger::commitTransactionLocked() {
2769 if (!mLayersPendingRemoval.isEmpty()) {
2770 // Notify removed layers now that they can't be drawn from
2771 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002772 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002773
2774 // Ensure any buffers set to display on any children are released.
2775 if (l->isRemovedFromCurrentState()) {
2776 l->latchAndReleaseBuffer();
2777 }
2778
2779 // If the layer has been removed and has no parent, then it will not be reachable
2780 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2781 // ensure we can copy its current to drawing state.
2782 if (!l->getParent()) {
2783 mOffscreenLayers.emplace(l.get());
2784 }
2785 }
2786 mLayersPendingRemoval.clear();
2787 }
2788
2789 // If this transaction is part of a window animation then the next frame
2790 // we composite should be considered an animation as well.
2791 mAnimCompositionPending = mAnimTransactionPending;
2792
2793 mDrawingState = mCurrentState;
2794 // clear the "changed" flags in current state
2795 mCurrentState.colorMatrixChanged = false;
2796
Edgar Arriaga844fa672020-01-16 14:21:42 -08002797 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002798 layer->commitChildList();
2799
2800 // If the layer can be reached when traversing mDrawingState, then the layer is no
2801 // longer offscreen. Remove the layer from the offscreenLayer set.
2802 if (mOffscreenLayers.count(layer)) {
2803 mOffscreenLayers.erase(layer);
2804 }
2805 });
2806
2807 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002808 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002809}
2810
Nataniel Borges2b796da2019-02-15 13:32:18 -08002811void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2812 if (mTracingEnabledChanged) {
2813 mTracingEnabled = mTracing.isEnabled();
2814 mTracingEnabledChanged = false;
2815 }
2816
2817 // Synchronize with Tracing thread
2818 std::unique_lock<std::mutex> lock;
2819 if (mTracingEnabled) {
2820 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2821 }
2822
2823 lockedOperation();
2824
2825 // Synchronize with Tracing thread
2826 if (mTracingEnabled) {
2827 lock.unlock();
2828 }
2829}
2830
chaviw74d90ad2019-04-26 14:45:26 -07002831void SurfaceFlinger::commitOffscreenLayers() {
2832 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002833 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002834 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2835 if (!trFlags) return;
2836
2837 layer->doTransaction(0);
2838 layer->commitChildList();
2839 });
2840 }
2841}
2842
Chia-I Wuab0c3192017-08-01 11:29:00 -07002843void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002844 for (const auto& [token, displayDevice] : mDisplays) {
2845 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002846 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002847 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002848 }
2849 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002850}
2851
Dan Stoza6b9454d2014-11-07 16:00:59 -08002852bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853{
Ady Abraham09bd3922019-04-08 10:44:56 -07002854 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 ALOGV("handlePageFlip");
2856
Brian Andersond6927fb2016-07-23 23:37:30 -07002857 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002861 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002862
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002863 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2864
Eric Penner51c59cd2014-07-28 19:51:58 -07002865 // Store the set of layers that need updates. This set must not change as
2866 // buffers are being latched, as this could result in a deadlock.
2867 // Example: Two producers share the same command stream and:
2868 // 1.) Layer 0 is latched
2869 // 2.) Layer 0 gets a new frame
2870 // 2.) Layer 1 gets a new frame
2871 // 3.) Layer 1 is latched.
2872 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2873 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002874 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002875 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002876 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002877 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002878 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002879 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002880 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002881 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002882 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002883 } else {
2884 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 }
Robert Carr2047fae2016-11-28 14:09:09 -08002886 });
2887
chaviw49a108c2019-08-12 11:23:06 -07002888 // The client can continue submitting buffers for offscreen layers, but they will not
2889 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2890 // layers to ensure dequeueBuffer doesn't block indefinitely.
2891 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002892 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002893 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2894 }
2895
Lloyd Piquef2c79392018-12-20 16:23:33 -08002896 if (!mLayersWithQueuedFrames.empty()) {
2897 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2898 // writes to Layer current state. See also b/119481871
2899 Mutex::Autolock lock(mStateLock);
2900
2901 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002902 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002903 mLayersPendingRefresh.push_back(layer);
2904 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002905 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002906 if (layer->isBufferLatched()) {
2907 newDataLatched = true;
2908 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002909 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002911
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002912 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002913
2914 // If we will need to wake up at some time in the future to deal with a
2915 // queued frame that shouldn't be displayed during this vsync period, wake
2916 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002917 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002918 signalLayerUpdate();
2919 }
2920
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002921 // enter boot animation on first buffer latch
2922 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2923 ALOGI("Enter boot animation");
2924 mBootStage = BootStage::BOOTANIMATION;
2925 }
2926
Edgar Arriaga844fa672020-01-16 14:21:42 -08002927 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002928
Dan Stoza6b9454d2014-11-07 16:00:59 -08002929 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002930 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931}
2932
Mathias Agopianad456f92011-01-13 17:53:01 -08002933void SurfaceFlinger::invalidateHwcGeometry()
2934{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002936}
2937
Robert Carrc0df3122019-04-11 13:18:21 -07002938status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2939 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2940 const sp<IBinder>& parentHandle,
2941 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002942 // add this layer to the current state list
2943 {
2944 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002945 sp<Layer> parent;
2946 if (parentHandle != nullptr) {
2947 parent = fromHandle(parentHandle);
2948 if (parent == nullptr) {
2949 return NAME_NOT_FOUND;
2950 }
2951 } else {
2952 parent = parentLayer;
2953 }
2954
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002956 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002957 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002958 return NO_MEMORY;
2959 }
Robert Carrc0df3122019-04-11 13:18:21 -07002960
2961 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2962
Robert Carrb89ea9d2018-12-10 13:01:14 -08002963 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002965 } else if (parent == nullptr) {
2966 lbc->onRemovedFromCurrentState();
2967 } else if (parent->isRemovedFromCurrentState()) {
2968 parent->addChild(lbc);
2969 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002970 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002971 parent->addChild(lbc);
2972 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002973
Yiwei Zhang243b3782018-05-15 17:40:04 -07002974 if (gbc != nullptr) {
2975 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2976 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2977 mMaxGraphicBufferProducerListSize,
2978 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2979 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002980 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002981 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002982 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002983 }
2984
Mathias Agopian96f08192010-06-02 23:28:45 -07002985 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002986 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002987
Dan Stoza7d89d062015-04-30 13:29:25 -07002988 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002989}
2990
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002991uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002992 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002993}
2994
Mathias Agopian3f844832013-08-07 21:24:32 -07002995uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002996 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Mathias Agopian3f844832013-08-07 21:24:32 -07002999uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003000 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003001}
3002
3003uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003004 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003005 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003006 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003008 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009 }
3010 return old;
3011}
3012
Marissa Wall713b63f2018-10-17 15:42:43 -07003013bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003014 // to prevent onHandleDestroyed from being called while the lock is held,
3015 // we must keep a copy of the transactions (specifically the composer
3016 // states) around outside the scope of the lock
3017 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003018 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003019 {
3020 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003021
Valerie Haufce31b82019-04-30 16:41:14 -07003022 auto it = mTransactionQueues.begin();
3023 while (it != mTransactionQueues.end()) {
3024 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003025
Valerie Haufce31b82019-04-30 16:41:14 -07003026 while (!transactionQueue.empty()) {
3027 const auto& transaction = transactionQueue.front();
3028 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003029 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003030 transaction.states)) {
3031 setTransactionFlags(eTransactionFlushNeeded);
3032 break;
3033 }
3034 transactions.push_back(transaction);
3035 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3036 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003037 transaction.buffer, transaction.postTime,
3038 transaction.privileged, transaction.hasListenerCallbacks,
3039 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003040 transactionQueue.pop();
3041 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003042 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003043
Valerie Haufce31b82019-04-30 16:41:14 -07003044 if (transactionQueue.empty()) {
3045 it = mTransactionQueues.erase(it);
3046 mTransactionCV.broadcast();
3047 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003048 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003049 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003050 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003051 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003052 return flushedATransaction;
3053}
3054
3055bool SurfaceFlinger::transactionFlushNeeded() {
3056 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003057}
3058
chaviwca27f252018-02-06 16:46:39 -08003059
Marissa Wall17b4e452018-12-26 16:32:34 -08003060bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003061 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003062 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003063 if (!useCachedExpectedPresentTime)
3064 populateExpectedPresentTime();
3065
3066 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003067 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3068 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3069 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3070 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3071 return false;
3072 }
3073
Marissa Wall713b63f2018-10-17 15:42:43 -07003074 for (const ComposerState& state : states) {
3075 const layer_state_t& s = state.state;
3076 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3077 continue;
3078 }
3079 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003080 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003081 }
3082 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003083 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003084}
3085
Valerie Hau9dab9732019-08-20 09:29:25 -07003086void SurfaceFlinger::setTransactionState(
3087 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3088 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3089 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3090 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003091 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003092
Valerie Haubc6ddb12019-03-08 11:10:15 -08003093 const int64_t postTime = systemTime();
3094
Robert Carr14167e02019-02-13 13:50:55 -08003095 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3096
Mathias Agopian698c0872011-06-28 19:09:31 -07003097 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098
Marissa Wall713b63f2018-10-17 15:42:43 -07003099 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003100 auto itr = mTransactionQueues.find(applyToken);
3101 // if this is an animation frame, wait until prior animation frame has
3102 // been applied by SF
3103 if (flags & eAnimation) {
3104 while (itr != mTransactionQueues.end()) {
3105 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3106 if (CC_UNLIKELY(err != NO_ERROR)) {
3107 ALOGW_IF(err == TIMED_OUT,
3108 "setTransactionState timed out "
3109 "waiting for animation frame to apply");
3110 break;
3111 }
3112 itr = mTransactionQueues.find(applyToken);
3113 }
3114 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003115
3116 // Expected present time is computed and cached on invalidate, so it may be stale.
3117 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3118 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003119 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003120 uncacheBuffer, postTime, privileged,
3121 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003122 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003123 return;
3124 }
3125
Valerie Haubc6ddb12019-03-08 11:10:15 -08003126 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003127 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3128 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003129}
3130
Valerie Hau9dab9732019-08-20 09:29:25 -07003131void SurfaceFlinger::applyTransactionState(
3132 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3133 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3134 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3135 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3136 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003137 uint32_t transactionFlags = 0;
3138
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003139 if (flags & eAnimation) {
3140 // For window updates that are part of an animation we must wait for
3141 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003142 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003143 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003144 if (CC_UNLIKELY(err != NO_ERROR)) {
3145 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003146 // caller after a few seconds.
3147 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3148 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003149 mAnimTransactionPending = false;
3150 break;
3151 }
3152 }
3153 }
3154
chaviwca27f252018-02-06 16:46:39 -08003155 for (const DisplayState& display : displays) {
3156 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003157 }
3158
Valerie Hau9dab9732019-08-20 09:29:25 -07003159 // start and end registration for listeners w/ no surface so they can get their callback. Note
3160 // that listeners with SurfaceControls will start registration during setClientStateLocked
3161 // below.
3162 for (const auto& listener : listenerCallbacks) {
3163 mTransactionCompletedThread.startRegistration(listener);
3164 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003165 }
3166
Valerie Hau9dab9732019-08-20 09:29:25 -07003167 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003168 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003169 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003170 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3171 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003172 }
3173
Valerie Hau9dab9732019-08-20 09:29:25 -07003174 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003175 mTransactionCompletedThread.endRegistration(listenerCallback);
3176 }
3177
Marissa Walle2ffb422018-10-12 11:33:52 -07003178 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003179 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003180 mTransactionCompletedThread.sendCallbacks();
3181 }
3182 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003183
chaviw273171b2018-12-26 11:46:30 -08003184 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3185
Marissa Wall947d34e2019-03-29 14:03:53 -07003186 if (uncacheBuffer.isValid()) {
3187 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003188 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003189 }
3190
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003191 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3192 // anyway. This can be used as a flush mechanism for previous async transactions.
3193 // Empty animation transaction can be used to simulate back-pressure, so also force a
3194 // transaction for empty animation transactions.
3195 if (transactionFlags == 0 &&
3196 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003197 transactionFlags = eTransactionNeeded;
3198 }
3199
Marissa Wall06255332019-03-27 13:48:27 -07003200 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3201 // so we don't have to wake up again next frame to preform an uneeded traversal.
3202 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3203 transactionFlags = transactionFlags & (~eTraversalNeeded);
3204 mTraversalNeededMainThread = true;
3205 }
3206
Mathias Agopian386aa982011-11-07 21:58:03 -08003207 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003208 if (mInterceptor->isEnabled()) {
3209 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003210 }
Irvel468051e2016-06-13 16:44:44 -07003211
Mathias Agopian386aa982011-11-07 21:58:03 -08003212 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003213 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3214 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003215 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003216
3217 // if this is a synchronous transaction, wait for it to take effect
3218 // before returning.
3219 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003220 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003221 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003222 if (flags & eAnimation) {
3223 mAnimTransactionPending = true;
3224 }
chaviw4fe36852019-04-15 16:25:49 -07003225 if (mPendingInputWindowCommands.syncInputWindows) {
3226 mPendingSyncInputWindows = true;
3227 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003228
3229 // applyTransactionState can be called by either the main SF thread or by
3230 // another process through setTransactionState. While a given process may wish
3231 // to wait on synchronous transactions, the main SF thread should never
3232 // be blocked. Therefore, we only wait if isMainThread is false.
3233 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003234 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3235 if (CC_UNLIKELY(err != NO_ERROR)) {
3236 // just in case something goes wrong in SF, return to the
3237 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003238 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3239 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003240 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003241 break;
3242 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003243 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 }
3245}
3246
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003247uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3248 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3249 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003250
Mathias Agopiane57f2922012-08-09 16:29:12 -07003251 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003252 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3253
3254 const uint32_t what = s.what;
3255 if (what & DisplayState::eSurfaceChanged) {
3256 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3257 state.surface = s.surface;
3258 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003259 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003260 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003261 if (what & DisplayState::eLayerStackChanged) {
3262 if (state.layerStack != s.layerStack) {
3263 state.layerStack = s.layerStack;
3264 flags |= eDisplayTransactionNeeded;
3265 }
3266 }
3267 if (what & DisplayState::eDisplayProjectionChanged) {
3268 if (state.orientation != s.orientation) {
3269 state.orientation = s.orientation;
3270 flags |= eDisplayTransactionNeeded;
3271 }
3272 if (state.frame != s.frame) {
3273 state.frame = s.frame;
3274 flags |= eDisplayTransactionNeeded;
3275 }
3276 if (state.viewport != s.viewport) {
3277 state.viewport = s.viewport;
3278 flags |= eDisplayTransactionNeeded;
3279 }
3280 }
3281 if (what & DisplayState::eDisplaySizeChanged) {
3282 if (state.width != s.width) {
3283 state.width = s.width;
3284 flags |= eDisplayTransactionNeeded;
3285 }
3286 if (state.height != s.height) {
3287 state.height = s.height;
3288 flags |= eDisplayTransactionNeeded;
3289 }
3290 }
3291
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 return flags;
3293}
3294
Robert Carr14167e02019-02-13 13:50:55 -08003295bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003296 IPCThreadState* ipc = IPCThreadState::self();
3297 const int pid = ipc->getCallingPid();
3298 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003299 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003300 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003301 return false;
3302 }
3303 return true;
3304}
3305
Marissa Wall3dad52d2019-03-22 14:03:19 -07003306uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003307 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3308 bool privileged,
3309 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003310 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003311
Valerie Hau9dab9732019-08-20 09:29:25 -07003312 for (auto& listener : s.listeners) {
3313 // note that startRegistration will not re-register if the listener has
3314 // already be registered for a prior surface control
3315 mTransactionCompletedThread.startRegistration(listener);
3316 listenerCallbacks.insert(listener);
3317 }
3318
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003319 sp<Layer> layer = nullptr;
3320 if (s.surface) {
3321 layer = fromHandle(s.surface);
3322 } else {
3323 // The client may provide us a null handle. Treat it as if the layer was removed.
3324 ALOGW("Attempt to set client state with a null layer handle");
3325 }
chaviw8b3871a2017-11-01 17:41:01 -07003326 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003327 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003328 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003329 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003330 }
chaviw8b3871a2017-11-01 17:41:01 -07003331 return 0;
3332 }
3333
chaviw8b3871a2017-11-01 17:41:01 -07003334 uint32_t flags = 0;
3335
Garfield Tan8a3083e2018-12-03 13:21:07 -08003336 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003337
3338 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3339 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003340 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003341 layer->pushPendingState();
3342 }
3343
Valerie Hau871d6352020-01-29 08:44:02 -08003344 // Only set by BLAST adapter layers
3345 if (what & layer_state_t::eProducerDisconnect) {
3346 layer->onDisconnect();
3347 }
3348
chaviw8b3871a2017-11-01 17:41:01 -07003349 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003350 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003351 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003352 }
chaviw8b3871a2017-11-01 17:41:01 -07003353 }
3354 if (what & layer_state_t::eLayerChanged) {
3355 // NOTE: index needs to be calculated before we update the state
3356 const auto& p = layer->getParent();
3357 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003358 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003359 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003360 mCurrentState.layersSortedByZ.removeAt(idx);
3361 mCurrentState.layersSortedByZ.add(layer);
3362 // we need traversal (state changed)
3363 // AND transaction (list changed)
3364 flags |= eTransactionNeeded|eTraversalNeeded;
3365 }
chaviw8b3871a2017-11-01 17:41:01 -07003366 } else {
3367 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003368 flags |= eTransactionNeeded|eTraversalNeeded;
3369 }
3370 }
chaviw8b3871a2017-11-01 17:41:01 -07003371 }
3372 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003373 // NOTE: index needs to be calculated before we update the state
3374 const auto& p = layer->getParent();
3375 if (p == nullptr) {
3376 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3377 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3378 mCurrentState.layersSortedByZ.removeAt(idx);
3379 mCurrentState.layersSortedByZ.add(layer);
3380 // we need traversal (state changed)
3381 // AND transaction (list changed)
3382 flags |= eTransactionNeeded|eTraversalNeeded;
3383 }
3384 } else {
3385 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3386 flags |= eTransactionNeeded|eTraversalNeeded;
3387 }
chaviw8b3871a2017-11-01 17:41:01 -07003388 }
3389 }
3390 if (what & layer_state_t::eSizeChanged) {
3391 if (layer->setSize(s.w, s.h)) {
3392 flags |= eTraversalNeeded;
3393 }
3394 }
3395 if (what & layer_state_t::eAlphaChanged) {
3396 if (layer->setAlpha(s.alpha))
3397 flags |= eTraversalNeeded;
3398 }
3399 if (what & layer_state_t::eColorChanged) {
3400 if (layer->setColor(s.color))
3401 flags |= eTraversalNeeded;
3402 }
Peiyong Lind3788632018-09-18 16:01:31 -07003403 if (what & layer_state_t::eColorTransformChanged) {
3404 if (layer->setColorTransform(s.colorTransform)) {
3405 flags |= eTraversalNeeded;
3406 }
3407 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003408 if (what & layer_state_t::eBackgroundColorChanged) {
3409 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3410 flags |= eTraversalNeeded;
3411 }
3412 }
chaviw8b3871a2017-11-01 17:41:01 -07003413 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003414 // TODO: b/109894387
3415 //
3416 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3417 // rotation. To see the problem observe that if we have a square parent, and a child
3418 // of the same size, then we rotate the child 45 degrees around it's center, the child
3419 // must now be cropped to a non rectangular 8 sided region.
3420 //
3421 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3422 // private API, and the WindowManager only uses rotation in one case, which is on a top
3423 // level layer in which cropping is not an issue.
3424 //
3425 // However given that abuse of rotation matrices could lead to surfaces extending outside
3426 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3427 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3428 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003429 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003430 flags |= eTraversalNeeded;
3431 }
3432 if (what & layer_state_t::eTransparentRegionChanged) {
3433 if (layer->setTransparentRegionHint(s.transparentRegion))
3434 flags |= eTraversalNeeded;
3435 }
3436 if (what & layer_state_t::eFlagsChanged) {
3437 if (layer->setFlags(s.flags, s.mask))
3438 flags |= eTraversalNeeded;
3439 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003440 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003441 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003442 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003443 if (what & layer_state_t::eCornerRadiusChanged) {
3444 if (layer->setCornerRadius(s.cornerRadius))
3445 flags |= eTraversalNeeded;
3446 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003447 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3448 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 if (what & layer_state_t::eLayerStackChanged) {
3451 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3452 // We only allow setting layer stacks for top level layers,
3453 // everything else inherits layer stack from its parent.
3454 if (layer->hasParent()) {
3455 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003456 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003457 } else if (idx < 0) {
3458 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003459 "that also does not appear in the top level layer list. Something"
3460 " has gone wrong.",
3461 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003462 } else if (layer->setLayerStack(s.layerStack)) {
3463 mCurrentState.layersSortedByZ.removeAt(idx);
3464 mCurrentState.layersSortedByZ.add(layer);
3465 // we need traversal (state changed)
3466 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003467 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003468 }
3469 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003470 if (what & layer_state_t::eDeferTransaction_legacy) {
3471 if (s.barrierHandle_legacy != nullptr) {
3472 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3473 } else if (s.barrierGbp_legacy != nullptr) {
3474 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003475 if (authenticateSurfaceTextureLocked(gbp)) {
3476 const auto& otherLayer =
3477 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003478 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003479 } else {
3480 ALOGE("Attempt to defer transaction to to an"
3481 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003482 }
3483 }
chaviw8b3871a2017-11-01 17:41:01 -07003484 // We don't trigger a traversal here because if no other state is
3485 // changed, we don't want this to cause any more work
3486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (what & layer_state_t::eReparentChildren) {
3488 if (layer->reparentChildren(s.reparentHandle)) {
3489 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 }
chaviw8b3871a2017-11-01 17:41:01 -07003492 if (what & layer_state_t::eDetachChildren) {
3493 layer->detachChildren();
3494 }
3495 if (what & layer_state_t::eOverrideScalingModeChanged) {
3496 layer->setOverrideScalingMode(s.overrideScalingMode);
3497 // We don't trigger a traversal here because if no other state is
3498 // changed, we don't want this to cause any more work
3499 }
Marissa Wall61c58622018-07-18 10:12:20 -07003500 if (what & layer_state_t::eTransformChanged) {
3501 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3502 }
3503 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3504 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3505 flags |= eTraversalNeeded;
3506 }
3507 if (what & layer_state_t::eCropChanged) {
3508 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3509 }
Marissa Wall861616d2018-10-22 12:52:23 -07003510 if (what & layer_state_t::eFrameChanged) {
3511 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3512 }
Marissa Wall61c58622018-07-18 10:12:20 -07003513 if (what & layer_state_t::eAcquireFenceChanged) {
3514 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3515 }
3516 if (what & layer_state_t::eDataspaceChanged) {
3517 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3518 }
3519 if (what & layer_state_t::eHdrMetadataChanged) {
3520 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3521 }
3522 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3523 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3524 }
3525 if (what & layer_state_t::eApiChanged) {
3526 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3527 }
3528 if (what & layer_state_t::eSidebandStreamChanged) {
3529 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3530 }
Robert Carr720e5062018-07-30 17:45:14 -07003531 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003532 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003533 layer->setInputInfo(s.inputInfo);
3534 flags |= eTraversalNeeded;
3535 } else {
3536 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3537 }
Robert Carr720e5062018-07-30 17:45:14 -07003538 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003539 if (what & layer_state_t::eMetadataChanged) {
3540 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3541 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003542 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3543 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3544 flags |= eTraversalNeeded;
3545 }
3546 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003547 if (what & layer_state_t::eShadowRadiusChanged) {
3548 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3549 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003550 if (what & layer_state_t::eFrameRateSelectionPriority) {
3551 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3552 flags |= eTraversalNeeded;
3553 }
3554 }
Steven Thomas3172e202020-01-06 19:25:30 -08003555 if (what & layer_state_t::eFrameRateChanged) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003556 if (layer->setFrameRate(
3557 Layer::FrameRate(s.frameRate, Layer::FrameRateCompatibility::Default)))
3558 flags |= eTraversalNeeded;
Steven Thomas3172e202020-01-06 19:25:30 -08003559 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003560 // This has to happen after we reparent children because when we reparent to null we remove
3561 // child layers from current state and remove its relative z. If the children are reparented in
3562 // the same transaction, then we have to make sure we reparent the children first so we do not
3563 // lose its relative z order.
3564 if (what & layer_state_t::eReparent) {
3565 bool hadParent = layer->hasParent();
3566 if (layer->reparent(s.parentHandleForChild)) {
3567 if (!hadParent) {
3568 mCurrentState.layersSortedByZ.remove(layer);
3569 }
3570 flags |= eTransactionNeeded | eTraversalNeeded;
3571 }
3572 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003573 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003574 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3575 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003576 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3577 }
3578 }
Marissa Wall78b72202019-03-15 14:58:34 -07003579 bool bufferChanged = what & layer_state_t::eBufferChanged;
3580 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3581 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003582 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003583 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003584 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3585 if (success) {
3586 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3587 success = ClientCache::getInstance()
3588 .registerErasedRecipient(s.cachedBuffer,
3589 wp<ClientCache::ErasedRecipient>(this));
3590 if (!success) {
3591 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3592 }
3593 }
Marissa Wall78b72202019-03-15 14:58:34 -07003594 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003595 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003596 } else if (bufferChanged) {
3597 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003598 }
Marissa Wall78b72202019-03-15 14:58:34 -07003599 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003600 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3601 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003602 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003603 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003604 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003605 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3606 // Do not put anything that updates layer state or modifies flags after
3607 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003608 return flags;
3609}
3610
chaviw273171b2018-12-26 11:46:30 -08003611uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3612 uint32_t flags = 0;
3613 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3614 flags |= eTraversalNeeded;
3615 }
3616
chaviwa911b102019-02-14 10:18:33 -08003617 if (inputWindowCommands.syncInputWindows) {
3618 flags |= eTraversalNeeded;
3619 }
3620
Vishnu Nairec0ab382019-02-13 15:32:56 -08003621 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003622 return flags;
3623}
3624
chaviwfe94a222019-08-21 13:52:59 -07003625status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3626 sp<IBinder>* outHandle) {
3627 if (!mirrorFromHandle) {
3628 return NAME_NOT_FOUND;
3629 }
3630
3631 sp<Layer> mirrorLayer;
3632 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003633 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003634
3635 {
3636 Mutex::Autolock _l(mStateLock);
3637 mirrorFrom = fromHandle(mirrorFromHandle);
3638 if (!mirrorFrom) {
3639 return NAME_NOT_FOUND;
3640 }
3641
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003642 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3643 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003644 if (result != NO_ERROR) {
3645 return result;
3646 }
3647
3648 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3649 }
3650
3651 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3652}
3653
Marissa Wall2d814fb2019-04-09 18:52:57 +00003654status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3655 uint32_t h, PixelFormat format, uint32_t flags,
3656 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003657 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003658 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3659 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003660 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003661 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003662 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003664 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003665
Robert Carrc0df3122019-04-11 13:18:21 -07003666 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3667 "Expected only one of parentLayer or parentHandle to be non-null. "
3668 "Programmer error?");
3669
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003670 status_t result = NO_ERROR;
3671
3672 sp<Layer> layer;
3673
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003674 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003675
Evan Roskya1f1e152019-01-24 16:17:46 -08003676 bool primaryDisplayOnly = false;
3677
3678 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3679 // TODO b/64227542
3680 if (metadata.has(METADATA_WINDOW_TYPE)) {
3681 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3682 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003683 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003684 primaryDisplayOnly = true;
3685 }
3686 }
3687
Mathias Agopian3165cc22012-08-08 19:42:09 -07003688 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003689 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003690 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3691 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003692
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003694 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003695 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003696 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003697 break;
chaviw13fdc492017-06-27 12:40:18 -07003698 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003699 // check if buffer size is set for color layer.
3700 if (w > 0 || h > 0) {
3701 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3702 int(w), int(h));
3703 return BAD_VALUE;
3704 }
3705
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003706 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3707 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003708 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003709 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003710 // check if buffer size is set for container layer.
3711 if (w > 0 || h > 0) {
3712 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3713 int(w), int(h));
3714 return BAD_VALUE;
3715 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003716 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3717 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003718 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 default:
3720 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003721 break;
3722 }
3723
Dan Stoza7d89d062015-04-30 13:29:25 -07003724 if (result != NO_ERROR) {
3725 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003726 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003727
Evan Roskya1f1e152019-01-24 16:17:46 -08003728 if (primaryDisplayOnly) {
3729 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003730 }
3731
Robert Carrb89ea9d2018-12-10 13:01:14 -08003732 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003733 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3734 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003735 if (result != NO_ERROR) {
3736 return result;
3737 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003738 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003739
3740 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003741 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003742}
3743
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003744std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3745 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003746
3747 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003748 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003749
Dan Stoza436ccf32018-06-21 12:10:12 -07003750 // Grab the state lock since we're accessing mCurrentState
3751 Mutex::Autolock lock(mStateLock);
3752
Cody Northropbc755282017-03-31 12:00:08 -06003753 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003754 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003755 while (matchFound) {
3756 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003757 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003758 if (layer->getName() == uniqueName) {
3759 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003760 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003761 }
3762 });
3763 }
3764
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003765 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003766 return uniqueName;
3767}
3768
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003769status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003770 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003771 LayerMetadata metadata, PixelFormat& format,
3772 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003773 sp<IGraphicBufferProducer>* gbp,
3774 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003775 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003776 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777 case PIXEL_FORMAT_TRANSPARENT:
3778 case PIXEL_FORMAT_TRANSLUCENT:
3779 format = PIXEL_FORMAT_RGBA_8888;
3780 break;
3781 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003782 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 break;
3784 }
3785
chaviwb4c6e582019-08-16 14:35:07 -07003786 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003787 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003788 args.textureName = getNewTexture();
3789 {
3790 // Grab the SF state lock during this since it's the only safe way to access
3791 // RenderEngine when creating a BufferLayerConsumer
3792 // TODO: Check if this lock is still needed here
3793 Mutex::Autolock lock(mStateLock);
3794 layer = getFactory().createBufferQueueLayer(args);
3795 }
3796
Marissa Wallfd668622018-05-10 10:21:13 -07003797 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003798 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003799 *handle = layer->getHandle();
3800 *gbp = layer->getProducer();
3801 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003803
Marissa Wallfd668622018-05-10 10:21:13 -07003804 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003805 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806}
3807
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003808status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003809 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003810 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003811 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003812 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003813 args.displayDevice = getDefaultDisplayDevice();
3814 args.textureName = getNewTexture();
3815 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003816 if (outTransformHint) {
3817 *outTransformHint = layer->getTransformHint();
3818 }
Marissa Wall61c58622018-07-18 10:12:20 -07003819 *handle = layer->getHandle();
3820 *outLayer = layer;
3821
3822 return NO_ERROR;
3823}
3824
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003825status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003826 uint32_t h, uint32_t flags, LayerMetadata metadata,
3827 sp<IBinder>* handle, sp<Layer>* outLayer) {
3828 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003829 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003830 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003831 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003832}
3833
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003834status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003835 uint32_t w, uint32_t h, uint32_t flags,
3836 LayerMetadata metadata, sp<IBinder>* handle,
3837 sp<Layer>* outLayer) {
3838 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003839 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003840 *handle = (*outLayer)->getHandle();
3841 return NO_ERROR;
3842}
3843
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003844void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003845 mLayersPendingRemoval.add(layer);
3846 mLayersRemoved = true;
3847 setTransactionFlags(eTransactionNeeded);
3848}
3849
Robert Carr695d5282018-12-18 15:27:58 -08003850void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003851{
Robert Carr2e102c92018-10-23 12:11:15 -07003852 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003853 // If a layer has a parent, we allow it to out-live it's handle
3854 // with the idea that the parent holds a reference and will eventually
3855 // be cleaned up. However no one cleans up the top-level so we do so
3856 // here.
3857 if (layer->getParent() == nullptr) {
3858 mCurrentState.layersSortedByZ.remove(layer);
3859 }
3860 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003861
3862 auto it = mLayersByLocalBinderToken.begin();
3863 while (it != mLayersByLocalBinderToken.end()) {
3864 if (it->second == layer) {
3865 it = mLayersByLocalBinderToken.erase(it);
3866 } else {
3867 it++;
3868 }
3869 }
3870
Robert Carr695d5282018-12-18 15:27:58 -08003871 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003872}
3873
Mathias Agopianb60314a2012-04-10 22:09:54 -07003874// ---------------------------------------------------------------------------
3875
Andy McFadden13a082e2012-08-24 10:16:42 -07003876void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003877 const auto display = getDefaultDisplayDeviceLocked();
3878 if (!display) return;
3879
3880 const sp<IBinder> token = display->getDisplayToken().promote();
3881 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003882
Jesse Hall01e29052013-02-19 16:13:35 -08003883 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003884 Vector<ComposerState> state;
3885 Vector<DisplayState> displays;
3886 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003887 d.what = DisplayState::eDisplayProjectionChanged |
3888 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003889 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003890 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003891 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003892 d.frame.makeInvalid();
3893 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003894 d.width = 0;
3895 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003896 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003897 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3898 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003899
Dominik Laskowskie9774092018-12-11 10:04:24 -08003900 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003901
Dominik Laskowski83b88212018-12-11 13:34:06 -08003902 const nsecs_t vsyncPeriod = getVsyncPeriod();
3903 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003904
Brian Andersond0010582017-03-07 13:20:31 -08003905 // Use phase of 0 since phase is not known.
3906 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003907 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003908 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003909}
3910
3911void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003912 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003913 postMessageAsync(
3914 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003915}
3916
Ady Abraham27c70212019-06-11 10:52:26 -07003917void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3918 if (mHWCVsyncState != enabled) {
3919 getHwComposer().setVsyncEnabled(displayId, enabled);
3920 mHWCVsyncState = enabled;
3921 }
3922}
3923
Dominik Laskowskie9774092018-12-11 10:04:24 -08003924void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003925 if (display->isVirtual()) {
3926 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003927 return;
3928 }
3929
Dominik Laskowski075d3172018-05-24 15:50:06 -07003930 const auto displayId = display->getId();
3931 LOG_ALWAYS_FATAL_IF(!displayId);
3932
Dominik Laskowski34157762018-10-31 13:07:19 -07003933 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003934
3935 int currentMode = display->getPowerMode();
3936 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003937 return;
3938 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003940 display->setPowerMode(mode);
3941
Lloyd Pique4dccc412018-01-22 17:21:36 -08003942 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003943 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003944 }
3945
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003946 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003947 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003948 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003949 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003950 mScheduler->onScreenAcquired(mAppConnectionHandle);
3951 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003952 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003953
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003954 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003955 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003956 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003957
3958 struct sched_param param = {0};
3959 param.sched_priority = 1;
3960 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3961 ALOGW("Couldn't set SCHED_FIFO on display on");
3962 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003963 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003964 // Turn off the display
3965 struct sched_param param = {0};
3966 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3967 ALOGW("Couldn't set SCHED_OTHER on display off");
3968 }
3969
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003970 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003971 mScheduler->disableHardwareVsync(true);
3972 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003973 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003974
Ady Abraham27c70212019-06-11 10:52:26 -07003975 // Make sure HWVsync is disabled before turning off the display
3976 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3977
Dominik Laskowski075d3172018-05-24 15:50:06 -07003978 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003979 mVisibleRegionsDirty = true;
3980 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003981 } else if (mode == HWC_POWER_MODE_DOZE ||
3982 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003983 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003984 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003986 mScheduler->onScreenAcquired(mAppConnectionHandle);
3987 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003988 }
3989 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3990 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003991 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003992 mScheduler->disableHardwareVsync(true);
3993 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003994 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003995 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003996 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003997 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003998 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003999 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004000
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004001 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004002 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004003 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004004 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004005 }
4006
Dominik Laskowski34157762018-10-31 13:07:19 -07004007 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004008}
4009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004010void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004011 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004012 const auto display = getDisplayDevice(displayToken);
4013 if (!display) {
4014 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4015 displayToken.get());
4016 } else if (display->isVirtual()) {
4017 ALOGW("Attempt to set power mode %d for virtual display", mode);
4018 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004019 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004020 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004022}
4023
4024// ---------------------------------------------------------------------------
4025
Dominik Laskowskic2867142019-01-21 11:33:38 -08004026status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4027 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004028 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004029
Mathias Agopianbd115332013-04-18 16:41:04 -07004030 IPCThreadState* ipc = IPCThreadState::self();
4031 const int pid = ipc->getCallingPid();
4032 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004033
Mathias Agopianbd115332013-04-18 16:41:04 -07004034 if ((uid != AID_SHELL) &&
4035 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004036 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4037 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004039 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004040 // (this would indicate SF is stuck, but we want to be able to
4041 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004042 status_t err = mStateLock.timedLock(s2ns(1));
4043 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004044 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004045 StringAppendF(&result,
4046 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4047 "(no locks held)\n",
4048 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004049 }
4050
Dominik Laskowskic2867142019-01-21 11:33:38 -08004051 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004052 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004053 {"--dispsync"s,
4054 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004055 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004056 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4057 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4058 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4059 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4060 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4061 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004062 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004063 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4064 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065
Dominik Laskowskic2867142019-01-21 11:33:38 -08004066 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004067
Dominik Laskowski46470112019-08-02 13:13:11 -07004068 const auto it = dumpers.find(flag);
4069 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004070 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004071 } else if (!asProto) {
4072 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004073 }
4074
Mathias Agopian9795c422009-08-26 16:36:26 -07004075 if (locked) {
4076 mStateLock.unlock();
4077 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004078
Dominik Laskowski46470112019-08-02 13:13:11 -07004079 if (it == dumpers.end()) {
4080 const LayersProto layersProto = dumpProtoFromMainThread();
4081 if (asProto) {
4082 result.append(layersProto.SerializeAsString());
4083 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004084 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004085 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4086 result.append(LayerProtoParser::layerTreeToString(layerTree));
4087 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004088 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004089 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004092 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 return NO_ERROR;
4094}
4095
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004096status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4097 if (asProto && mTracing.isEnabled()) {
4098 mTracing.writeToFileAsync();
4099 }
4100
4101 return doDump(fd, DumpArgs(), asProto);
4102}
4103
Dominik Laskowskic2867142019-01-21 11:33:38 -08004104void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004105 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004106 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004107}
4108
Dominik Laskowskic2867142019-01-21 11:33:38 -08004109void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004110 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004111
Dominik Laskowskic2867142019-01-21 11:33:38 -08004112 if (args.size() > 1) {
4113 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004114 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004115 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004116 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004117 }
Robert Carr2047fae2016-11-28 14:09:09 -08004118 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004119 } else {
4120 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004121 }
4122}
4123
Dominik Laskowskic2867142019-01-21 11:33:38 -08004124void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004125 const bool clearAll = args.size() < 2;
4126 const auto name = clearAll ? String8() : String8(args[1]);
4127
Edgar Arriaga844fa672020-01-16 14:21:42 -08004128 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004129 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004130 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004131 }
Robert Carr2047fae2016-11-28 14:09:09 -08004132 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004133
Svetoslavd85084b2014-03-20 10:28:31 -07004134 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004135}
4136
Dominik Laskowskic2867142019-01-21 11:33:38 -08004137void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4138 mTimeStats->parseArgs(asProto, args, result);
4139}
4140
Jamie Gennis6547ff42013-07-16 20:12:42 -07004141// This should only be called from the main thread. Otherwise it would need
4142// the lock and should use mCurrentState rather than mDrawingState.
4143void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004144 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004145 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004146 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004147
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004148 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004149}
4150
Yiwei Zhang5434a782018-12-05 18:06:32 -08004151void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004152 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004153
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004154 if (isLayerTripleBufferingDisabled())
4155 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004156
Yiwei Zhang5434a782018-12-05 18:06:32 -08004157 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4158 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4159 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4160 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4161 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4162 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004163 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004164}
4165
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004166void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004167 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004168
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004169 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004170 result.append("\n");
4171
Ady Abraham9e16a482019-12-03 17:19:41 -08004172 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004173 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004174 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004175 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004176
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004177 HwcConfigIndexType defaultConfig;
4178 float minFps, maxFps;
4179 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004180 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004181 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004182 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004183 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004184 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4185 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004186
Ana Krulecc2870422019-01-29 19:00:58 -08004187 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004188}
4189
Yiwei Zhang5434a782018-12-05 18:06:32 -08004190void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4191 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004192 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4193 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004194 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004195 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004196 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004197 }
David Sodman4a36e932017-11-07 14:29:47 -08004198 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004199 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004200 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004201 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4202 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004203}
4204
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004205void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4206 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004207 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4208 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004209 for (const auto& segment : history) {
4210 if (!segment.usedThirdBuffer) {
4211 stats.twoBufferTime += segment.totalTime;
4212 }
4213 if (segment.occupancyAverage < 1.0f) {
4214 stats.doubleBufferedTime += segment.totalTime;
4215 } else if (segment.occupancyAverage < 2.0f) {
4216 stats.tripleBufferedTime += segment.totalTime;
4217 }
4218 ++stats.numSegments;
4219 stats.totalTime += segment.totalTime;
4220 }
4221}
4222
Yiwei Zhang5434a782018-12-05 18:06:32 -08004223void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4224 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004225
4226 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4227 const size_t count = currentLayers.size();
4228 for (size_t i=0 ; i<count ; i++) {
4229 currentLayers[i]->dumpFrameEvents(result);
4230 }
4231}
4232
Yiwei Zhang5434a782018-12-05 18:06:32 -08004233void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004234 result.append("Buffering stats:\n");
4235 result.append(" [Layer name] <Active time> <Two buffer> "
4236 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004237 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004238 typedef std::tuple<std::string, float, float, float> BufferTuple;
4239 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004240 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004241 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004242 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004243 if (stats.numSegments == 0) {
4244 continue;
4245 }
4246 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4247 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4248 stats.totalTime;
4249 float doubleBufferRatio = static_cast<float>(
4250 stats.doubleBufferedTime) / stats.totalTime;
4251 float tripleBufferRatio = static_cast<float>(
4252 stats.tripleBufferedTime) / stats.totalTime;
4253 sorted.insert({activeTime, {name, twoBufferRatio,
4254 doubleBufferRatio, tripleBufferRatio}});
4255 }
4256 for (const auto& sortedPair : sorted) {
4257 float activeTime = sortedPair.first;
4258 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004259 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4260 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004261 }
4262 result.append("\n");
4263}
4264
Yiwei Zhang5434a782018-12-05 18:06:32 -08004265void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004266 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004267 const auto displayId = display->getId();
4268 if (!displayId) {
4269 continue;
4270 }
4271 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004272 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004273 continue;
4274 }
4275
Yiwei Zhang5434a782018-12-05 18:06:32 -08004276 StringAppendF(&result,
4277 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4278 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004279 uint8_t port;
4280 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004281 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004282 result.append("no identification data\n");
4283 continue;
4284 }
4285
4286 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004287 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004288 continue;
4289 }
4290
4291 const auto edid = parseEdid(data);
4292 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004293 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004294 continue;
4295 }
4296
Yiwei Zhang5434a782018-12-05 18:06:32 -08004297 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004298 result.append(edid->displayName.data(), edid->displayName.length());
4299 result.append("\"\n");
4300 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004301}
4302
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004303void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4304 std::string& result) const {
4305 hwc2_display_t hwcDisplayId;
4306 uint8_t port;
4307 DisplayIdentificationData data;
4308
4309 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4310 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4311 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4312 }
4313}
4314
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004316 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004317 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4318 StringAppendF(&result, "DisplayColorSetting: %s\n",
4319 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004320
4321 // TODO: print out if wide-color mode is active or not
4322
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004323 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004324 const auto displayId = display->getId();
4325 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004326 continue;
4327 }
4328
Yiwei Zhang5434a782018-12-05 18:06:32 -08004329 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004330 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004331 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004333 }
4334
Lloyd Pique32cbe282018-10-19 13:09:22 -07004335 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336 StringAppendF(&result, " Current color mode: %s (%d)\n",
4337 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004338 }
4339 result.append("\n");
4340}
4341
Vishnu Nair8406fd72019-07-30 11:29:31 -07004342LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004343 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004344 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4345 layer->writeToProto(layersProto, traceFlags);
4346 }
chaviw1d044282017-09-27 12:19:28 -07004347 return layersProto;
4348}
4349
Vishnu Nair0f085c62019-08-30 08:49:12 -07004350void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4351 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4352 // it.
4353 LayerProto* rootProto = layersProto.add_layers();
4354 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4355 rootProto->set_id(offscreenRootLayerId);
4356 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004357 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004358
4359 for (Layer* offscreenLayer : mOffscreenLayers) {
4360 // Add layer as child of the fake root
4361 rootProto->add_children(offscreenLayer->sequence);
4362
4363 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004364 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004365 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004366 }
4367}
4368
Vishnu Nair8406fd72019-07-30 11:29:31 -07004369LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4370 LayersProto layersProto;
4371 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4372 return layersProto;
4373}
4374
Vishnu Nair0f085c62019-08-30 08:49:12 -07004375void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4376 result.append("Offscreen Layers:\n");
4377 postMessageSync(new LambdaMessage([&]() {
4378 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004379 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004380 layer->dumpCallingUidPid(result);
4381 });
4382 }
4383 }));
4384}
4385
Dominik Laskowskic2867142019-01-21 11:33:38 -08004386void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4387 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004388 Colorizer colorizer(colorize);
4389
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 // figure out if we're stuck somewhere
4391 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4394
4395 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004396 * Dump library configuration.
4397 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004398
4399 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004400 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004401 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004402 appendSfConfigString(result);
4403 appendUiConfigString(result);
4404 appendGuiConfigString(result);
4405 result.append("\n");
4406
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004407 result.append("\nDisplay identification data:\n");
4408 dumpDisplayIdentificationData(result);
4409
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004410 result.append("\nWide-Color information:\n");
4411 dumpWideColorInfo(result);
4412
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004413 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004414 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004415 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004416 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004417 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004418
Andy McFadden41d67d72014-04-25 16:58:34 -07004419 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004420 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004421 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004422 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004423 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004424
Dan Stozab90cf072015-03-05 11:05:59 -08004425 dumpStaticScreenStats(result);
4426 result.append("\n");
4427
Alec Mouri40189b02019-03-05 15:07:54 -08004428 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4429 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4430 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004431
Dan Stozae77c7662016-05-13 11:37:28 -07004432 dumpBufferingStats(result);
4433
Andy McFadden4803b742012-09-24 19:07:20 -07004434 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004435 * Dump the visible layer list
4436 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004437 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004438 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004439 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4440 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004441 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004442
Chia-I Wu2f884132018-09-13 15:17:58 -07004443 {
Lloyd Pique207def92019-02-28 16:09:52 -08004444 StringAppendF(&result, "Composition layers\n");
4445 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004446 auto* compositionState = layer->getCompositionState();
4447 if (!compositionState) return;
4448
4449 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4450 layer->getDebugName() ? layer->getDebugName()
4451 : "<unknown>");
4452 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004453 });
4454 }
4455
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004456 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004457 * Dump Display state
4458 */
4459
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004460 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004461 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004462 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004463 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004464 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004465 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004466 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004467
4468 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004469 * Dump CompositionEngine state
4470 */
4471
4472 mCompositionEngine->dump(result);
4473
4474 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004475 * Dump SurfaceFlinger global state
4476 */
4477
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004478 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004479 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004480 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004481
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004482 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004483
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004484 DebugEGLImageTracker::getInstance()->dump(result);
4485
Dominik Laskowski075d3172018-05-24 15:50:06 -07004486 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004487 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4488 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004489 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4490 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004491 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492 StringAppendF(&result,
4493 " transaction-flags : %08x\n"
4494 " gpu_to_cpu_unsupported : %d\n",
4495 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004497 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004498 displayId && getHwComposer().isConnected(*displayId)) {
4499 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result,
4501 " refresh-rate : %f fps\n"
4502 " x-dpi : %f\n"
4503 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004504 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4505 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004506 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004507
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004509
Dan Stozae22aec72016-08-01 13:20:59 -07004510 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004511 * Tracing state
4512 */
4513 mTracing.dump(result);
4514 result.append("\n");
4515
4516 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004517 * HWC layer minidump
4518 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004519 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004520 const auto displayId = display->getId();
4521 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004522 continue;
4523 }
4524
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004526 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004527 const sp<DisplayDevice> displayDevice = display;
4528 mCurrentState.traverseInZOrder(
4529 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004530 result.append("\n");
4531 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004532
4533 /*
4534 * Dump HWComposer state
4535 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004536 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004537 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004539 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004541 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004542
4543 /*
4544 * Dump gralloc state
4545 */
4546 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4547 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004548
4549 /*
4550 * Dump VrFlinger state if in use.
4551 */
4552 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4553 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004555 result.append("\n");
4556 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004557
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004558 result.append(mTimeStats->miniDump());
4559 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004560}
4561
Chia-I Wu28f320b2018-05-03 11:02:56 -07004562void SurfaceFlinger::updateColorMatrixLocked() {
4563 mat4 colorMatrix;
4564 if (mGlobalSaturationFactor != 1.0f) {
4565 // Rec.709 luma coefficients
4566 float3 luminance{0.213f, 0.715f, 0.072f};
4567 luminance *= 1.0f - mGlobalSaturationFactor;
4568 mat4 saturationMatrix = mat4(
4569 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4570 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4571 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4572 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4573 );
4574 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4575 } else {
4576 colorMatrix = mClientColorMatrix * mDaltonizer();
4577 }
4578
4579 if (mCurrentState.colorMatrix != colorMatrix) {
4580 mCurrentState.colorMatrix = colorMatrix;
4581 mCurrentState.colorMatrixChanged = true;
4582 setTransactionFlags(eTransactionNeeded);
4583 }
4584}
4585
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004586status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004587#pragma clang diagnostic push
4588#pragma clang diagnostic error "-Wswitch-enum"
4589 switch (static_cast<ISurfaceComposerTag>(code)) {
4590 // These methods should at minimum make sure that the client requested
4591 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004592 case BOOT_FINISHED:
4593 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004594 case CREATE_DISPLAY:
4595 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004596 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004597 case GET_ANIMATION_FRAME_STATS:
4598 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004599 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004600 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004601 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004602 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4603 case SET_AUTO_LOW_LATENCY_MODE:
4604 case GET_GAME_CONTENT_TYPE_SUPPORT:
4605 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004606 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004607 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004608 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004609 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004610 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004611 case NOTIFY_POWER_HINT:
4612 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004613 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4614 IPCThreadState* ipc = IPCThreadState::self();
4615 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4616 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004617 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004618 }
Robert Carr1db73f62016-12-21 12:58:51 -08004619 return OK;
4620 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004621 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004622 IPCThreadState* ipc = IPCThreadState::self();
4623 const int pid = ipc->getCallingPid();
4624 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004625 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4626 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004627 return PERMISSION_DENIED;
4628 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004629 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004630 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004631 // Used by apps to hook Choreographer to SurfaceFlinger.
4632 case CREATE_DISPLAY_EVENT_CONNECTION:
4633 // The following calls are currently used by clients that do not
4634 // request necessary permissions. However, they do not expose any secret
4635 // information, so it is OK to pass them.
4636 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004637 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004638 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004639 case GET_PHYSICAL_DISPLAY_IDS:
4640 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004641 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004642 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004643 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004644 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004645 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004646 case GET_DISPLAY_STATS:
4647 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4648 // Calling setTransactionState is safe, because you need to have been
4649 // granted a reference to Client* and Handle* to do anything with it.
4650 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004651 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004652 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004653 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004654 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004655 case IS_WIDE_COLOR_DISPLAY:
4656 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4657 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004658 return OK;
4659 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004660 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004661 case CAPTURE_SCREEN:
4662 case ADD_REGION_SAMPLING_LISTENER:
4663 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004664 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004665 IPCThreadState* ipc = IPCThreadState::self();
4666 const int pid = ipc->getCallingPid();
4667 const int uid = ipc->getCallingUid();
4668 if ((uid != AID_GRAPHICS) &&
4669 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4670 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4671 return PERMISSION_DENIED;
4672 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004673 return OK;
4674 }
chaviw93df2ea2019-04-30 16:45:12 -07004675 case CAPTURE_SCREEN_BY_ID: {
4676 IPCThreadState* ipc = IPCThreadState::self();
4677 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004678 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004679 return OK;
4680 }
4681 return PERMISSION_DENIED;
4682 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004684
4685 // These codes are used for the IBinder protocol to either interrogate the recipient
4686 // side of the transaction for its canonical interface descriptor or to dump its state.
4687 // We let them pass by default.
4688 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4689 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4690 code == IBinder::SYSPROPS_TRANSACTION) {
4691 return OK;
4692 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004693 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004694 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004695 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004696 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4697 return OK;
4698 }
4699 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4700 return PERMISSION_DENIED;
4701#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004702}
4703
Ana Krulec13be8ad2018-08-21 02:43:56 +00004704status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4705 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004706 status_t credentialCheck = CheckTransactCodeCredentials(code);
4707 if (credentialCheck != OK) {
4708 return credentialCheck;
4709 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004711 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4712 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004713 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004714 IPCThreadState* ipc = IPCThreadState::self();
4715 const int uid = ipc->getCallingUid();
4716 if (CC_UNLIKELY(uid != AID_SYSTEM
4717 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004718 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004719 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004720 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004721 return PERMISSION_DENIED;
4722 }
4723 int n;
4724 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004725 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004726 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004727 return NO_ERROR;
4728 case 1002: // SHOW_UPDATES
4729 n = data.readInt32();
4730 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004731 invalidateHwcGeometry();
4732 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004733 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004734 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004735 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004736 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004737 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004738 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004739 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004740 setTransactionFlags(
4741 eTransactionNeeded|
4742 eDisplayTransactionNeeded|
4743 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004744 return NO_ERROR;
4745 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004746 case 1006:{ // send empty update
4747 signalRefresh();
4748 return NO_ERROR;
4749 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004750 case 1008: // toggle use of hw composer
4751 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004752 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004753 invalidateHwcGeometry();
4754 repaintEverything();
4755 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004756 case 1009: // toggle use of transform hint
4757 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004758 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004759 invalidateHwcGeometry();
4760 repaintEverything();
4761 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004762 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004763 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004764 reply->writeInt32(0);
4765 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004766 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004767 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004768 return NO_ERROR;
4769 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004770 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004771 if (!display) {
4772 return NAME_NOT_FOUND;
4773 }
4774
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004775 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004776 return NO_ERROR;
4777 }
4778 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004779 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004780 // daltonize
4781 n = data.readInt32();
4782 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004783 case 1:
4784 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4785 break;
4786 case 2:
4787 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4788 break;
4789 case 3:
4790 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4791 break;
4792 default:
4793 mDaltonizer.setType(ColorBlindnessType::None);
4794 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004795 }
4796 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004797 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004798 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004799 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004800 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004801
4802 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004803 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004804 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004805 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004806 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004807 // apply a color matrix
4808 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004809 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004810 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004811 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004812 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004813 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004814 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004815 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004816 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004817 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004818 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004819
4820 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4821 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004822 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004823 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4824 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4825 }
4826
Chia-I Wu28f320b2018-05-03 11:02:56 -07004827 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004828 return NO_ERROR;
4829 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004830 case 1016: { // Unused.
4831 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004832 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004833 case 1017: {
4834 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004835 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004836 return NO_ERROR;
4837 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004838 case 1018: { // Modify Choreographer's phase offset
4839 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004840 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004841 return NO_ERROR;
4842 }
4843 case 1019: { // Modify SurfaceFlinger's phase offset
4844 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004845 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004846 return NO_ERROR;
4847 }
Irvel468051e2016-06-13 16:44:44 -07004848 case 1020: { // Layer updates interceptor
4849 n = data.readInt32();
4850 if (n) {
4851 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004852 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004853 }
4854 else{
4855 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004856 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004857 }
4858 return NO_ERROR;
4859 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004860 case 1021: { // Disable HWC virtual displays
4861 n = data.readInt32();
4862 mUseHwcVirtualDisplays = !n;
4863 return NO_ERROR;
4864 }
Romain Guy0147a172017-06-01 13:53:56 -07004865 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004866 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004867 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004868
Chia-I Wu28f320b2018-05-03 11:02:56 -07004869 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004870 return NO_ERROR;
4871 }
Romain Guy54f154a2017-10-24 21:40:32 +01004872 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004873 int32_t colorMode;
4874
Chia-I Wu0d711262018-05-21 15:19:35 -07004875 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004876 if (data.readInt32(&colorMode) == NO_ERROR) {
4877 mForceColorMode = static_cast<ColorMode>(colorMode);
4878 }
Romain Guy54f154a2017-10-24 21:40:32 +01004879 invalidateHwcGeometry();
4880 repaintEverything();
4881 return NO_ERROR;
4882 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004883 // Deprecate, use 1030 to check whether the device is color managed.
4884 case 1024: {
4885 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004886 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004887 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004888 n = data.readInt32();
4889 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004890 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004891 Mutex::Autolock lock(mStateLock);
4892 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004893 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004894 reply->writeInt32(NO_ERROR);
4895 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004896 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004897 bool writeFile = false;
4898 {
4899 Mutex::Autolock lock(mStateLock);
4900 mTracingEnabledChanged = true;
4901 writeFile = mTracing.disable();
4902 }
4903
4904 if (writeFile) {
4905 reply->writeInt32(mTracing.writeToFile());
4906 } else {
4907 reply->writeInt32(NO_ERROR);
4908 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004909 }
4910 return NO_ERROR;
4911 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004912 case 1026: { // Get layer tracing status
4913 reply->writeBool(mTracing.isEnabled());
4914 return NO_ERROR;
4915 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004916 // Is a DisplayColorSetting supported?
4917 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004918 const auto display = getDefaultDisplayDevice();
4919 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004920 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004921 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004922
4923 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4924 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004925 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004926 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004927 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004928 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004929 reply->writeBool(true);
4930 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004931 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004932 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004933 break;
4934 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004935 reply->writeBool(
4936 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004937 break;
4938 }
4939 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004940 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004941 // Is VrFlinger active?
4942 case 1028: {
4943 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004944 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004945 return NO_ERROR;
4946 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004947 // Set buffer size for SF tracing (value in KB)
4948 case 1029: {
4949 n = data.readInt32();
4950 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4951 ALOGW("Invalid buffer size: %d KB", n);
4952 reply->writeInt32(BAD_VALUE);
4953 return BAD_VALUE;
4954 }
4955
4956 ALOGD("Updating trace buffer to %d KB", n);
4957 mTracing.setBufferSize(n * 1024);
4958 reply->writeInt32(NO_ERROR);
4959 return NO_ERROR;
4960 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004961 // Is device color managed?
4962 case 1030: {
4963 reply->writeBool(useColorManagement);
4964 return NO_ERROR;
4965 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004966 // Override default composition data space
4967 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4968 // && adb shell stop zygote && adb shell start zygote
4969 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4970 // adb shell stop zygote && adb shell start zygote
4971 case 1031: {
4972 Mutex::Autolock _l(mStateLock);
4973 n = data.readInt32();
4974 if (n) {
4975 n = data.readInt32();
4976 if (n) {
4977 Dataspace dataspace = static_cast<Dataspace>(n);
4978 if (!validateCompositionDataspace(dataspace)) {
4979 return BAD_VALUE;
4980 }
4981 mDefaultCompositionDataspace = dataspace;
4982 }
4983 n = data.readInt32();
4984 if (n) {
4985 Dataspace dataspace = static_cast<Dataspace>(n);
4986 if (!validateCompositionDataspace(dataspace)) {
4987 return BAD_VALUE;
4988 }
4989 mWideColorGamutCompositionDataspace = dataspace;
4990 }
4991 } else {
4992 // restore composition data space.
4993 mDefaultCompositionDataspace = defaultCompositionDataspace;
4994 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4995 }
4996 return NO_ERROR;
4997 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004998 // Set trace flags
4999 case 1033: {
5000 n = data.readUint32();
5001 ALOGD("Updating trace flags to 0x%x", n);
5002 mTracing.setTraceFlags(n);
5003 reply->writeInt32(NO_ERROR);
5004 return NO_ERROR;
5005 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005006 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005007 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005008 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005009 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005010 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5011 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005012 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005013 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005014 } else {
5015 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005016 }
5017 return NO_ERROR;
5018 }
Ady Abraham34392f72019-04-10 11:29:27 -07005019 case 1035: {
5020 n = data.readInt32();
5021 mDebugDisplayConfigSetByBackdoor = false;
5022 if (n >= 0) {
5023 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005024 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005025 if (result != NO_ERROR) {
5026 return result;
5027 }
5028 mDebugDisplayConfigSetByBackdoor = true;
5029 }
5030 return NO_ERROR;
5031 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005032 }
5033 }
5034 return err;
5035}
5036
Steven Thomas6d8110b2017-08-31 18:24:21 -07005037void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005038 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005039 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005040}
5041
Ana Krulec7d1d6832018-12-27 11:10:09 -08005042void SurfaceFlinger::repaintEverythingForHWC() {
5043 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005044 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005045}
5046
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005047// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5048class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005049public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005050 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5051 ~WindowDisconnector() {
5052 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005053 }
5054
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005055private:
5056 ANativeWindow* mWindow;
5057 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005058};
5059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005060status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005061 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005062 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5063 const Rect& sourceCrop, uint32_t reqWidth,
5064 uint32_t reqHeight, bool useIdentityTransform,
5065 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005066 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005068 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005069
Dominik Laskowski718f9602019-11-09 20:01:35 -08005070 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5071 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5072 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5073 renderAreaRotation = ui::Transform::ROT_0;
5074 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005075
Chia-I Wu20261cb2018-08-23 12:55:44 -07005076 sp<DisplayDevice> display;
5077 {
5078 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005079
Chia-I Wu20261cb2018-08-23 12:55:44 -07005080 display = getDisplayDeviceLocked(displayToken);
5081 if (!display) return BAD_VALUE;
5082
Chia-I Wucb023152018-08-28 12:57:23 -07005083 // set the requested width/height to the logical display viewport size
5084 // by default
5085 if (reqWidth == 0 || reqHeight == 0) {
5086 reqWidth = uint32_t(display->getViewport().width());
5087 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005088 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005089 }
5090
Peiyong Lin0e003c92018-09-17 11:09:51 -07005091 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005092 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005093
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005094 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5095 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005096 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005097 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005098}
5099
chaviw93df2ea2019-04-30 16:45:12 -07005100static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5101 switch (colorMode) {
5102 case ColorMode::DISPLAY_P3:
5103 case ColorMode::BT2100_PQ:
5104 case ColorMode::BT2100_HLG:
5105 case ColorMode::DISPLAY_BT2020:
5106 return Dataspace::DISPLAY_P3;
5107 default:
5108 return Dataspace::V0_SRGB;
5109 }
5110}
5111
5112const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5113 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5114 if (displayToken) {
5115 return getDisplayDeviceLocked(displayToken);
5116 }
5117 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5118 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005119 return getDisplayByLayerStack(displayOrLayerStack);
5120}
5121
5122const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005123 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005124 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005125 return display;
5126 }
5127 }
5128 return nullptr;
5129}
5130
5131status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5132 sp<GraphicBuffer>* outBuffer) {
5133 sp<DisplayDevice> display;
5134 uint32_t width;
5135 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005136 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005137 {
5138 Mutex::Autolock _l(mStateLock);
5139 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5140 if (!display) {
5141 return BAD_VALUE;
5142 }
5143
5144 width = uint32_t(display->getViewport().width());
5145 height = uint32_t(display->getViewport().height());
5146
Dominik Laskowski718f9602019-11-09 20:01:35 -08005147 const auto orientation = display->getOrientation();
5148 captureOrientation = ui::Transform::toRotationFlags(orientation);
5149
5150 switch (captureOrientation) {
5151 case ui::Transform::ROT_90:
5152 captureOrientation = ui::Transform::ROT_270;
5153 break;
5154
5155 case ui::Transform::ROT_270:
5156 captureOrientation = ui::Transform::ROT_90;
5157 break;
5158
5159 case ui::Transform::ROT_INVALID:
5160 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5161 captureOrientation = ui::Transform::ROT_0;
5162 break;
5163
5164 default:
5165 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005166 }
chaviw93df2ea2019-04-30 16:45:12 -07005167 *outDataspace =
5168 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5169 }
5170
5171 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5172 false /* captureSecureLayers */);
5173
5174 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5175 std::placeholders::_1);
5176 bool ignored = false;
5177 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5178 false /* useIdentityTransform */,
5179 ignored /* outCapturedSecureLayers */);
5180}
5181
Robert Carr866455f2019-04-02 16:28:26 -07005182status_t SurfaceFlinger::captureLayers(
5183 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5184 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5185 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5186 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005187 ATRACE_CALL();
5188
5189 class LayerRenderArea : public RenderArea {
5190 public:
Robert Carr578038f2018-03-09 12:25:24 -08005191 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005192 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005193 bool childrenOnly, const Rect& displayViewport)
5194 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005195 mLayer(layer),
5196 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005197 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005198 mFlinger(flinger),
5199 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005200 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005201 Rect getBounds() const override {
5202 const Layer::State& layerState(mLayer->getDrawingState());
5203 return mLayer->getBufferSize(layerState);
5204 }
Marissa Wall61c58622018-07-18 10:12:20 -07005205 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005206 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005207 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005208 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005209 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005210 }
chaviwa76b2712017-09-20 12:02:26 -07005211 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005212 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005213 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005214 Rect getSourceCrop() const override {
5215 if (mCrop.isEmpty()) {
5216 return getBounds();
5217 } else {
5218 return mCrop;
5219 }
5220 }
Robert Carr578038f2018-03-09 12:25:24 -08005221 class ReparentForDrawing {
5222 public:
5223 const sp<Layer>& oldParent;
5224 const sp<Layer>& newParent;
5225
Vishnu Nair4351ad52019-02-11 14:13:02 -08005226 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5227 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005228 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005229 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005230 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5231 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005232 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005233 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005234 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005235 };
5236
5237 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005238 const Rect sourceCrop = getSourceCrop();
5239 // no need to check rotation because there is none
5240 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5241 sourceCrop.height() != getReqHeight();
5242
Robert Carr578038f2018-03-09 12:25:24 -08005243 if (!mChildrenOnly) {
5244 mTransform = mLayer->getTransform().inverse();
5245 drawLayers();
5246 } else {
5247 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005248 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5249 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005250 // In the "childrenOnly" case we reparent the children to a screenshot
5251 // layer which has no properties set and which does not draw.
5252 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005253 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5254 "Screenshot Parent"s, w, h, 0,
5255 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005256
Vishnu Nair4351ad52019-02-11 14:13:02 -08005257 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005258 drawLayers();
5259 }
5260 }
chaviwa76b2712017-09-20 12:02:26 -07005261
chaviwa76b2712017-09-20 12:02:26 -07005262 private:
chaviw7206d492017-11-10 16:16:12 -08005263 const sp<Layer> mLayer;
5264 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005265
Peiyong Linefefaac2018-08-17 12:27:51 -07005266 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005267 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005268
5269 SurfaceFlinger* mFlinger;
5270 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005271 };
5272
Robert Carrc0df3122019-04-11 13:18:21 -07005273 int reqWidth = 0;
5274 int reqHeight = 0;
5275 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005276 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005277 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005278 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005279 {
5280 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005281
Robert Carrc0df3122019-04-11 13:18:21 -07005282 parent = fromHandle(layerHandleBinder);
5283 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5284 ALOGE("captureLayers called with an invalid or removed parent");
5285 return NAME_NOT_FOUND;
5286 }
5287
5288 const int uid = IPCThreadState::self()->getCallingUid();
5289 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5290 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5291 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5292 return PERMISSION_DENIED;
5293 }
5294
Vishnu Nairefc42e22019-12-03 17:36:12 -08005295 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005296 if (sourceCrop.width() <= 0) {
5297 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005298 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005299 }
5300
5301 if (sourceCrop.height() <= 0) {
5302 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005303 crop.bottom = parentSourceBounds.getHeight();
5304 }
5305
5306 if (crop.isEmpty() || frameScale <= 0.0f) {
5307 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5308 // crop was not specified, or an invalid frame scale was provided.
5309 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005310 }
5311 reqWidth = crop.width() * frameScale;
5312 reqHeight = crop.height() * frameScale;
5313
5314 for (const auto& handle : excludeHandles) {
5315 sp<Layer> excludeLayer = fromHandle(handle);
5316 if (excludeLayer != nullptr) {
5317 excludeLayers.emplace(excludeLayer);
5318 } else {
5319 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5320 return NAME_NOT_FOUND;
5321 }
5322 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005323
5324 auto display = getDisplayByLayerStack(parent->getLayerStack());
5325 if (!display) {
5326 return BAD_VALUE;
5327 }
5328
5329 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005330 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005331
Chia-I Wu20261cb2018-08-23 12:55:44 -07005332 // really small crop or frameScale
5333 if (reqWidth <= 0) {
5334 reqWidth = 1;
5335 }
5336 if (reqHeight <= 0) {
5337 reqHeight = 1;
5338 }
5339
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005340 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5341 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005342 auto traverseLayers = [parent, childrenOnly,
5343 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005344 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5345 if (!layer->isVisible()) {
5346 return;
Robert Carr578038f2018-03-09 12:25:24 -08005347 } else if (childrenOnly && layer == parent.get()) {
5348 return;
chaviwa76b2712017-09-20 12:02:26 -07005349 }
Robert Carr866455f2019-04-02 16:28:26 -07005350
5351 sp<Layer> p = layer;
5352 while (p != nullptr) {
5353 if (excludeLayers.count(p) != 0) {
5354 return;
5355 }
5356 p = p->getParent();
5357 }
5358
chaviwa76b2712017-09-20 12:02:26 -07005359 visitor(layer);
5360 });
5361 };
Robert Carr108b2c72019-04-02 16:32:58 -07005362
5363 bool outCapturedSecureLayers = false;
5364 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5365 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005366}
5367
5368status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5369 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005370 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005371 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005372 bool useIdentityTransform,
5373 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005374 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005375
Peiyong Lin0e003c92018-09-17 11:09:51 -07005376 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005377 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5378 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005379 *outBuffer =
5380 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5381 static_cast<android_pixel_format>(reqPixelFormat), 1,
5382 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005383
Robert Carr108b2c72019-04-02 16:32:58 -07005384 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5385 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005386}
5387
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005388status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5389 TraverseLayersFunction traverseLayers,
5390 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005391 bool useIdentityTransform,
5392 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005393 // This mutex protects syncFd and captureResult for communication of the return values from the
5394 // main thread back to this Binder thread
5395 std::mutex captureMutex;
5396 std::condition_variable captureCondition;
5397 std::unique_lock<std::mutex> captureLock(captureMutex);
5398 int syncFd = -1;
5399 std::optional<status_t> captureResult;
5400
Robert Carr03480e22018-01-04 16:02:06 -08005401 const int uid = IPCThreadState::self()->getCallingUid();
5402 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5403
Dominik Laskowski8c001672018-05-30 16:52:06 -07005404 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405 // If there is a refresh pending, bug out early and tell the binder thread to try again
5406 // after the refresh.
5407 if (mRefreshPending) {
5408 ATRACE_NAME("Skipping screenshot for now");
5409 std::unique_lock<std::mutex> captureLock(captureMutex);
5410 captureResult = std::make_optional<status_t>(EAGAIN);
5411 captureCondition.notify_one();
5412 return;
5413 }
5414
5415 status_t result = NO_ERROR;
5416 int fd = -1;
5417 {
5418 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005419 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005420 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005421 useIdentityTransform, forSystem, &fd,
5422 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005423 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 }
5425
5426 {
5427 std::unique_lock<std::mutex> captureLock(captureMutex);
5428 syncFd = fd;
5429 captureResult = std::make_optional<status_t>(result);
5430 captureCondition.notify_one();
5431 }
5432 });
5433
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005434 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005435 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005436 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005437 while (*captureResult == EAGAIN) {
5438 captureResult.reset();
5439 result = postMessageAsync(message);
5440 if (result != NO_ERROR) {
5441 return result;
5442 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005443 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005444 }
5445 result = *captureResult;
5446 }
5447
5448 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005449 sync_wait(syncFd, -1);
5450 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005451 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005452
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005453 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005454}
5455
chaviwa76b2712017-09-20 12:02:26 -07005456void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005457 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005458 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5459 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005460 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005461
chaviwa76b2712017-09-20 12:02:26 -07005462 const auto reqWidth = renderArea.getReqWidth();
5463 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005464 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005465 const auto transform = renderArea.getTransform();
5466 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005467 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005468
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005469 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005470 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005471
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005472 // assume that bounds are never offset, and that they are the same as the
5473 // buffer bounds.
5474 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005475 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005476 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005477
5478 // Now take into account the rotation flag. We append a transform that
5479 // rotates the layer stack about the origin, then translate by buffer
5480 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005481 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005482 int displacementX = 0;
5483 int displacementY = 0;
5484 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5485 switch (rotation) {
5486 case ui::Transform::ROT_90:
5487 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005488 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005489 break;
5490 case ui::Transform::ROT_180:
5491 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005492 displacementY = renderArea.getBounds().getWidth();
5493 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005494 break;
5495 case ui::Transform::ROT_270:
5496 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005497 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005498 break;
5499 default:
5500 break;
5501 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005502
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005503 // We need to transform the clipping window into the right spot.
5504 // First, rotate the clipping rectangle by the rotation hint to get the
5505 // right orientation
5506 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5507 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5508 const vec4 rotClipTL = rotMatrix * clipTL;
5509 const vec4 rotClipBR = rotMatrix * clipBR;
5510 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5511 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5512 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5513 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5514
5515 // Now reposition the clipping rectangle with the displacement vector
5516 // computed above.
5517 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005518 clientCompositionDisplay.clip =
5519 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5520 newClipRight + displacementX, newClipBottom + displacementY);
5521
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005522 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005523 clientCompositionDisplay.globalTransform =
5524 clipTransform * clientCompositionDisplay.globalTransform;
5525
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005526 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5527 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528
chaviw50da5042018-04-09 13:49:37 -07005529 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005530
Vishnu Nair9b079a22020-01-21 14:36:08 -08005531 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005532 fillLayer.source.buffer.buffer = nullptr;
5533 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5534 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5535 fillLayer.alpha = half(alpha);
5536 clientCompositionLayers.push_back(fillLayer);
5537
5538 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005539 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005540 const bool supportProtectedContent = false;
5541 Region clip(renderArea.getBounds());
5542 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5543 clip,
5544 useIdentityTransform,
5545 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5546 renderArea.isSecure(),
5547 supportProtectedContent,
5548 clearRegion,
5549 };
5550 auto result = layer->prepareClientComposition(targetSettings);
5551 if (result) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08005552 std::optional<compositionengine::LayerFE::LayerSettings> shadowLayer =
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005553 layer->prepareShadowClientComposition(*result, displayViewport,
5554 clientCompositionDisplay.outputDataspace);
5555 if (shadowLayer) {
5556 clientCompositionLayers.push_back(*shadowLayer);
5557 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005558 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005559 }
chaviwa76b2712017-09-20 12:02:26 -07005560 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005561
Vishnu Nair9b079a22020-01-21 14:36:08 -08005562 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5563 clientCompositionLayers.reserve(clientCompositionLayers.size());
5564 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5565 std::back_inserter(clientCompositionLayerPointers),
5566 [](compositionengine::LayerFE::LayerSettings& settings)
5567 -> renderengine::LayerSettings* { return &settings; });
5568
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005569 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005570 // Use an empty fence for the buffer fence, since we just created the buffer so
5571 // there is no need for synchronization with the GPU.
5572 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005573 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005574 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005575 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005576 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005577
5578 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005579}
5580
chaviwa76b2712017-09-20 12:02:26 -07005581status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5582 TraverseLayersFunction traverseLayers,
5583 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005584 bool useIdentityTransform, bool forSystem,
5585 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005586 ATRACE_CALL();
5587
chaviwa76b2712017-09-20 12:02:26 -07005588 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005589 outCapturedSecureLayers =
5590 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005591 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005592
Robert Carr03480e22018-01-04 16:02:06 -08005593 // We allow the system server to take screenshots of secure layers for
5594 // use in situations like the Screen-rotation animation and place
5595 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005596 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005597 ALOGW("FB is protected: PERMISSION_DENIED");
5598 return PERMISSION_DENIED;
5599 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005600 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005601 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005602}
5603
chaviw95ef3c42019-02-14 10:55:09 -08005604void SurfaceFlinger::setInputWindowsFinished() {
5605 Mutex::Autolock _l(mStateLock);
5606
5607 mPendingSyncInputWindows = false;
5608 mTransactionCV.broadcast();
5609}
chaviw5f21a5e2019-02-14 10:00:34 -08005610
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005611// ---------------------------------------------------------------------------
5612
Edgar Arriaga844fa672020-01-16 14:21:42 -08005613void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5614 layersSortedByZ.traverse(visitor);
5615}
5616
Dan Stoza412903f2017-04-27 13:42:17 -07005617void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5618 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005619}
5620
Dan Stoza412903f2017-04-27 13:42:17 -07005621void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5622 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005623}
5624
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005625void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005626 const LayerVector::Visitor& visitor) {
5627 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005628 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005629 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005630 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005631 continue;
5632 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005633 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005634 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005635 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005636 return;
5637 }
chaviwa76b2712017-09-20 12:02:26 -07005638 if (!layer->isVisible()) {
5639 return;
5640 }
5641 visitor(layer);
5642 });
5643 }
5644}
5645
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005646status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5647 HwcConfigIndexType defaultConfig,
5648 float minRefreshRate,
5649 float maxRefreshRate) {
5650 Mutex::Autolock lock(mStateLock);
5651
Dominik Laskowski22488f62019-03-28 09:53:04 -07005652 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005653 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5654 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5655 // it should go thru setDesiredActiveConfig, similar to primary display.
5656 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5657 const auto displayId = display->getId();
5658 LOG_ALWAYS_FATAL_IF(!displayId);
5659
5660 HWC2::VsyncPeriodChangeConstraints constraints;
5661 constraints.desiredTimeNanos = systemTime();
5662 constraints.seamlessRequired = false;
5663
5664 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005665 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5666 constraints, &timeline) < 0) {
5667 return BAD_VALUE;
5668 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005669 if (timeline.refreshRequired) {
5670 repaintEverythingForHWC();
5671 }
5672
Ady Abrahamdfa37362020-01-21 18:02:39 -08005673 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005674 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005675 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5676 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005677 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005678 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005679 }
5680
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005681 if (mDebugDisplayConfigSetByBackdoor) {
5682 // ignore this request as config is overridden by backdoor
5683 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005684 }
5685
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005686 bool policyChanged;
5687 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5688 &policyChanged) < 0) {
5689 return BAD_VALUE;
5690 }
5691 if (!policyChanged) {
5692 return NO_ERROR;
5693 }
5694
5695 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5696 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005697
5698 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5699 // that listeners that care about a change in allowed configs can get the notification.
5700 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005701 const nsecs_t vsyncPeriod =
5702 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005703 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005704 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005705
Ana Krulec3f6a2062020-01-23 15:48:01 -08005706 auto configId = mScheduler->getPreferredConfigId();
5707 auto preferredRefreshRate = configId
5708 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5709 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5710 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5711 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5712 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5713
5714 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5715 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5716 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005717 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005718 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005719 }
5720
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005721 return NO_ERROR;
5722}
5723
Ana Krulec0782b882019-10-15 17:34:54 -07005724status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005725 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005726 float maxRefreshRate) {
5727 ATRACE_CALL();
5728
5729 if (!displayToken) {
5730 return BAD_VALUE;
5731 }
5732
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005733 status_t result = NO_ERROR;
5734
Ana Krulec234bb162019-11-10 22:55:55 +01005735 postMessageSync(new LambdaMessage([&]() {
5736 const auto display = getDisplayDeviceLocked(displayToken);
5737 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005738 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005739 ALOGE("Attempt to set desired display configs for invalid display token %p",
5740 displayToken.get());
5741 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005742 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005743 ALOGW("Attempt to set desired display configs for virtual display");
5744 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005745 result =
5746 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5747 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005748 }
5749 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005750
5751 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005752}
5753
5754status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005755 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005756 float* outMinRefreshRate,
5757 float* outMaxRefreshRate) {
5758 ATRACE_CALL();
5759
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005760 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005761 return BAD_VALUE;
5762 }
5763
5764 Mutex::Autolock lock(mStateLock);
5765 const auto display = getDisplayDeviceLocked(displayToken);
5766 if (!display) {
5767 return NAME_NOT_FOUND;
5768 }
5769
5770 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005771 HwcConfigIndexType defaultConfig;
5772 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5773 *outDefaultConfig = defaultConfig.value();
5774 return NO_ERROR;
5775 } else if (display->isVirtual()) {
5776 return BAD_VALUE;
5777 } else {
5778 const auto displayId = display->getId();
5779 if (!displayId) {
5780 return BAD_VALUE;
5781 }
5782 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5783 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5784 *outMinRefreshRate = 1e9f / vsyncPeriod;
5785 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5786 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005787 }
Ana Krulec0782b882019-10-15 17:34:54 -07005788}
5789
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005790void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005791 mFlinger->setInputWindowsFinished();
5792}
5793
Robert Carrc0df3122019-04-11 13:18:21 -07005794sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005795 BBinder* b = nullptr;
5796 if (handle) {
5797 b = handle->localBinder();
5798 }
Robert Carrc0df3122019-04-11 13:18:21 -07005799 if (b == nullptr) {
5800 return nullptr;
5801 }
5802 auto it = mLayersByLocalBinderToken.find(b);
5803 if (it != mLayersByLocalBinderToken.end()) {
5804 return it->second.promote();
5805 }
5806 return nullptr;
5807}
5808
Dominik Laskowski75848362019-11-11 17:57:20 -08005809void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005810 mNumLayers++;
5811 mScheduler->registerLayer(layer);
5812}
5813
5814void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5815 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005816 removeFromOffscreenLayers(layer);
5817}
5818
5819// WARNING: ONLY CALL THIS FROM LAYER DTOR
5820// Here we add children in the current state to offscreen layers and remove the
5821// layer itself from the offscreen layer list. Since
5822// this is the dtor, it is safe to access the current state. This keeps us
5823// from dangling children layers such that they are not reachable from the
5824// Drawing state nor the offscreen layer list
5825// See b/141111965
5826void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5827 for (auto& child : layer->getCurrentChildren()) {
5828 mOffscreenLayers.emplace(child.get());
5829 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005830 mOffscreenLayers.erase(layer);
5831}
5832
Alec Mouri4545a8a2019-08-08 20:05:32 -07005833void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5834 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5835}
5836
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005837status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5838 float lightPosY, float lightPosZ,
5839 float lightRadius) {
5840 Mutex::Autolock _l(mStateLock);
5841 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5842 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5843 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5844 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5845 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5846
5847 // these values are overridden when calculating the shadow settings for a layer.
5848 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5849 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005850 return NO_ERROR;
5851}
5852
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005853} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005854
Mathias Agopian3f844832013-08-07 21:24:32 -07005855#if defined(__gl_h_)
5856#error "don't include gl/gl.h in this file"
5857#endif
5858
5859#if defined(__gl2_h_)
5860#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005861#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005862
5863// TODO(b/129481165): remove the #pragma below and fix conversion issues
5864#pragma clang diagnostic pop // ignored "-Wconversion"