blob: a894005c1da05d9eca6d764e9f6dc1223dd1f4c1 [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 Piquecc01a452018-12-04 17:24:00 -080048#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070049#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070050#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080051#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070053#include <gui/DebugEGLImageTracker.h>
54
Andy McFadden4803b742012-09-24 19:07:20 -070055#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070056#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080057#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080058#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080059#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070061#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070062#include <ui/ColorSpace.h>
63#include <ui/DebugUtils.h>
64#include <ui/DisplayInfo.h>
65#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070066#include <ui/GraphicBufferAllocator.h>
67#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070068#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/String16.h>
71#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070072#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080073#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070074#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Mathias Agopian921e6ac2012-07-23 23:11:29 -070076#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070077#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Robert Carr578038f2018-03-09 12:25:24 -080079#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070080#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070081#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020082#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020084#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080086#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070088#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080089#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070090#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070091#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070092#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095
Steven Thomasb02664d2017-07-26 18:48:28 -070096#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070097#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070098#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070099#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700100#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700101#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700102#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700103#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700105#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106#include "Scheduler/EventControlThread.h"
107#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700108#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700109#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700110#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800111#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700112
Mathias Agopianff2ed702013-09-01 21:36:12 -0700113#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700114
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700115#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800116#include "android-base/stringprintf.h"
117
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800119#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
120#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700121#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900122#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123
chaviw1d044282017-09-27 12:19:28 -0700124#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900125#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Peiyong Lin9d846a52018-11-05 13:18:20 -0800185// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
186bool validateCompositionDataspace(Dataspace dataspace) {
187 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
188}
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190} // namespace anonymous
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192// ---------------------------------------------------------------------------
193
Mathias Agopian99b49842011-06-27 16:05:52 -0700194const String16 sHardwareTest("android.permission.HARDWARE_TEST");
195const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
196const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
197const String16 sDump("android.permission.DUMP");
198
199// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700200int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700201bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800202uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800203bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800204bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800205int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600206bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800207ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700208bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700209bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700210Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
211ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
212Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
213ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700214
Kalle Raitaa099a242017-01-11 11:17:29 -0800215std::string getHwcServiceName() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.hwc_service_name", value, "default");
218 ALOGI("Using HWComposer service: '%s'", value);
219 return std::string(value);
220}
221
222bool useTrebleTestingOverride() {
223 char value[PROPERTY_VALUE_MAX] = {};
224 property_get("debug.sf.treble_testing_override", value, "false");
225 ALOGI("Treble testing override: '%s'", value);
226 return std::string(value) == "true";
227}
228
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
230 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800231 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800233 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700234 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800235 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700236 return std::string("Enhanced");
237 default:
238 return std::string("Unknown ") +
239 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800241}
242
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700243SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800244
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700245SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
246 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700247 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700248 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700249 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700250 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700251 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700252 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800256
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900257 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900259 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700260
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900261 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700262
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900263 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264
Steven Thomas050b2c82017-03-06 11:45:16 -0800265 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900266 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600273
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 mDefaultCompositionDataspace =
275 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700276 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
277 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 defaultCompositionDataspace = mDefaultCompositionDataspace;
279 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
280 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
281 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
282 wideColorGamutCompositionPixelFormat =
283 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700284
Yichi Chenda901bf2019-06-28 14:58:27 +0800285 mColorSpaceAgnosticDataspace =
286 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800289
Dominik Laskowski718f9602019-11-09 20:01:35 -0800290 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
291 switch (primary_display_orientation(Values::ORIENTATION_0)) {
292 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800293 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800294 case Values::ORIENTATION_90:
295 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800296 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800297 case Values::ORIENTATION_180:
298 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800299 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800300 case Values::ORIENTATION_270:
301 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800302 break;
303 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800304 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800305
Sundong Ahn85131bd2019-02-18 15:51:53 +0900306 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800307
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 // debugging stuff...
309 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700310
Mathias Agopianb4b17302013-03-20 18:36:41 -0700311 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700312 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314 property_get("debug.sf.showupdates", value, "0");
315 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700316
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700317 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000318
319 // DDMS debugging deprecated (b/120782499)
320 property_get("debug.sf.ddms", value, "0");
321 int debugDdms = atoi(value);
322 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700323
324 property_get("debug.sf.disable_backpressure", value, "0");
325 mPropagateBackpressure = !atoi(value);
326 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700327
Ady Abrahamadb9a992019-09-19 21:21:55 +0000328 property_get("debug.sf.enable_gl_backpressure", value, "0");
329 mPropagateBackpressureClientComposition = atoi(value);
330 ALOGI_IF(mPropagateBackpressureClientComposition,
331 "Enabling backpressure propagation for Client Composition");
332
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800333 property_get("debug.sf.enable_hwc_vds", value, "0");
334 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800335 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800336
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800337 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800338 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800339 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700340
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800341 property_get("ro.surface_flinger.supports_background_blur", value, "0");
342 bool supportsBlurs = atoi(value);
343 property_get("debug.sf.disableBlurs", value, "0");
344 bool disableBlurs = atoi(value);
345 mEnableBlurs = supportsBlurs && !disableBlurs;
346 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
347 disableBlurs);
348
Yiwei Zhang243b3782018-05-15 17:40:04 -0700349 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700350 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
351 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
352
Dan Stozaec460082018-12-17 15:35:09 -0800353 property_get("debug.sf.luma_sampling", value, "1");
354 mLumaSampling = atoi(value);
355
Vishnu Nair9b079a22020-01-21 14:36:08 -0800356 property_get("debug.sf.disable_client_composition_cache", value, "1");
357 mDisableClientCompositionCache = atoi(value);
358
Romain Guy11d63f42017-07-20 12:47:14 -0700359 // We should be reading 'persist.sys.sf.color_saturation' here
360 // but since /data may be encrypted, we need to wait until after vold
361 // comes online to attempt to read the property. The property is
362 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800363
364 if (useTrebleTestingOverride()) {
365 // Without the override SurfaceFlinger cannot connect to HIDL
366 // services that are not listed in the manifests. Considered
367 // deriving the setting from the set service name, but it
368 // would be brittle if the name that's not 'default' is used
369 // for production purposes later on.
370 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
371 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372}
373
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374void SurfaceFlinger::onFirstRef()
375{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800376 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800377}
378
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700379SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380
Dan Stozac7014012014-02-14 15:03:43 -0800381void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382{
383 // the window manager died on us. prepare its eulogy.
384
Andy McFadden13a082e2012-08-24 10:16:42 -0700385 // restore initial conditions (default device unblank, etc)
386 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800387
388 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700389 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390}
391
Robert Carr1db73f62016-12-21 12:58:51 -0800392static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700393 status_t err = client->initCheck();
394 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800395 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 }
Robert Carr1db73f62016-12-21 12:58:51 -0800397 return nullptr;
398}
399
400sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
401 return initClient(new Client(this));
402}
403
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700404sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
405 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406{
407 class DisplayToken : public BBinder {
408 sp<SurfaceFlinger> flinger;
409 virtual ~DisplayToken() {
410 // no more references, this display must be terminated
411 Mutex::Autolock _l(flinger->mStateLock);
412 flinger->mCurrentState.displays.removeItem(this);
413 flinger->setTransactionFlags(eDisplayTransactionNeeded);
414 }
415 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700416 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417 : flinger(flinger) {
418 }
419 };
420
421 sp<BBinder> token = new DisplayToken(this);
422
423 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700424 // Display ID is assigned when virtual display is allocated by HWC.
425 DisplayDeviceState state;
426 state.isSecure = secure;
427 state.displayName = displayName;
428 mCurrentState.displays.add(token, state);
429 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700430 return token;
431}
432
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700433void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 Mutex::Autolock _l(mStateLock);
435
Dominik Laskowski075d3172018-05-24 15:50:06 -0700436 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
437 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700438 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700439 return;
440 }
441
Dominik Laskowski075d3172018-05-24 15:50:06 -0700442 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
443 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700444 ALOGE("destroyDisplay called for non-virtual display");
445 return;
446 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 mInterceptor->saveDisplayDeletion(state.sequenceId);
448 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700449 setTransactionFlags(eDisplayTransactionNeeded);
450}
451
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800452std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
453 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455 const auto internalDisplayId = getInternalDisplayIdLocked();
456 if (!internalDisplayId) {
457 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 }
459
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800460 std::vector<PhysicalDisplayId> displayIds;
461 displayIds.reserve(mPhysicalDisplayTokens.size());
462 displayIds.push_back(internalDisplayId->value);
463
464 for (const auto& [id, token] : mPhysicalDisplayTokens) {
465 if (id != *internalDisplayId) {
466 displayIds.push_back(id.value);
467 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800470 return displayIds;
471}
472
473sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
474 Mutex::Autolock lock(mStateLock);
475 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476}
477
Ady Abraham37965d42018-11-01 13:43:32 -0700478status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
479 if (!outGetColorManagement) {
480 return BAD_VALUE;
481 }
482 *outGetColorManagement = useColorManagement;
483 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700484}
485
Lloyd Pique441d5042018-10-18 16:49:51 -0700486HWComposer& SurfaceFlinger::getHwComposer() const {
487 return mCompositionEngine->getHwComposer();
488}
489
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700490renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
491 return mCompositionEngine->getRenderEngine();
492}
493
Lloyd Pique70d91362018-10-18 16:02:55 -0700494compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
495 return *mCompositionEngine.get();
496}
497
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498void SurfaceFlinger::bootFinished()
499{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700500 if (mStartPropertySetThread->join() != NO_ERROR) {
501 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800502 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503 const nsecs_t now = systemTime();
504 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000505 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700506
Mikael Pessa90092f42019-08-26 17:22:04 -0700507 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000508 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700509
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700510 // wait patiently for the window manager death
511 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700512 mWindowManager = defaultServiceManager()->getService(name);
513 if (mWindowManager != 0) {
514 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515 }
Robert Carr720e5062018-07-30 17:45:14 -0700516 sp<IBinder> input(defaultServiceManager()->getService(
517 String16("inputflinger")));
518 if (input == nullptr) {
519 ALOGE("Failed to link to input service");
520 } else {
521 mInputFlinger = interface_cast<IInputFlinger>(input);
522 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
Steven Thomas050b2c82017-03-06 11:45:16 -0800524 if (mVrFlinger) {
525 mVrFlinger->OnBootFinished();
526 }
527
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700529 // formerly we would just kill the process, but we now ask it to exit so it
530 // can choose where to stop the animation.
531 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700532
533 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
534 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
535 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700536
Ana Krulecbd6654b2019-02-15 15:18:15 -0800537 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800538 readPersistentProperties();
539 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800540
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700541 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
542 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800543 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
544 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800545 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800546 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800547}
548
Dan Stoza436ccf32018-06-21 12:10:12 -0700549uint32_t SurfaceFlinger::getNewTexture() {
550 {
551 std::lock_guard lock(mTexturePoolMutex);
552 if (!mTexturePool.empty()) {
553 uint32_t name = mTexturePool.back();
554 mTexturePool.pop_back();
555 ATRACE_INT("TexturePoolSize", mTexturePool.size());
556 return name;
557 }
558
559 // The pool was too small, so increase it for the future
560 ++mTexturePoolSize;
561 }
562
563 // The pool was empty, so we need to get a new texture name directly using a
564 // blocking call to the main thread
565 uint32_t name = 0;
566 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
567 return name;
568}
569
Mathias Agopian3f844832013-08-07 21:24:32 -0700570void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700571 std::lock_guard lock(mTexturePoolMutex);
572 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
573 // to actually delete this or not based on mTexturePoolSize
574 mTexturePool.push_back(texture);
575 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700576}
577
Wei Wangf9b05ee2017-07-19 20:59:39 -0700578// Do not call property_set on main thread which will be blocked by init
579// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700580void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700581 ALOGI( "SurfaceFlinger's main thread ready to run. "
582 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700583 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800584
Steven Thomasb02664d2017-07-26 18:48:28 -0700585 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700586 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800587 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700588 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
589 renderengine::RenderEngineCreationArgs::Builder()
590 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
591 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
592 .setUseColorManagerment(useColorManagement)
593 .setEnableProtectedContext(enable_protected_contents(false))
594 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800595 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700596 .setContextPriority(useContextPriority
597 ? renderengine::RenderEngine::ContextPriority::HIGH
598 : renderengine::RenderEngine::ContextPriority::MEDIUM)
599 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800600 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700601
602 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
603 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700604 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
605 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800606 // Process any initial hotplug and resulting display changes.
607 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700608 const auto display = getDefaultDisplayDeviceLocked();
609 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700610 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700611 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800612
Steven Thomas050b2c82017-03-06 11:45:16 -0800613 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700614 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700615 // This callback is called from the vr flinger dispatch thread. We
616 // need to call signalTransaction(), which requires holding
617 // mStateLock when we're not on the main thread. Acquiring
618 // mStateLock from the vr flinger dispatch thread might trigger a
619 // deadlock in surface flinger (see b/66916578), so post a message
620 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700621 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700622 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
623 mVrFlingerRequestsDisplay = requestDisplay;
624 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700625 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700627 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
628 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700629 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700630 .value_or(0),
631 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800632 if (!mVrFlinger) {
633 ALOGE("Failed to start vrflinger");
634 }
635 }
636
Mathias Agopian92a979a2012-08-02 18:32:23 -0700637 // initialize our drawing state
638 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700639
Andy McFadden13a082e2012-08-24 10:16:42 -0700640 // set initial conditions (e.g. unblank default device)
641 initializeDisplays();
642
Steven Thomas137d4bc2019-07-25 16:55:14 -0700643 char primeShaderCache[PROPERTY_VALUE_MAX];
644 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
645 if (atoi(primeShaderCache)) {
646 getRenderEngine().primeCache();
647 }
Dan Stoza4e637772016-07-28 13:31:51 -0700648
Wei Wangf9b05ee2017-07-19 20:59:39 -0700649 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700650
651 const bool presentFenceReliable =
652 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
653 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700654
655 if (mStartPropertySetThread->Start() != NO_ERROR) {
656 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800658
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700660}
661
Romain Guy11d63f42017-07-20 12:47:14 -0700662void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700663 Mutex::Autolock _l(mStateLock);
664
Romain Guy11d63f42017-07-20 12:47:14 -0700665 char value[PROPERTY_VALUE_MAX];
666
667 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800668 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700669 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800670 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100671
672 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700673 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800674
675 property_get("persist.sys.sf.color_mode", value, "0");
676 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700677}
678
Mathias Agopiana67e4182012-06-19 17:26:12 -0700679void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Start boot animation service by setting a property mailbox
681 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 if (mStartPropertySetThread->join() != NO_ERROR) {
685 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800686 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687}
688
Mathias Agopian875d8e12013-06-07 15:35:48 -0700689size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700690 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700691}
692
Mathias Agopian875d8e12013-06-07 15:35:48 -0700693size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700694 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700695}
696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800698
Jamie Gennis582270d2011-08-17 18:19:00 -0700699bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800700 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800701 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800702 return authenticateSurfaceTextureLocked(bufferProducer);
703}
704
705bool SurfaceFlinger::authenticateSurfaceTextureLocked(
706 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800707 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800708 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800709}
710
Brian Anderson6b376712017-04-04 10:51:39 -0700711status_t SurfaceFlinger::getSupportedFrameTimestamps(
712 std::vector<FrameEvent>* outSupported) const {
713 *outSupported = {
714 FrameEvent::REQUESTED_PRESENT,
715 FrameEvent::ACQUIRE,
716 FrameEvent::LATCH,
717 FrameEvent::FIRST_REFRESH_START,
718 FrameEvent::LAST_REFRESH_START,
719 FrameEvent::GPU_COMPOSITION_DONE,
720 FrameEvent::DEQUEUE_READY,
721 FrameEvent::RELEASE,
722 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700723 ConditionalLock _l(mStateLock,
724 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700725 if (!getHwComposer().hasCapability(
726 HWC2::Capability::PresentFenceIsNotReliable)) {
727 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
728 }
729 return NO_ERROR;
730}
731
Dominik Laskowski22488f62019-03-28 09:53:04 -0700732status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
733 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700734 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700735 return BAD_VALUE;
736 }
737
Dominik Laskowski22488f62019-03-28 09:53:04 -0700738 Mutex::Autolock lock(mStateLock);
739
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800740 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700741 if (!displayId) {
742 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700743 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700744
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745 // TODO: Not sure if display density should handled by SF any longer
746 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700747 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700748 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700749 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800750 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700751 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752 }
753 return density;
754 }
755 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700756 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700758 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 return getDensityFromProperty("ro.sf.lcd_density"); }
760 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700763
Dominik Laskowski075d3172018-05-24 15:50:06 -0700764 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 DisplayInfo info = DisplayInfo();
766
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 float xdpi = hwConfig->getDpiX();
768 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700769
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700770 info.w = hwConfig->getWidth();
771 info.h = hwConfig->getHeight();
772 // Default display viewport to display width and height
773 info.viewportW = info.w;
774 info.viewportH = info.h;
775
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800776 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 // The density of the device is provided by a build property
778 float density = Density::getBuildDensity() / 160.0f;
779 if (density == 0) {
780 // the build doesn't provide a density -- this is wrong!
781 // use xdpi instead
782 ALOGE("ro.sf.lcd_density must be defined as a build property");
783 density = xdpi / 160.0f;
784 }
785 if (Density::getEmuDensity()) {
786 // if "qemu.sf.lcd_density" is specified, it overrides everything
787 xdpi = ydpi = density = Density::getEmuDensity();
788 density /= 160.0f;
789 }
790 info.density = density;
791
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700792 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800793 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700794
795 // This is for screenrecord
796 const Rect viewport = display->getViewport();
797 if (viewport.isValid()) {
798 info.viewportW = uint32_t(viewport.getWidth());
799 info.viewportH = uint32_t(viewport.getHeight());
800 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700801 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700802 } else {
803 // TODO: where should this value come from?
804 static const int TV_DENSITY = 213;
805 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700806
807 const auto display = getDisplayDeviceLocked(displayToken);
808 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 }
810
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 info.xdpi = xdpi;
812 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800814
Ady Abraham9e16a482019-12-03 17:19:41 -0800815 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700816 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817
Andy McFadden91b2ca82014-06-13 14:04:23 -0700818 // This is how far in advance a buffer must be queued for
819 // presentation at a given time. If you want a buffer to appear
820 // on the screen at time N, you must submit the buffer before
821 // (N - presentationDeadline).
822 //
823 // Normally it's one full refresh period (to give SF a chance to
824 // latch the buffer), but this can be reduced by configuring a
825 // DispSync offset. Any additional delays introduced by the hardware
826 // composer or panel must be accounted for here.
827 //
828 // We add an additional 1ms to allow for processing time and
829 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700830 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
832 // All non-virtual displays are currently considered secure.
833 info.secure = true;
834
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800835 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800836 (internalDisplayOrientation == ui::ROTATION_90 ||
837 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800838 std::swap(info.w, info.h);
839 }
840
Michael Wright28f24d02016-07-12 13:30:53 -0700841 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 return NO_ERROR;
845}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700846
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700847status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
848 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700849 return BAD_VALUE;
850 }
851
Ana Krulecc2870422019-01-29 19:00:58 -0800852 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700853 return NO_ERROR;
854}
855
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700856int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
857 const auto display = getDisplayDevice(displayToken);
858 if (!display) {
859 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800860 return BAD_VALUE;
861 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700862
Steven Thomasc9098452019-09-30 17:15:05 -0700863 if (display->isPrimary()) {
864 std::lock_guard<std::mutex> lock(mActiveConfigLock);
865 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800866 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700867 }
Steven Thomasc9098452019-09-30 17:15:05 -0700868 }
Ady Abraham2139f732019-11-13 18:56:40 -0800869
870 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700871}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700872
Ady Abraham03b02dd2019-03-21 15:40:11 -0700873void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800874 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800875 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
876 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800877
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800878 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800879 // config twice. However event generation config might have changed so we need to update it
880 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800881 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700882 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
883 mDesiredActiveConfig = info;
884 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800885
886 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800887 // This will trigger HWC refresh without resetting the idle timer.
888 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700889 // Start receiving vsync samples now, so that we can detect a period
890 // switch.
891 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700892 // As we called to set period, we will call to onRefreshRateChangeCompleted once
893 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700894 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800895
Ady Abraham9e16a482019-12-03 17:19:41 -0800896 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
897 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800898 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800899 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700900
901 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800902 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700903 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800904}
905
906status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
907 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800908
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100909 if (!displayToken) {
910 return BAD_VALUE;
911 }
Ady Abraham838de062019-02-04 10:24:03 -0800912
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100913 status_t result = NO_ERROR;
914
915 postMessageSync(new LambdaMessage([&]() {
916 const auto display = getDisplayDeviceLocked(displayToken);
917 if (!display) {
918 ALOGE("Attempt to set allowed display configs for invalid display token %p",
919 displayToken.get());
920 result = BAD_VALUE;
921 } else if (display->isVirtual()) {
922 ALOGW("Attempt to set allowed display configs for virtual display");
923 result = BAD_VALUE;
924 } else {
925 HwcConfigIndexType config(mode);
926 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
927 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
928 refreshRate.fps);
929 }
930 }));
931
932 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933}
934
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800935void SurfaceFlinger::setActiveConfigInternal() {
936 ATRACE_CALL();
937
Dominik Laskowski22488f62019-03-28 09:53:04 -0700938 const auto display = getDefaultDisplayDeviceLocked();
939 if (!display) {
940 return;
941 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942
Dominik Laskowski22488f62019-03-28 09:53:04 -0700943 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800944 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700945 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 display->setActiveConfig(mUpcomingActiveConfig.configId);
947
Ady Abraham2139f732019-11-13 18:56:40 -0800948 auto refreshRate =
949 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800950 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
951 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800952 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700953
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800954 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700955 const nsecs_t vsyncPeriod =
956 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
957 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800958 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700959 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800960 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961}
962
Ady Abraham53852a52019-05-28 18:07:44 -0700963void SurfaceFlinger::desiredActiveConfigChangeDone() {
964 std::lock_guard<std::mutex> lock(mActiveConfigLock);
965 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
966 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700967
968 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800969 auto refreshRate =
970 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800971 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
972 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700973}
974
Dominik Laskowski22488f62019-03-28 09:53:04 -0700975bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800976 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800977 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700979 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800980 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700981 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800982 return true;
983 }
984
985 // We received the present fence from the HWC, so we assume it successfully updated
986 // the config, hence we update SF.
987 mCheckPendingFence = false;
988 setActiveConfigInternal();
989 }
990
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991 // Store the local variable to release the lock.
992 ActiveConfigInfo desiredActiveConfig;
993 {
994 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800995 if (!mDesiredActiveConfigChanged) {
996 return false;
997 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998 desiredActiveConfig = mDesiredActiveConfig;
999 }
1000
Ady Abraham2139f732019-11-13 18:56:40 -08001001 auto refreshRate =
1002 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1003 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1004 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001005 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1007 // display is not valid or we are already in the requested mode
1008 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001009 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012
Ady Abraham838de062019-02-04 10:24:03 -08001013 // Desired active config was set, it is different than the config currently in use, however
1014 // allowed configs might have change by the time we process the refresh.
1015 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001016 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001017 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001018 return false;
1019 }
Alec Mouri7f015182019-07-11 13:56:22 -07001020
Ady Abrahamb838aed2019-02-12 15:30:16 -08001021 mUpcomingActiveConfig = desiredActiveConfig;
1022 const auto displayId = display->getId();
1023 LOG_ALWAYS_FATAL_IF(!displayId);
1024
Ady Abraham2139f732019-11-13 18:56:40 -08001025 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001027 // TODO(b/142753666) use constrains
1028 HWC2::VsyncPeriodChangeConstraints constraints;
1029 constraints.desiredTimeNanos = systemTime();
1030 constraints.seamlessRequired = false;
1031
1032 HWC2::VsyncPeriodChangeTimeline outTimeline;
1033 auto status =
1034 getHwComposer().setActiveConfigWithConstraints(*displayId,
1035 mUpcomingActiveConfig.configId.value(),
1036 constraints, &outTimeline);
1037 if (status != NO_ERROR) {
1038 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1039 return false;
1040 }
1041
1042 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1043 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001046}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1049 Vector<ColorMode>* outColorModes) {
1050 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001051 return BAD_VALUE;
1052 }
1053
Peiyong Lina52f0292018-03-14 17:26:31 -07001054 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001055 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001056 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001057 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1058
1059 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1060 if (!displayId) {
1061 return NAME_NOT_FOUND;
1062 }
1063
Dominik Laskowski075d3172018-05-24 15:50:06 -07001064 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001065 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001066 }
Michael Wright28f24d02016-07-12 13:30:53 -07001067 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001068
1069 // If it's built-in display and the configuration claims it's not wide color capable,
1070 // filter out all wide color modes. The typical reason why this happens is that the
1071 // hardware is not good enough to support GPU composition of wide color, and thus the
1072 // OEMs choose to disable this capability.
1073 if (isInternalDisplay && !hasWideColorDisplay) {
1074 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1075 isWideColorMode);
1076 } else {
1077 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1078 }
Michael Wright28f24d02016-07-12 13:30:53 -07001079
1080 return NO_ERROR;
1081}
1082
Daniel Solomon42d04562019-01-20 21:03:19 -08001083status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1084 ui::DisplayPrimaries &primaries) {
1085 if (!displayToken) {
1086 return BAD_VALUE;
1087 }
1088
1089 // Currently we only support this API for a single internal display.
1090 if (getInternalDisplayToken() != displayToken) {
1091 return BAD_VALUE;
1092 }
1093
1094 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1099 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001100 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001102 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001103}
1104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 Vector<ColorMode> modes;
1108 getDisplayColorModes(displayToken, &modes);
1109 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1110 if (mode < ColorMode::NATIVE || !exists) {
1111 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1112 decodeColorMode(mode).c_str(), mode, displayToken.get());
1113 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 const auto display = getDisplayDevice(displayToken);
1116 if (!display) {
1117 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1118 decodeColorMode(mode).c_str(), mode, displayToken.get());
1119 } else if (display->isVirtual()) {
1120 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1121 decodeColorMode(mode).c_str(), mode);
1122 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001123 display->getCompositionDisplay()->setColorProfile(
1124 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1125 RenderIntent::COLORIMETRIC,
1126 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127 }
1128 }));
1129
Michael Wright28f24d02016-07-12 13:30:53 -07001130 return NO_ERROR;
1131}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001132
Galia Peycheva5492cb52019-10-30 14:13:16 +01001133status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1134 bool* outSupport) const {
1135 Mutex::Autolock _l(mStateLock);
1136
1137 if (!displayToken) {
1138 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1139 return BAD_VALUE;
1140 }
1141 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1142 if (!displayId) {
1143 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1144 displayToken.get());
1145 return NAME_NOT_FOUND;
1146 }
1147 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1148 HWC2::DisplayCapability::AutoLowLatencyMode);
1149 return NO_ERROR;
1150}
1151
1152void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1153 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1154}
1155
1156void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1157 if (!displayToken) {
1158 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1159 return;
1160 }
1161 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1162 if (!displayId) {
1163 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1164 displayToken.get());
1165 return;
1166 }
1167
1168 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1169}
1170
1171status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1172 bool* outSupport) const {
1173 Mutex::Autolock _l(mStateLock);
1174
1175 if (!displayToken) {
1176 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1177 return BAD_VALUE;
1178 }
1179 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1180 if (!displayId) {
1181 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1182 displayToken.get());
1183 return NAME_NOT_FOUND;
1184 }
1185
1186 std::vector<HWC2::ContentType> outSupportedContentTypes;
1187 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1188 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1189 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1190 return NO_ERROR;
1191}
1192
1193void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1194 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1195}
1196
1197void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1198 if (!displayToken) {
1199 ALOGE("setGameContentType() failed. Missing display token.");
1200 return;
1201 }
1202 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1203 if (!displayId) {
1204 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1205 displayToken.get());
1206 return;
1207 }
1208
1209 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1210 getHwComposer().setContentType(*displayId, type);
1211}
1212
Svetoslavd85084b2014-03-20 10:28:31 -07001213status_t SurfaceFlinger::clearAnimationFrameStats() {
1214 Mutex::Autolock _l(mStateLock);
1215 mAnimFrameTracker.clearStats();
1216 return NO_ERROR;
1217}
1218
1219status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1220 Mutex::Autolock _l(mStateLock);
1221 mAnimFrameTracker.getStats(outStats);
1222 return NO_ERROR;
1223}
1224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001225status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1226 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001227 Mutex::Autolock _l(mStateLock);
1228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001229 const auto display = getDisplayDeviceLocked(displayToken);
1230 if (!display) {
1231 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001232 return BAD_VALUE;
1233 }
1234
Peiyong Linfb069302018-04-25 14:34:31 -07001235 // At this point the DisplayDeivce should already be set up,
1236 // meaning the luminance information is already queried from
1237 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001238 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001239 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1240 capabilities.getDesiredMaxLuminance(),
1241 capabilities.getDesiredMaxAverageLuminance(),
1242 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001243
1244 return NO_ERROR;
1245}
1246
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001247status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1248 ui::PixelFormat* outFormat,
1249 ui::Dataspace* outDataspace,
1250 uint8_t* outComponentMask) const {
1251 if (!outFormat || !outDataspace || !outComponentMask) {
1252 return BAD_VALUE;
1253 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001254 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001255 if (!display || !display->getId()) {
1256 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1257 return BAD_VALUE;
1258 }
1259 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1260 outDataspace, outComponentMask);
1261}
1262
Kevin DuBois74e53772018-11-19 10:52:38 -08001263status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1264 bool enable, uint8_t componentMask,
1265 uint64_t maxFrames) const {
1266 const auto display = getDisplayDevice(displayToken);
1267 if (!display || !display->getId()) {
1268 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1269 return BAD_VALUE;
1270 }
1271
1272 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1273 componentMask, maxFrames);
1274}
1275
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001276status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1277 uint64_t maxFrames, uint64_t timestamp,
1278 DisplayedFrameStats* outStats) const {
1279 const auto display = getDisplayDevice(displayToken);
1280 if (!display || !display->getId()) {
1281 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1282 return BAD_VALUE;
1283 }
1284
1285 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1286 outStats);
1287}
1288
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001289status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1290 if (!outSupported) {
1291 return BAD_VALUE;
1292 }
1293 *outSupported = getRenderEngine().supportsProtectedContent();
1294 return NO_ERROR;
1295}
1296
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001297status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1298 bool* outIsWideColorDisplay) const {
1299 if (!displayToken || !outIsWideColorDisplay) {
1300 return BAD_VALUE;
1301 }
1302 Mutex::Autolock _l(mStateLock);
1303 const auto display = getDisplayDeviceLocked(displayToken);
1304 if (!display) {
1305 return BAD_VALUE;
1306 }
Peiyong Linff84a152019-05-17 18:36:19 -07001307
1308 // Use hasWideColorDisplay to override built-in display.
1309 const auto displayId = display->getId();
1310 if (displayId && displayId == getInternalDisplayIdLocked()) {
1311 *outIsWideColorDisplay = hasWideColorDisplay;
1312 return NO_ERROR;
1313 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001314 *outIsWideColorDisplay = display->hasWideColorGamut();
1315 return NO_ERROR;
1316}
1317
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001318status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001319 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001320 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001321
Dominik Laskowski6505f792019-09-18 11:10:05 -07001322 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1323 mEventQueue->setEventConnection(
1324 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001325 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001326 }));
1327
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001328 return NO_ERROR;
1329}
1330
1331status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001332 Mutex::Autolock lock(mStateLock);
1333 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001334}
1335
Lloyd Pique755e3192018-01-31 16:46:15 -08001336status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1337 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001338 // Try to acquire a lock for 1s, fail gracefully
1339 const status_t err = mStateLock.timedLock(s2ns(1));
1340 const bool locked = (err == NO_ERROR);
1341 if (!locked) {
1342 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1343 return TIMED_OUT;
1344 }
1345
1346 outLayers->clear();
1347 mCurrentState.traverseInZOrder([&](Layer* layer) {
1348 outLayers->push_back(layer->getLayerDebugInfo());
1349 });
1350
1351 mStateLock.unlock();
1352 return NO_ERROR;
1353}
1354
Peiyong Linc6780972018-10-28 15:24:08 -07001355status_t SurfaceFlinger::getCompositionPreference(
1356 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1357 Dataspace* outWideColorGamutDataspace,
1358 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001359 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001360 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001361 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001362 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001363 return NO_ERROR;
1364}
1365
Dan Stozaec460082018-12-17 15:35:09 -08001366status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1367 const sp<IBinder>& stopLayerHandle,
1368 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001369 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001370 return BAD_VALUE;
1371 }
1372 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001373 return NO_ERROR;
1374}
1375
Dan Stozaec460082018-12-17 15:35:09 -08001376status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001377 if (!listener) {
1378 return BAD_VALUE;
1379 }
Dan Stozaec460082018-12-17 15:35:09 -08001380 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001381 return NO_ERROR;
1382}
Dan Gittik57e63c52019-01-18 16:37:54 +00001383
1384status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1385 bool* outSupport) const {
1386 if (!displayToken || !outSupport) {
1387 return BAD_VALUE;
1388 }
1389 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1390 if (!displayId) {
1391 return NAME_NOT_FOUND;
1392 }
1393 *outSupport =
1394 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1395 return NO_ERROR;
1396}
1397
1398status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1399 float brightness) const {
1400 if (!displayToken) {
1401 return BAD_VALUE;
1402 }
1403 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1404 if (!displayId) {
1405 return NAME_NOT_FOUND;
1406 }
1407 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1408}
1409
Ady Abraham8532d012019-05-08 14:50:56 -07001410status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1411 PowerHint powerHint = static_cast<PowerHint>(hintId);
1412
1413 if (powerHint == PowerHint::INTERACTION) {
1414 mScheduler->notifyTouchEvent();
1415 }
1416
1417 return NO_ERROR;
1418}
1419
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001420// ----------------------------------------------------------------------------
1421
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001422sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001423 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001424 const auto& handle =
1425 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001426
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001427 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001428}
1429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001430// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431
1432void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001433 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001434}
1435
1436void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001437 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001438 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001439}
1440
1441void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001442 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001443 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001444}
1445
1446void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001447 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001448 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001449}
1450
1451status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001452 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001453 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001454}
1455
1456status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001457 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001458 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001459 if (res == NO_ERROR) {
1460 msg->wait();
1461 }
1462 return res;
1463}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001464
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001465void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001466 do {
1467 waitForEvent();
1468 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001469}
1470
Dominik Laskowski83b88212018-12-11 13:34:06 -08001471nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001472 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001473 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1474 return 0;
1475 }
1476
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001477 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001478}
1479
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001480void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001481 int64_t timestamp,
1482 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001483 ATRACE_NAME("SF onVsync");
1484
Ady Abraham7159f572019-10-11 11:10:18 -07001485 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1486
Steven Thomas3cfac282017-02-06 12:29:30 -08001487 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001488 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001489 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 return;
1491 }
1492
Dominik Laskowski075d3172018-05-24 15:50:06 -07001493 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001494 return;
1495 }
1496
Dominik Laskowski075d3172018-05-24 15:50:06 -07001497 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001498 // For now, we don't do anything with external display vsyncs.
1499 return;
1500 }
1501
Alec Mourif8e689c2019-05-20 18:32:22 -07001502 bool periodFlushed = false;
1503 mScheduler->addResyncSample(timestamp, &periodFlushed);
1504 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001505 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001506 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001507}
1508
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001509void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001510 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1511 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001512}
1513
Ady Abraham2139f732019-11-13 18:56:40 -08001514bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001515 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001516}
1517
Ady Abraham2139f732019-11-13 18:56:40 -08001518void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1519 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001520 const auto display = getDefaultDisplayDeviceLocked();
1521 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522 return;
1523 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001524 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001525
Ana Krulec7d1d6832018-12-27 11:10:09 -08001526 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001527 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1528 ALOGV("Skipping config %d as it is not part of allowed configs",
1529 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001530 return;
1531 }
1532
Ady Abraham2139f732019-11-13 18:56:40 -08001533 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001534}
1535
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001536void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001537 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001538 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001539 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540
Lloyd Piqueba04e622017-12-14 17:11:26 -08001541 // Ignore events that do not have the right sequenceId.
1542 if (sequenceId != getBE().mComposerSequenceId) {
1543 return;
1544 }
1545
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 // Only lock if we're not on the main thread. This function is normally
1547 // called on a hwbinder thread, but for the primary display it's called on
1548 // the main thread with the state lock already held, so don't attempt to
1549 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001550 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001551
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001552 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001553
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001554 if (std::this_thread::get_id() == mMainThreadId) {
1555 // Process all pending hot plug events immediately if we are on the main thread.
1556 processDisplayHotplugEventsLocked();
1557 }
1558
Lloyd Piqueba04e622017-12-14 17:11:26 -08001559 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001560}
1561
Ady Abraham7159f572019-10-11 11:10:18 -07001562void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001563 int32_t sequenceId, hwc2_display_t /*display*/,
1564 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1565 Mutex::Autolock lock(mStateLock);
1566 if (sequenceId != getBE().mComposerSequenceId) {
1567 return;
1568 }
1569 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001570}
1571
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001572void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1573 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1574 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1575}
1576
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001577void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001578 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001579 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001581 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001582 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001583}
1584
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001585void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001586 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001587
1588 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1589 // display power state.
1590 postMessageAsync(new LambdaMessage(
1591 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1592}
1593
1594void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1595 ATRACE_CALL();
1596
Ady Abraham27c70212019-06-11 10:52:26 -07001597 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1598
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001599 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001600 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1601 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001602 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001603 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001604 }
Mathias Agopian86303202012-07-24 22:46:10 -07001605}
1606
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001607// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001608void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001609 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001610 // Clear the drawing state so that the logic inside of
1611 // handleTransactionLocked will fire. It will determine the delta between
1612 // mCurrentState and mDrawingState and re-apply all changes when we make the
1613 // transition.
1614 mDrawingState.displays.clear();
1615 mDisplays.clear();
1616}
1617
Steven Thomas050b2c82017-03-06 11:45:16 -08001618void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001619 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001620 if (!mVrFlinger)
1621 return;
1622 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001624 return;
1625 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001626
Lloyd Pique441d5042018-10-18 16:49:51 -07001627 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001628 ALOGE("Vr flinger is only supported for remote hardware composer"
1629 " service connections. Ignoring request to transition to vr"
1630 " flinger.");
1631 mVrFlingerRequestsDisplay = false;
1632 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001633 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001634
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001635 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001636
Steven Thomas0123ac62018-07-12 11:32:34 -07001637 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001638 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001639
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001640 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001641
1642 // Clear out all the output layers from the composition engine for all
1643 // displays before destroying the hardware composer interface. This ensures
1644 // any HWC layers are destroyed through that interface before it becomes
1645 // invalid.
1646 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001647 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001648 }
1649
Steven Thomas0123ac62018-07-12 11:32:34 -07001650 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1651 // called below. Clear the reference now so we don't accidentally use it
1652 // later.
1653 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001654
Steven Thomasb02664d2017-07-26 18:48:28 -07001655 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001656 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001657 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001658
Steven Thomasb02664d2017-07-26 18:48:28 -07001659 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001660 // Delete the current instance before creating the new one
1661 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1662 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1663 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1664 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001665
Lloyd Pique441d5042018-10-18 16:49:51 -07001666 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001667 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001668
1669 if (vrFlingerRequestsDisplay) {
1670 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001671 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001672
1673 mVisibleRegionsDirty = true;
1674 invalidateHwcGeometry();
1675
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001676 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001677 display = getDefaultDisplayDeviceLocked();
1678 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001679 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001680
Steven Thomasb02664d2017-07-26 18:48:28 -07001681 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001682 const nsecs_t vsyncPeriod = getVsyncPeriod();
1683 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001684
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001685 // The present fences returned from vr_hwc are not an accurate
1686 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001687 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001688
Steven Thomasb02664d2017-07-26 18:48:28 -07001689 // Use phase of 0 since phase is not known.
1690 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001691 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001692 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001693
Ana Krulecc2870422019-01-29 19:00:58 -08001694 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001695
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001696 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001697 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001698}
1699
Ady Abraham11579302019-09-19 12:35:58 -07001700bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1701 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001702 // We are storing the last 2 present fences. If sf's phase offset is to be
1703 // woken up before the actual vsync but targeting the next vsync, we need to check
1704 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001705 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1706 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001707
Ady Abraham11579302019-09-19 12:35:58 -07001708 if (fence == Fence::NO_FENCE) {
1709 return false;
1710 }
1711
1712 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1713 fence->wait(graceTimeMs);
1714 }
1715
1716 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001717}
1718
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001719void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001720 DisplayStatInfo stats;
1721 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001722 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001723 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001724 mExpectedPresentTime.store(
1725 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001726}
1727
Dominik Laskowski22488f62019-03-28 09:53:04 -07001728void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001729 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001730 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001732 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001733 // calculate the expected present time once and use the cached
1734 // value throughout this frame to make sure all layers are
1735 // seeing this same value.
1736 populateExpectedPresentTime();
1737
Ady Abraham11579302019-09-19 12:35:58 -07001738 // When Backpressure propagation is enabled we want to give a small grace period
1739 // for the present fence to fire instead of just giving up on this frame to handle cases
1740 // where present fence is just about to get signaled.
1741 const int graceTimeForPresentFenceMs =
1742 (mPropagateBackpressure &&
1743 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1744 ? 1
1745 : 0;
1746 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1747 previousFrameMissed(
1748 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001749 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1750 mHadDeviceComposition && frameMissed};
1751 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1752 mHadClientComposition && frameMissed};
1753
Alec Mouricc0fc602019-02-26 21:45:19 -08001754 if (frameMissed) {
1755 mFrameMissedCount++;
1756 mTimeStats->incrementMissedFrames();
1757 }
1758
Alec Mouri40189b02019-03-05 15:07:54 -08001759 if (hwcFrameMissed) {
1760 mHwcFrameMissedCount++;
1761 }
1762
1763 if (gpuFrameMissed) {
1764 mGpuFrameMissedCount++;
1765 }
1766
Ady Abrahamadb9a992019-09-19 21:21:55 +00001767 if (frameMissed && mPropagateBackpressure) {
1768 if ((hwcFrameMissed && !gpuFrameMissed) ||
1769 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001770 signalLayerUpdate();
1771 break;
1772 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001773 }
Dan Stoza50182882016-07-08 12:02:20 -07001774
Steven Thomas050b2c82017-03-06 11:45:16 -08001775 // Now that we're going to make it to the handleMessageTransaction()
1776 // call below it's safe to call updateVrFlinger(), which will
1777 // potentially trigger a display handoff.
1778 updateVrFlinger();
1779
Dan Stoza6b9454d2014-11-07 16:00:59 -08001780 bool refreshNeeded = handleMessageTransaction();
1781 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001782
Ana Krulecc84d09b2019-11-02 23:10:29 +01001783 // Layers need to get updated (in the previous line) before we can use them for
1784 // choosing the refresh rate.
1785 mScheduler->chooseRefreshRateForContent();
1786 if (performSetActiveConfig()) {
1787 break;
1788 }
1789
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001790 updateCursorAsync();
1791 updateInputFlinger();
1792
Dan Stoza58784442014-12-02 16:58:17 -08001793 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001794 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001795 // Signal a refresh if a transaction modified the window state,
1796 // a new buffer was latched, or if HWC has requested a full
1797 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001798 if (mFrameStartTime <= 0) {
1799 // We should only use the time of the first invalidate
1800 // message that signals a refresh as the beginning of the
1801 // frame. Otherwise the real frame time will be
1802 // underestimated.
1803 mFrameStartTime = frameStart;
1804 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001805 signalRefresh();
1806 }
1807 break;
1808 }
1809 case MessageQueue::REFRESH: {
1810 handleMessageRefresh();
1811 break;
1812 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001813 }
1814}
1815
Dan Stoza6b9454d2014-11-07 16:00:59 -08001816bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001817 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001818 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001819
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001820 bool flushedATransaction = flushTransactionQueues();
1821
1822 bool runHandleTransaction = transactionFlags &&
1823 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1824
1825 if (runHandleTransaction) {
1826 handleTransaction(eTransactionMask);
1827 } else {
1828 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001829 }
1830
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001831 if (transactionFlushNeeded()) {
1832 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001833 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001834
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001835 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001836}
1837
Mathias Agopian4fec8732012-06-29 14:12:52 -07001838void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001840
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001841 mRefreshPending = false;
1842
Lloyd Piqueab039b52019-02-13 14:22:42 -08001843 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001844 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001845 for (const auto& [_, display] : mDisplays) {
1846 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1847 }
1848 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1849 auto compositionLayer = layer->getCompositionLayer();
1850 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1851 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001852 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1853 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1854 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001855 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001856 }
1857
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001858 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001859 refreshArgs.outputColorSetting = useColorManagement
1860 ? mDisplayColorSetting
1861 : compositionengine::OutputColorSetting::kUnmanaged;
1862 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1863 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001864
1865 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1866 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001867
1868 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1869 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1870 mDrawingState.colorMatrixChanged = false;
1871 }
1872
1873 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1874
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001875 if (mDebugRegion != 0) {
1876 refreshArgs.devOptFlashDirtyRegionsDelay =
1877 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1878 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001879
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001880 mGeometryInvalid = false;
1881
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001882 // Store the present time just before calling to the composition engine so we could notify
1883 // the scheduler.
1884 const auto presentTime = systemTime();
1885
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001886 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001887 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1888 // Reset the frame start time now that we've recorded this frame.
1889 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001890
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001891 mScheduler->onDisplayRefreshed(presentTime);
1892
David Sodmanfa9b2af2017-12-24 13:28:59 -08001893 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001894 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001895
Lloyd Pique66d68602019-02-13 14:23:31 -08001896 mHadClientComposition =
1897 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1898 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001899 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1900 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001901 });
1902 mHadDeviceComposition =
1903 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1904 auto& displayDevice = tokenDisplayPair.second;
1905 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1906 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001907 mReusedClientComposition =
1908 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1909 auto& displayDevice = tokenDisplayPair.second;
1910 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1911 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001912
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001913 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001914
David Sodman7e4ae112018-02-09 15:02:28 -08001915 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001916 if (mVisibleRegionsDirty) {
1917 mVisibleRegionsDirty = false;
1918 if (mTracingEnabled) {
1919 mTracing.notify("visibleRegionsDirty");
1920 }
1921 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001922
1923 if (mCompositionEngine->needsAnotherUpdate()) {
1924 signalLayerUpdate();
1925 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001926}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001927
David Sodmanfa9b2af2017-12-24 13:28:59 -08001928
1929bool SurfaceFlinger::handleMessageInvalidate() {
1930 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001931 bool refreshNeeded = handlePageFlip();
1932
Vishnu Nair4351ad52019-02-11 14:13:02 -08001933 if (mVisibleRegionsDirty) {
1934 computeLayerBounds();
1935 }
1936
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001937 for (auto& layer : mLayersPendingRefresh) {
1938 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001939 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001940 invalidateLayerStack(layer, visibleReg);
1941 }
1942 mLayersPendingRefresh.clear();
1943 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001944}
1945
Ana Krulece588e312018-09-18 12:32:24 -07001946void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1947 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 // Update queue of past composite+present times and determine the
1949 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001950 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001952 while (!getBE().mCompositePresentTimes.empty()) {
1953 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // Cached values should have been updated before calling this method,
1955 // which helps avoid duplicate syscalls.
1956 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1957 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1958 break;
1959 }
1960 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001961 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 }
1963
1964 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001965 while (getBE().mCompositePresentTimes.size() > 16) {
1966 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 }
1968
Ana Krulece588e312018-09-18 12:32:24 -07001969 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001970}
1971
Ana Krulece588e312018-09-18 12:32:24 -07001972void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1973 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974 // Integer division and modulo round toward 0 not -inf, so we need to
1975 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001976 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1977 ? (stats.vsyncPeriod -
1978 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1979 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980
Ady Abraham9e16a482019-12-03 17:19:41 -08001981 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001982 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001983 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001984 }
1985
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986 // Snap the latency to a value that removes scheduling jitter from the
1987 // composition and present times, which often have >1ms of jitter.
1988 // Reducing jitter is important if an app attempts to extrapolate
1989 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001990 // Snapping also allows an app to precisely calculate
1991 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001992 nsecs_t bias = stats.vsyncPeriod / 2;
1993 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1994 nsecs_t snappedCompositeToPresentLatency =
1995 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001996
David Sodman99974d22017-11-28 12:04:33 -08001997 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001998 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1999 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002000 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002001}
2002
David Sodman2b406362017-12-15 13:33:47 -08002003void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 ATRACE_CALL();
2006 ALOGV("postComposition");
2007
Brian Anderson3546a3f2016-07-14 11:51:14 -07002008 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002009 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002010 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002011 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012 }
2013
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002014 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002015 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016
David Sodman73beded2017-11-15 11:56:06 -08002017 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002019 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002021 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2022 ->getRenderSurface()
2023 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002024 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 } else {
2026 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2027 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028
David Sodman73beded2017-11-15 11:56:06 -08002029 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002030 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2031 mPreviousPresentFences[0] = displayDevice
2032 ? getHwComposer().getPresentFence(*displayDevice->getId())
2033 : Fence::NO_FENCE;
2034 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002035 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002036
Ana Krulece588e312018-09-18 12:32:24 -07002037 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002038 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002039
Lloyd Piqueab039b52019-02-13 14:22:42 -08002040 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2041 // be sampled a little later than when we started doing work for this frame,
2042 // but that should be okay since updateCompositorTiming has snapping logic.
2043 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2044 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002045 CompositorTiming compositorTiming;
2046 {
David Sodman99974d22017-11-28 12:04:33 -08002047 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2048 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002049 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050
Robert Carr2047fae2016-11-28 14:09:09 -08002051 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002052 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2053 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002054 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002055 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002056 }
Robert Carr2047fae2016-11-28 14:09:09 -08002057 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002058
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002059 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002060 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002061 }
2062
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002063 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002064 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2065 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002066 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002067 }
2068 }
2069
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002070 if (mAnimCompositionPending) {
2071 mAnimCompositionPending = false;
2072
Brian Anderson4e606e32017-03-16 15:34:57 -07002073 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002074 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002075 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002076 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002077 // The HWC doesn't support present fences, so use the refresh
2078 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002079 const nsecs_t presentTime =
2080 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002081 mAnimFrameTracker.setActualPresentTime(presentTime);
2082 }
2083 mAnimFrameTracker.advanceFrame();
2084 }
Dan Stozab90cf072015-03-05 11:05:59 -08002085
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002086 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002087 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002088 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002089 }
2090
Vishnu Nair9b079a22020-01-21 14:36:08 -08002091 if (mReusedClientComposition) {
2092 mTimeStats->incrementClientCompositionReusedFrames();
2093 }
2094
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002095 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002096
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2098 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002099 return;
2100 }
2101
2102 nsecs_t currentTime = systemTime();
2103 if (mHasPoweredOff) {
2104 mHasPoweredOff = false;
2105 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002106 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002107 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002108 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2109 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002110 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002111 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002112 }
David Sodman4a36e932017-11-07 14:29:47 -08002113 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002114 }
David Sodman4a36e932017-11-07 14:29:47 -08002115 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002116
2117 {
2118 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002119 if (mTexturePool.size() < mTexturePoolSize) {
2120 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002121 const size_t offset = mTexturePool.size();
2122 mTexturePool.resize(mTexturePoolSize);
2123 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2124 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002125 } else if (mTexturePool.size() > mTexturePoolSize) {
2126 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2127 const size_t offset = mTexturePoolSize;
2128 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2129 mTexturePool.resize(mTexturePoolSize);
2130 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002131 }
2132 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002133
Ady Abrahambe0f9482019-04-24 15:41:53 -07002134 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002135 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002136
Kevin DuBois413287f2019-02-25 08:46:47 -08002137 if (mLumaSampling && mRegionSamplingThread) {
2138 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002139 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002140
2141 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2142 // side-effect of getTotalSize(), so we check that again here
2143 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002144 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002145 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2146 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002147}
2148
Vishnu Nair4351ad52019-02-11 14:13:02 -08002149void SurfaceFlinger::computeLayerBounds() {
2150 for (const auto& pair : mDisplays) {
2151 const auto& displayDevice = pair.second;
2152 const auto display = displayDevice->getCompositionDisplay();
2153 for (const auto& layer : mDrawingState.layersSortedByZ) {
2154 // only consider the layers on the given layer stack
2155 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002156 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002157 }
2158
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002159 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2160 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002161 }
2162 }
2163}
2164
David Sodmanfa9b2af2017-12-24 13:28:59 -08002165void SurfaceFlinger::postFrame()
2166{
2167 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002168 const auto display = getDefaultDisplayDeviceLocked();
2169 if (display && getHwComposer().isConnected(*display->getId())) {
2170 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002171 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2172 logFrameStats();
2173 }
2174 }
2175}
2176
Mathias Agopian87baae12012-07-31 12:38:26 -07002177void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178{
Mathias Agopian841cde52012-03-01 15:44:37 -08002179 ATRACE_CALL();
2180
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002181 // here we keep a copy of the drawing state (that is the state that's
2182 // going to be overwritten by handleTransactionLocked()) outside of
2183 // mStateLock so that the side-effects of the State assignment
2184 // don't happen with mStateLock held (which can cause deadlocks).
2185 State drawingState(mDrawingState);
2186
Mathias Agopianca4d3602011-05-19 15:38:14 -07002187 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002188 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002189
Mathias Agopianca4d3602011-05-19 15:38:14 -07002190 // Here we're guaranteed that some transaction flags are set
2191 // so we can call handleTransactionLocked() unconditionally.
2192 // We call getTransactionFlags(), which will also clear the flags,
2193 // with mStateLock held to guarantee that mCurrentState won't change
2194 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002195
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002196 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002197 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002198 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002199
Mathias Agopianca4d3602011-05-19 15:38:14 -07002200 mDebugInTransaction = 0;
2201 invalidateHwcGeometry();
2202 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002203}
2204
Lloyd Piqueba04e622017-12-14 17:11:26 -08002205void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2206 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002207 const std::optional<DisplayIdentificationInfo> info =
2208 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002209
Dominik Laskowski075d3172018-05-24 15:50:06 -07002210 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002211 continue;
2212 }
2213
Lloyd Piqueba04e622017-12-14 17:11:26 -08002214 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002216 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002217 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2218 initScheduler(info->id);
2219 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002220 mPhysicalDisplayTokens[info->id] = new BBinder();
2221 DisplayDeviceState state;
2222 state.displayId = info->id;
2223 state.isSecure = true; // All physical displays are currently considered secure.
2224 state.displayName = info->name;
2225 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2226 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002227 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002228 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002229 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002230
Dominik Laskowski075d3172018-05-24 15:50:06 -07002231 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2232 if (index >= 0) {
2233 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2234 mInterceptor->saveDisplayDeletion(state.sequenceId);
2235 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002236 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002237 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002238 }
2239
2240 processDisplayChangesLocked();
2241 }
2242
2243 mPendingHotplugEvents.clear();
2244}
2245
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002246void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002247 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2248 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002249}
2250
Lloyd Pique99d3da52018-01-22 17:48:03 -08002251sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002252 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002253 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002254 const sp<IGraphicBufferProducer>& producer) {
2255 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002256 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002257 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002258 creationArgs.isSecure = state.isSecure;
2259 creationArgs.displaySurface = dispSurface;
2260 creationArgs.hasWideColorGamut = false;
2261 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002262 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002263
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002264 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 creationArgs.isPrimary = isInternalDisplay;
2266
2267 if (useColorManagement && displayId) {
2268 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002269 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002270 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002271 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273
Dominik Laskowski7e045462018-05-30 13:02:02 -07002274 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002275 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002276 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277 }
tangrobin6753a022018-08-10 10:58:54 +08002278 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002279
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 if (displayId) {
2281 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002282 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002284 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285
Lloyd Pique90c115d2018-09-18 21:39:42 -07002286 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002287 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002288 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 // Make sure that composition can never be stalled by a virtual display
2291 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002292 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002293 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2295 }
2296
Dominik Laskowski718f9602019-11-09 20:01:35 -08002297 creationArgs.physicalOrientation =
2298 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002299
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002301 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002302
Lloyd Pique90c115d2018-09-18 21:39:42 -07002303 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304
2305 if (maxFrameBufferAcquiredBuffers >= 3) {
2306 nativeWindowSurface->preallocateBuffers();
2307 }
2308
2309 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002311 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002313 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002315 display->getCompositionDisplay()->setColorProfile(
2316 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2317 RenderIntent::COLORIMETRIC,
2318 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002319 if (!state.isVirtual()) {
2320 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002321 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2322 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002323 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002324
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002325 display->setLayerStack(state.layerStack);
2326 display->setProjection(state.orientation, state.viewport, state.frame);
2327 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002328
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330}
2331
Lloyd Pique347200f2017-12-14 17:00:15 -08002332void SurfaceFlinger::processDisplayChangesLocked() {
2333 // here we take advantage of Vector's copy-on-write semantics to
2334 // improve performance by skipping the transaction entirely when
2335 // know that the lists are identical
2336 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2337 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2338 if (!curr.isIdenticalTo(draw)) {
2339 mVisibleRegionsDirty = true;
2340 const size_t cc = curr.size();
2341 size_t dc = draw.size();
2342
2343 // find the displays that were removed
2344 // (ie: in drawing state but not in current state)
2345 // also handle displays that changed
2346 // (ie: displays that are in both lists)
2347 for (size_t i = 0; i < dc;) {
2348 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2349 if (j < 0) {
2350 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002351 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002352 // Save display ID before disconnecting.
2353 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002354 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002355
2356 if (!display->isVirtual()) {
2357 LOG_ALWAYS_FATAL_IF(!displayId);
2358 dispatchDisplayHotplugEvent(displayId->value, false);
2359 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002360 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002361
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002362 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 } else {
2364 // this display is in both lists. see if something changed.
2365 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2368 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2369 if (state_binder != draw_binder) {
2370 // changing the surface is like destroying and
2371 // recreating the DisplayDevice, so we just remove it
2372 // from the drawing state, so that it get re-added
2373 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002375 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002377 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 mDrawingState.displays.removeItemsAt(i);
2379 dc--;
2380 // at this point we must loop to the next item
2381 continue;
2382 }
2383
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002384 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002385 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002386 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002387 }
2388 if ((state.orientation != draw[i].orientation) ||
2389 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002390 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002391 }
2392 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002394 }
2395 }
2396 }
2397 ++i;
2398 }
2399
2400 // find displays that were added
2401 // (ie: in current state but not in drawing state)
2402 for (size_t i = 0; i < cc; i++) {
2403 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2404 const DisplayDeviceState& state(curr[i]);
2405
Lloyd Pique542307f2018-10-19 13:24:08 -07002406 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002407 sp<IGraphicBufferProducer> producer;
2408 sp<IGraphicBufferProducer> bqProducer;
2409 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002410 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002411
Dominik Laskowski075d3172018-05-24 15:50:06 -07002412 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002413 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002414 // Virtual displays without a surface are dormant:
2415 // they have external state (layer stack, projection,
2416 // etc.) but no internal state (i.e. a DisplayDevice).
2417 if (state.surface != nullptr) {
2418 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002420 int width = 0;
2421 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2422 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2423 int height = 0;
2424 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2425 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2426 int intFormat = 0;
2427 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2428 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002429 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002430
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 displayId =
2432 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002433 }
2434
2435 // TODO: Plumb requested format back up to consumer
2436
2437 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002439 bqProducer, bqConsumer,
2440 state.displayName);
2441
2442 dispSurface = vds;
2443 producer = vds;
2444 }
2445 } else {
2446 ALOGE_IF(state.surface != nullptr,
2447 "adding a supported display, but rendering "
2448 "surface is provided (%p), ignoring it",
2449 state.surface.get());
2450
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 displayId = state.displayId;
2452 LOG_ALWAYS_FATAL_IF(!displayId);
2453 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002454 producer = bqProducer;
2455 }
2456
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002458 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002459 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002460 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002461 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002462 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002464 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002465 }
2466 }
2467 }
2468 }
2469 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002470
2471 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002472}
2473
Mathias Agopian87baae12012-07-31 12:38:26 -07002474void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002475{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002476 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2477
Dan Stoza7dde5992015-05-22 09:51:44 -07002478 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002479 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2480 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002481 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002482
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483 /*
2484 * Traversal of the children
2485 * (perform the transaction for each of them if needed)
2486 */
2487
Marissa Wall06255332019-03-27 13:48:27 -07002488 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002489 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002491 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492
2493 const uint32_t flags = layer->doTransaction(0);
2494 if (flags & Layer::eVisibleRegion)
2495 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002496
2497 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002498 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002499 }
Robert Carr2047fae2016-11-28 14:09:09 -08002500 });
Marissa Wall06255332019-03-27 13:48:27 -07002501 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502 }
2503
2504 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002505 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 */
2507
Mathias Agopiane57f2922012-08-09 16:29:12 -07002508 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002510 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002513 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002514 // The transform hint might have changed for some layers
2515 // (either because a display has changed, or because a layer
2516 // as changed).
2517 //
2518 // Walk through all the layers in currentLayers,
2519 // and update their transform hint.
2520 //
2521 // If a layer is visible only on a single display, then that
2522 // display is used to calculate the hint, otherwise we use the
2523 // default display.
2524 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002525 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002526 // the hint is set before we acquire a buffer from the surface texture.
2527 //
2528 // NOTE: layer transactions have taken place already, so we use their
2529 // drawing state. However, SurfaceFlinger's own transaction has not
2530 // happened yet, so we must use the current state layer list
2531 // (soon to become the drawing state list).
2532 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002533 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002534 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002535 bool first = true;
2536 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002537 // NOTE: we rely on the fact that layers are sorted by
2538 // layerStack first (so we don't have to traverse the list
2539 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002540 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002541 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002542 currentlayerStack = layerStack;
2543 // figure out if this layerstack is mirrored
2544 // (more than one display) if so, pick the default display,
2545 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002546 hintDisplay = nullptr;
2547 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002548 if (display->getCompositionDisplay()
2549 ->belongsInOutput(layer->getLayerStack(),
2550 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 if (hintDisplay) {
2552 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002553 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002554 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002555 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002556 }
2557 }
2558 }
2559 }
Chet Haase91d25932013-04-11 15:24:55 -07002560
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002562 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2563 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002564
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002565 // could be null when this layer is using a layerStack
2566 // that is not visible on any display. Also can occur at
2567 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002568 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002569 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002570
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002571 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002572 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002573 if (hintDisplay) {
2574 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002575 }
Robert Carr2047fae2016-11-28 14:09:09 -08002576
2577 first = false;
2578 });
Mathias Agopian84300952012-11-21 16:02:13 -08002579 }
2580
2581
Mathias Agopian3559b072012-08-15 13:46:03 -07002582 /*
2583 * Perform our own transaction if needed
2584 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585
2586 if (mLayersAdded) {
2587 mLayersAdded = false;
2588 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002589 mVisibleRegionsDirty = true;
2590 }
2591
2592 // some layers might have been removed, so
2593 // we need to update the regions they're exposing.
2594 if (mLayersRemoved) {
2595 mLayersRemoved = false;
2596 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002597 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002598 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002599 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002600 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002601 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002602 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002603 }
Robert Carr2047fae2016-11-28 14:09:09 -08002604 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 }
2606
Vishnu Nairec0ab382019-02-13 15:32:56 -08002607 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002609}
2610
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002611void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002612 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002613 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002614 return;
2615 }
2616
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002617 if (mVisibleRegionsDirty || mInputInfoChanged) {
2618 mInputInfoChanged = false;
2619 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002620 } else if (mInputWindowCommands.syncInputWindows) {
2621 // If the caller requested to sync input windows, but there are no
2622 // changes to input windows, notify immediately.
2623 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002624 }
2625
Arthur Hung6cbb9752019-09-05 16:38:18 +08002626 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002627}
2628
2629void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002630 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002631
2632 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2633 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002634 // When calculating the screen bounds we ignore the transparent region since it may
2635 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002636 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002637 }
2638 });
chaviw291d88a2019-02-14 10:33:58 -08002639
2640 mInputFlinger->setInputWindows(inputHandles,
2641 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2642 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002643}
2644
Vishnu Nairec0ab382019-02-13 15:32:56 -08002645void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002646 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002647 mPendingInputWindowCommands.clear();
2648}
2649
Riley Andrews03414a12014-07-01 14:22:59 -07002650void SurfaceFlinger::updateCursorAsync()
2651{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002652 compositionengine::CompositionRefreshArgs refreshArgs;
2653 for (const auto& [_, display] : mDisplays) {
2654 if (display->getId()) {
2655 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002656 }
2657 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002658
2659 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002660}
2661
Ady Abraham2139f732019-11-13 18:56:40 -08002662void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2663 Scheduler::ConfigEvent event) {
2664 Mutex::Autolock lock(mStateLock);
2665 changeRefreshRateLocked(refreshRate, event);
2666}
2667
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002668void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2669 if (mScheduler) {
2670 // In practice it's not allowed to hotplug in/out the primary display once it's been
2671 // connected during startup, but some tests do it, so just warn and return.
2672 ALOGW("Can't re-init scheduler");
2673 return;
2674 }
2675
Ady Abraham2139f732019-11-13 18:56:40 -08002676 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002677 mRefreshRateConfigs =
2678 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2679 getHwComposer().getConfigs(
2680 primaryDisplayId),
2681 currentConfig);
2682 mRefreshRateStats =
2683 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2684 currentConfig, HWC_POWER_MODE_OFF);
2685 mRefreshRateStats->setConfigMode(currentConfig);
2686
Ady Abraham9e16a482019-12-03 17:19:41 -08002687 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2688
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002689 // start the EventThread
2690 mScheduler =
2691 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002692 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002693 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002694 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002695 impl::EventThread::InterceptVSyncsCallback());
2696 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002697 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002698 [this](nsecs_t timestamp) {
2699 mInterceptor->saveVSyncEvent(timestamp);
2700 });
2701
2702 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2703 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002704 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002705
2706 mRegionSamplingThread =
2707 new RegionSamplingThread(*this, *mScheduler,
2708 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002709 // Dispatch a config change request for the primary display on scheduler
2710 // initialization, so that the EventThreads always contain a reference to a
2711 // prior configuration.
2712 //
2713 // This is a bit hacky, but this avoids a back-pointer into the main SF
2714 // classes from EventThread, and there should be no run-time binder cost
2715 // anyway since there are no connected apps at this point.
2716 const nsecs_t vsyncPeriod =
2717 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2718 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2719 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002720}
2721
Mathias Agopian4fec8732012-06-29 14:12:52 -07002722void SurfaceFlinger::commitTransaction()
2723{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002724 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002725
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002726 mTransactionPending = false;
2727 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002728 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729}
2730
Lloyd Pique58e24a32019-08-01 15:50:14 -07002731void SurfaceFlinger::commitTransactionLocked() {
2732 if (!mLayersPendingRemoval.isEmpty()) {
2733 // Notify removed layers now that they can't be drawn from
2734 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002735 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002736
2737 // Ensure any buffers set to display on any children are released.
2738 if (l->isRemovedFromCurrentState()) {
2739 l->latchAndReleaseBuffer();
2740 }
2741
2742 // If the layer has been removed and has no parent, then it will not be reachable
2743 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2744 // ensure we can copy its current to drawing state.
2745 if (!l->getParent()) {
2746 mOffscreenLayers.emplace(l.get());
2747 }
2748 }
2749 mLayersPendingRemoval.clear();
2750 }
2751
2752 // If this transaction is part of a window animation then the next frame
2753 // we composite should be considered an animation as well.
2754 mAnimCompositionPending = mAnimTransactionPending;
2755
2756 mDrawingState = mCurrentState;
2757 // clear the "changed" flags in current state
2758 mCurrentState.colorMatrixChanged = false;
2759
2760 mDrawingState.traverseInZOrder([&](Layer* layer) {
2761 layer->commitChildList();
2762
2763 // If the layer can be reached when traversing mDrawingState, then the layer is no
2764 // longer offscreen. Remove the layer from the offscreenLayer set.
2765 if (mOffscreenLayers.count(layer)) {
2766 mOffscreenLayers.erase(layer);
2767 }
2768 });
2769
2770 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002771 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002772}
2773
Nataniel Borges2b796da2019-02-15 13:32:18 -08002774void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2775 if (mTracingEnabledChanged) {
2776 mTracingEnabled = mTracing.isEnabled();
2777 mTracingEnabledChanged = false;
2778 }
2779
2780 // Synchronize with Tracing thread
2781 std::unique_lock<std::mutex> lock;
2782 if (mTracingEnabled) {
2783 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2784 }
2785
2786 lockedOperation();
2787
2788 // Synchronize with Tracing thread
2789 if (mTracingEnabled) {
2790 lock.unlock();
2791 }
2792}
2793
chaviw74d90ad2019-04-26 14:45:26 -07002794void SurfaceFlinger::commitOffscreenLayers() {
2795 for (Layer* offscreenLayer : mOffscreenLayers) {
2796 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2797 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2798 if (!trFlags) return;
2799
2800 layer->doTransaction(0);
2801 layer->commitChildList();
2802 });
2803 }
2804}
2805
Chia-I Wuab0c3192017-08-01 11:29:00 -07002806void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002807 for (const auto& [token, displayDevice] : mDisplays) {
2808 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002809 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002810 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002811 }
2812 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002813}
2814
Dan Stoza6b9454d2014-11-07 16:00:59 -08002815bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816{
Ady Abraham09bd3922019-04-08 10:44:56 -07002817 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002818 ALOGV("handlePageFlip");
2819
Brian Andersond6927fb2016-07-23 23:37:30 -07002820 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821
Mathias Agopian4fec8732012-06-29 14:12:52 -07002822 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002823 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002824 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002825
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002826 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2827
Eric Penner51c59cd2014-07-28 19:51:58 -07002828 // Store the set of layers that need updates. This set must not change as
2829 // buffers are being latched, as this could result in a deadlock.
2830 // Example: Two producers share the same command stream and:
2831 // 1.) Layer 0 is latched
2832 // 2.) Layer 0 gets a new frame
2833 // 2.) Layer 1 gets a new frame
2834 // 3.) Layer 1 is latched.
2835 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2836 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002837 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002838 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002839 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002840 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002841 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002842 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002843 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002844 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002845 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002846 } else {
2847 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002848 }
Robert Carr2047fae2016-11-28 14:09:09 -08002849 });
2850
chaviw49a108c2019-08-12 11:23:06 -07002851 // The client can continue submitting buffers for offscreen layers, but they will not
2852 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2853 // layers to ensure dequeueBuffer doesn't block indefinitely.
2854 for (Layer* offscreenLayer : mOffscreenLayers) {
2855 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2856 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2857 }
2858
Lloyd Piquef2c79392018-12-20 16:23:33 -08002859 if (!mLayersWithQueuedFrames.empty()) {
2860 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2861 // writes to Layer current state. See also b/119481871
2862 Mutex::Autolock lock(mStateLock);
2863
2864 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002865 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002866 mLayersPendingRefresh.push_back(layer);
2867 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002868 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002869 if (layer->isBufferLatched()) {
2870 newDataLatched = true;
2871 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002872 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002873 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002874
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002875 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002876
2877 // If we will need to wake up at some time in the future to deal with a
2878 // queued frame that shouldn't be displayed during this vsync period, wake
2879 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002880 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002881 signalLayerUpdate();
2882 }
2883
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002884 // enter boot animation on first buffer latch
2885 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2886 ALOGI("Enter boot animation");
2887 mBootStage = BootStage::BOOTANIMATION;
2888 }
2889
chaviw74b03172019-08-19 11:09:03 -07002890 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2891
Dan Stoza6b9454d2014-11-07 16:00:59 -08002892 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002893 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894}
2895
Mathias Agopianad456f92011-01-13 17:53:01 -08002896void SurfaceFlinger::invalidateHwcGeometry()
2897{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002898 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002899}
2900
Robert Carrc0df3122019-04-11 13:18:21 -07002901status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2902 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2903 const sp<IBinder>& parentHandle,
2904 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002905 // add this layer to the current state list
2906 {
2907 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002908 sp<Layer> parent;
2909 if (parentHandle != nullptr) {
2910 parent = fromHandle(parentHandle);
2911 if (parent == nullptr) {
2912 return NAME_NOT_FOUND;
2913 }
2914 } else {
2915 parent = parentLayer;
2916 }
2917
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002919 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002920 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002921 return NO_MEMORY;
2922 }
Robert Carrc0df3122019-04-11 13:18:21 -07002923
2924 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2925
Robert Carrb89ea9d2018-12-10 13:01:14 -08002926 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002927 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002928 } else if (parent == nullptr) {
2929 lbc->onRemovedFromCurrentState();
2930 } else if (parent->isRemovedFromCurrentState()) {
2931 parent->addChild(lbc);
2932 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002933 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002934 parent->addChild(lbc);
2935 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002936
Yiwei Zhang243b3782018-05-15 17:40:04 -07002937 if (gbc != nullptr) {
2938 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2939 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2940 mMaxGraphicBufferProducerListSize,
2941 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2942 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002943 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002944 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002945 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002946 }
2947
Mathias Agopian96f08192010-06-02 23:28:45 -07002948 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002949 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002950
Dan Stoza7d89d062015-04-30 13:29:25 -07002951 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002952}
2953
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002954uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002955 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002956}
2957
Mathias Agopian3f844832013-08-07 21:24:32 -07002958uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002959 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960}
2961
Mathias Agopian3f844832013-08-07 21:24:32 -07002962uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002963 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002964}
2965
2966uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002967 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002968 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002969 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002971 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972 }
2973 return old;
2974}
2975
Marissa Wall713b63f2018-10-17 15:42:43 -07002976bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002977 // to prevent onHandleDestroyed from being called while the lock is held,
2978 // we must keep a copy of the transactions (specifically the composer
2979 // states) around outside the scope of the lock
2980 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002981 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002982 {
2983 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002984
Valerie Haufce31b82019-04-30 16:41:14 -07002985 auto it = mTransactionQueues.begin();
2986 while (it != mTransactionQueues.end()) {
2987 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002988
Valerie Haufce31b82019-04-30 16:41:14 -07002989 while (!transactionQueue.empty()) {
2990 const auto& transaction = transactionQueue.front();
2991 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002992 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002993 transaction.states)) {
2994 setTransactionFlags(eTransactionFlushNeeded);
2995 break;
2996 }
2997 transactions.push_back(transaction);
2998 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2999 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003000 transaction.buffer, transaction.postTime,
3001 transaction.privileged, transaction.hasListenerCallbacks,
3002 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003003 transactionQueue.pop();
3004 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003005 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003006
Valerie Haufce31b82019-04-30 16:41:14 -07003007 if (transactionQueue.empty()) {
3008 it = mTransactionQueues.erase(it);
3009 mTransactionCV.broadcast();
3010 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003011 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003012 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003013 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003014 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003015 return flushedATransaction;
3016}
3017
3018bool SurfaceFlinger::transactionFlushNeeded() {
3019 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003020}
3021
chaviwca27f252018-02-06 16:46:39 -08003022
Marissa Wall17b4e452018-12-26 16:32:34 -08003023bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003024 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003025 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003026 if (!useCachedExpectedPresentTime)
3027 populateExpectedPresentTime();
3028
3029 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003030 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3031 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3032 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3033 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3034 return false;
3035 }
3036
Marissa Wall713b63f2018-10-17 15:42:43 -07003037 for (const ComposerState& state : states) {
3038 const layer_state_t& s = state.state;
3039 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3040 continue;
3041 }
3042 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003043 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003044 }
3045 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003046 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003047}
3048
Valerie Hau9dab9732019-08-20 09:29:25 -07003049void SurfaceFlinger::setTransactionState(
3050 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3051 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3052 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3053 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003054 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003055
Valerie Haubc6ddb12019-03-08 11:10:15 -08003056 const int64_t postTime = systemTime();
3057
Robert Carr14167e02019-02-13 13:50:55 -08003058 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3059
Mathias Agopian698c0872011-06-28 19:09:31 -07003060 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061
Marissa Wall713b63f2018-10-17 15:42:43 -07003062 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003063 auto itr = mTransactionQueues.find(applyToken);
3064 // if this is an animation frame, wait until prior animation frame has
3065 // been applied by SF
3066 if (flags & eAnimation) {
3067 while (itr != mTransactionQueues.end()) {
3068 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3069 if (CC_UNLIKELY(err != NO_ERROR)) {
3070 ALOGW_IF(err == TIMED_OUT,
3071 "setTransactionState timed out "
3072 "waiting for animation frame to apply");
3073 break;
3074 }
3075 itr = mTransactionQueues.find(applyToken);
3076 }
3077 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003078
3079 // Expected present time is computed and cached on invalidate, so it may be stale.
3080 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3081 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003082 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003083 uncacheBuffer, postTime, privileged,
3084 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003085 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003086 return;
3087 }
3088
Valerie Haubc6ddb12019-03-08 11:10:15 -08003089 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003090 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3091 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003092}
3093
Valerie Hau9dab9732019-08-20 09:29:25 -07003094void SurfaceFlinger::applyTransactionState(
3095 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3096 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3097 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3098 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3099 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003100 uint32_t transactionFlags = 0;
3101
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003102 if (flags & eAnimation) {
3103 // For window updates that are part of an animation we must wait for
3104 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003105 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003106 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003107 if (CC_UNLIKELY(err != NO_ERROR)) {
3108 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003109 // caller after a few seconds.
3110 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3111 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003112 mAnimTransactionPending = false;
3113 break;
3114 }
3115 }
3116 }
3117
chaviwca27f252018-02-06 16:46:39 -08003118 for (const DisplayState& display : displays) {
3119 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003120 }
3121
Valerie Hau9dab9732019-08-20 09:29:25 -07003122 // start and end registration for listeners w/ no surface so they can get their callback. Note
3123 // that listeners with SurfaceControls will start registration during setClientStateLocked
3124 // below.
3125 for (const auto& listener : listenerCallbacks) {
3126 mTransactionCompletedThread.startRegistration(listener);
3127 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003128 }
3129
Valerie Hau9dab9732019-08-20 09:29:25 -07003130 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003131 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003132 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003133 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3134 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003135 }
3136
Valerie Hau9dab9732019-08-20 09:29:25 -07003137 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003138 mTransactionCompletedThread.endRegistration(listenerCallback);
3139 }
3140
Marissa Walle2ffb422018-10-12 11:33:52 -07003141 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003142 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003143 mTransactionCompletedThread.sendCallbacks();
3144 }
3145 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003146
chaviw273171b2018-12-26 11:46:30 -08003147 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3148
Marissa Wall947d34e2019-03-29 14:03:53 -07003149 if (uncacheBuffer.isValid()) {
3150 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003151 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003152 }
3153
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003154 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3155 // anyway. This can be used as a flush mechanism for previous async transactions.
3156 // Empty animation transaction can be used to simulate back-pressure, so also force a
3157 // transaction for empty animation transactions.
3158 if (transactionFlags == 0 &&
3159 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003160 transactionFlags = eTransactionNeeded;
3161 }
3162
Marissa Wall06255332019-03-27 13:48:27 -07003163 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3164 // so we don't have to wake up again next frame to preform an uneeded traversal.
3165 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3166 transactionFlags = transactionFlags & (~eTraversalNeeded);
3167 mTraversalNeededMainThread = true;
3168 }
3169
Mathias Agopian386aa982011-11-07 21:58:03 -08003170 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003171 if (mInterceptor->isEnabled()) {
3172 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003173 }
Irvel468051e2016-06-13 16:44:44 -07003174
Mathias Agopian386aa982011-11-07 21:58:03 -08003175 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003176 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3177 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003178 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003179
3180 // if this is a synchronous transaction, wait for it to take effect
3181 // before returning.
3182 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003183 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003184 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003185 if (flags & eAnimation) {
3186 mAnimTransactionPending = true;
3187 }
chaviw4fe36852019-04-15 16:25:49 -07003188 if (mPendingInputWindowCommands.syncInputWindows) {
3189 mPendingSyncInputWindows = true;
3190 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003191
3192 // applyTransactionState can be called by either the main SF thread or by
3193 // another process through setTransactionState. While a given process may wish
3194 // to wait on synchronous transactions, the main SF thread should never
3195 // be blocked. Therefore, we only wait if isMainThread is false.
3196 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003197 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3198 if (CC_UNLIKELY(err != NO_ERROR)) {
3199 // just in case something goes wrong in SF, return to the
3200 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003201 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3202 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003203 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003204 break;
3205 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003206 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207 }
3208}
3209
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003210uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3211 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3212 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003213
Mathias Agopiane57f2922012-08-09 16:29:12 -07003214 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003215 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3216
3217 const uint32_t what = s.what;
3218 if (what & DisplayState::eSurfaceChanged) {
3219 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3220 state.surface = s.surface;
3221 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003222 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003223 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003224 if (what & DisplayState::eLayerStackChanged) {
3225 if (state.layerStack != s.layerStack) {
3226 state.layerStack = s.layerStack;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
3230 if (what & DisplayState::eDisplayProjectionChanged) {
3231 if (state.orientation != s.orientation) {
3232 state.orientation = s.orientation;
3233 flags |= eDisplayTransactionNeeded;
3234 }
3235 if (state.frame != s.frame) {
3236 state.frame = s.frame;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 if (state.viewport != s.viewport) {
3240 state.viewport = s.viewport;
3241 flags |= eDisplayTransactionNeeded;
3242 }
3243 }
3244 if (what & DisplayState::eDisplaySizeChanged) {
3245 if (state.width != s.width) {
3246 state.width = s.width;
3247 flags |= eDisplayTransactionNeeded;
3248 }
3249 if (state.height != s.height) {
3250 state.height = s.height;
3251 flags |= eDisplayTransactionNeeded;
3252 }
3253 }
3254
Mathias Agopiane57f2922012-08-09 16:29:12 -07003255 return flags;
3256}
3257
Robert Carr14167e02019-02-13 13:50:55 -08003258bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003259 IPCThreadState* ipc = IPCThreadState::self();
3260 const int pid = ipc->getCallingPid();
3261 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003262 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003263 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003264 return false;
3265 }
3266 return true;
3267}
3268
Marissa Wall3dad52d2019-03-22 14:03:19 -07003269uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003270 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3271 bool privileged,
3272 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003273 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003274
Valerie Hau9dab9732019-08-20 09:29:25 -07003275 for (auto& listener : s.listeners) {
3276 // note that startRegistration will not re-register if the listener has
3277 // already be registered for a prior surface control
3278 mTransactionCompletedThread.startRegistration(listener);
3279 listenerCallbacks.insert(listener);
3280 }
3281
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003282 sp<Layer> layer = nullptr;
3283 if (s.surface) {
3284 layer = fromHandle(s.surface);
3285 } else {
3286 // The client may provide us a null handle. Treat it as if the layer was removed.
3287 ALOGW("Attempt to set client state with a null layer handle");
3288 }
chaviw8b3871a2017-11-01 17:41:01 -07003289 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003290 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003291 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003292 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003293 }
chaviw8b3871a2017-11-01 17:41:01 -07003294 return 0;
3295 }
3296
chaviw8b3871a2017-11-01 17:41:01 -07003297 uint32_t flags = 0;
3298
Garfield Tan8a3083e2018-12-03 13:21:07 -08003299 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003300
3301 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3302 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003303 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003304 layer->pushPendingState();
3305 }
3306
chaviw8b3871a2017-11-01 17:41:01 -07003307 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003308 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003309 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003310 }
chaviw8b3871a2017-11-01 17:41:01 -07003311 }
3312 if (what & layer_state_t::eLayerChanged) {
3313 // NOTE: index needs to be calculated before we update the state
3314 const auto& p = layer->getParent();
3315 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003316 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003317 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003318 mCurrentState.layersSortedByZ.removeAt(idx);
3319 mCurrentState.layersSortedByZ.add(layer);
3320 // we need traversal (state changed)
3321 // AND transaction (list changed)
3322 flags |= eTransactionNeeded|eTraversalNeeded;
3323 }
chaviw8b3871a2017-11-01 17:41:01 -07003324 } else {
3325 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003326 flags |= eTransactionNeeded|eTraversalNeeded;
3327 }
3328 }
chaviw8b3871a2017-11-01 17:41:01 -07003329 }
3330 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003331 // NOTE: index needs to be calculated before we update the state
3332 const auto& p = layer->getParent();
3333 if (p == nullptr) {
3334 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3335 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3336 mCurrentState.layersSortedByZ.removeAt(idx);
3337 mCurrentState.layersSortedByZ.add(layer);
3338 // we need traversal (state changed)
3339 // AND transaction (list changed)
3340 flags |= eTransactionNeeded|eTraversalNeeded;
3341 }
3342 } else {
3343 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3344 flags |= eTransactionNeeded|eTraversalNeeded;
3345 }
chaviw8b3871a2017-11-01 17:41:01 -07003346 }
3347 }
3348 if (what & layer_state_t::eSizeChanged) {
3349 if (layer->setSize(s.w, s.h)) {
3350 flags |= eTraversalNeeded;
3351 }
3352 }
3353 if (what & layer_state_t::eAlphaChanged) {
3354 if (layer->setAlpha(s.alpha))
3355 flags |= eTraversalNeeded;
3356 }
3357 if (what & layer_state_t::eColorChanged) {
3358 if (layer->setColor(s.color))
3359 flags |= eTraversalNeeded;
3360 }
Peiyong Lind3788632018-09-18 16:01:31 -07003361 if (what & layer_state_t::eColorTransformChanged) {
3362 if (layer->setColorTransform(s.colorTransform)) {
3363 flags |= eTraversalNeeded;
3364 }
3365 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003366 if (what & layer_state_t::eBackgroundColorChanged) {
3367 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3368 flags |= eTraversalNeeded;
3369 }
3370 }
chaviw8b3871a2017-11-01 17:41:01 -07003371 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003372 // TODO: b/109894387
3373 //
3374 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3375 // rotation. To see the problem observe that if we have a square parent, and a child
3376 // of the same size, then we rotate the child 45 degrees around it's center, the child
3377 // must now be cropped to a non rectangular 8 sided region.
3378 //
3379 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3380 // private API, and the WindowManager only uses rotation in one case, which is on a top
3381 // level layer in which cropping is not an issue.
3382 //
3383 // However given that abuse of rotation matrices could lead to surfaces extending outside
3384 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3385 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3386 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003387 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003388 flags |= eTraversalNeeded;
3389 }
3390 if (what & layer_state_t::eTransparentRegionChanged) {
3391 if (layer->setTransparentRegionHint(s.transparentRegion))
3392 flags |= eTraversalNeeded;
3393 }
3394 if (what & layer_state_t::eFlagsChanged) {
3395 if (layer->setFlags(s.flags, s.mask))
3396 flags |= eTraversalNeeded;
3397 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003398 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003399 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003400 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003401 if (what & layer_state_t::eCornerRadiusChanged) {
3402 if (layer->setCornerRadius(s.cornerRadius))
3403 flags |= eTraversalNeeded;
3404 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003405 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3406 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3407 }
chaviw8b3871a2017-11-01 17:41:01 -07003408 if (what & layer_state_t::eLayerStackChanged) {
3409 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3410 // We only allow setting layer stacks for top level layers,
3411 // everything else inherits layer stack from its parent.
3412 if (layer->hasParent()) {
3413 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003414 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003415 } else if (idx < 0) {
3416 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003417 "that also does not appear in the top level layer list. Something"
3418 " has gone wrong.",
3419 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003420 } else if (layer->setLayerStack(s.layerStack)) {
3421 mCurrentState.layersSortedByZ.removeAt(idx);
3422 mCurrentState.layersSortedByZ.add(layer);
3423 // we need traversal (state changed)
3424 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003425 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003426 }
3427 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003428 if (what & layer_state_t::eDeferTransaction_legacy) {
3429 if (s.barrierHandle_legacy != nullptr) {
3430 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3431 } else if (s.barrierGbp_legacy != nullptr) {
3432 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003433 if (authenticateSurfaceTextureLocked(gbp)) {
3434 const auto& otherLayer =
3435 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003436 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003437 } else {
3438 ALOGE("Attempt to defer transaction to to an"
3439 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003440 }
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 // We don't trigger a traversal here because if no other state is
3443 // changed, we don't want this to cause any more work
3444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 if (what & layer_state_t::eReparentChildren) {
3446 if (layer->reparentChildren(s.reparentHandle)) {
3447 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003448 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003449 }
chaviw8b3871a2017-11-01 17:41:01 -07003450 if (what & layer_state_t::eDetachChildren) {
3451 layer->detachChildren();
3452 }
3453 if (what & layer_state_t::eOverrideScalingModeChanged) {
3454 layer->setOverrideScalingMode(s.overrideScalingMode);
3455 // We don't trigger a traversal here because if no other state is
3456 // changed, we don't want this to cause any more work
3457 }
Marissa Wall61c58622018-07-18 10:12:20 -07003458 if (what & layer_state_t::eTransformChanged) {
3459 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3462 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3463 flags |= eTraversalNeeded;
3464 }
3465 if (what & layer_state_t::eCropChanged) {
3466 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3467 }
Marissa Wall861616d2018-10-22 12:52:23 -07003468 if (what & layer_state_t::eFrameChanged) {
3469 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3470 }
Marissa Wall61c58622018-07-18 10:12:20 -07003471 if (what & layer_state_t::eAcquireFenceChanged) {
3472 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3473 }
3474 if (what & layer_state_t::eDataspaceChanged) {
3475 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3476 }
3477 if (what & layer_state_t::eHdrMetadataChanged) {
3478 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3481 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3482 }
3483 if (what & layer_state_t::eApiChanged) {
3484 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3485 }
3486 if (what & layer_state_t::eSidebandStreamChanged) {
3487 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3488 }
Robert Carr720e5062018-07-30 17:45:14 -07003489 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003490 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003491 layer->setInputInfo(s.inputInfo);
3492 flags |= eTraversalNeeded;
3493 } else {
3494 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3495 }
Robert Carr720e5062018-07-30 17:45:14 -07003496 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003497 if (what & layer_state_t::eMetadataChanged) {
3498 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3499 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003500 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3501 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3502 flags |= eTraversalNeeded;
3503 }
3504 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003505 if (what & layer_state_t::eShadowRadiusChanged) {
3506 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3507 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003508 if (what & layer_state_t::eFrameRateSelectionPriority) {
3509 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3510 flags |= eTraversalNeeded;
3511 }
3512 }
Steven Thomas3172e202020-01-06 19:25:30 -08003513 if (what & layer_state_t::eFrameRateChanged) {
3514 if (layer->setFrameRate(s.frameRate)) flags |= eTraversalNeeded;
3515 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003516 // This has to happen after we reparent children because when we reparent to null we remove
3517 // child layers from current state and remove its relative z. If the children are reparented in
3518 // the same transaction, then we have to make sure we reparent the children first so we do not
3519 // lose its relative z order.
3520 if (what & layer_state_t::eReparent) {
3521 bool hadParent = layer->hasParent();
3522 if (layer->reparent(s.parentHandleForChild)) {
3523 if (!hadParent) {
3524 mCurrentState.layersSortedByZ.remove(layer);
3525 }
3526 flags |= eTransactionNeeded | eTraversalNeeded;
3527 }
3528 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003529 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003530 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3531 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003532 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3533 }
3534 }
Marissa Wall78b72202019-03-15 14:58:34 -07003535 bool bufferChanged = what & layer_state_t::eBufferChanged;
3536 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3537 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003538 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003539 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003540 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3541 if (success) {
3542 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3543 success = ClientCache::getInstance()
3544 .registerErasedRecipient(s.cachedBuffer,
3545 wp<ClientCache::ErasedRecipient>(this));
3546 if (!success) {
3547 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3548 }
3549 }
Marissa Wall78b72202019-03-15 14:58:34 -07003550 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003551 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003552 } else if (bufferChanged) {
3553 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003554 }
Marissa Wall78b72202019-03-15 14:58:34 -07003555 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003556 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003557 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003558 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003559 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003560 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3561 // Do not put anything that updates layer state or modifies flags after
3562 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003563 return flags;
3564}
3565
chaviw273171b2018-12-26 11:46:30 -08003566uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3567 uint32_t flags = 0;
3568 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3569 flags |= eTraversalNeeded;
3570 }
3571
chaviwa911b102019-02-14 10:18:33 -08003572 if (inputWindowCommands.syncInputWindows) {
3573 flags |= eTraversalNeeded;
3574 }
3575
Vishnu Nairec0ab382019-02-13 15:32:56 -08003576 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003577 return flags;
3578}
3579
chaviwfe94a222019-08-21 13:52:59 -07003580status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3581 sp<IBinder>* outHandle) {
3582 if (!mirrorFromHandle) {
3583 return NAME_NOT_FOUND;
3584 }
3585
3586 sp<Layer> mirrorLayer;
3587 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003588 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003589
3590 {
3591 Mutex::Autolock _l(mStateLock);
3592 mirrorFrom = fromHandle(mirrorFromHandle);
3593 if (!mirrorFrom) {
3594 return NAME_NOT_FOUND;
3595 }
3596
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003597 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3598 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003599 if (result != NO_ERROR) {
3600 return result;
3601 }
3602
3603 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3604 }
3605
3606 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3607}
3608
Marissa Wall2d814fb2019-04-09 18:52:57 +00003609status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3610 uint32_t h, PixelFormat format, uint32_t flags,
3611 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003612 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003613 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3614 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003615 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003616 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003617 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003619 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003620
Robert Carrc0df3122019-04-11 13:18:21 -07003621 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3622 "Expected only one of parentLayer or parentHandle to be non-null. "
3623 "Programmer error?");
3624
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003625 status_t result = NO_ERROR;
3626
3627 sp<Layer> layer;
3628
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003629 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003630
Evan Roskya1f1e152019-01-24 16:17:46 -08003631 bool primaryDisplayOnly = false;
3632
3633 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3634 // TODO b/64227542
3635 if (metadata.has(METADATA_WINDOW_TYPE)) {
3636 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3637 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003638 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003639 primaryDisplayOnly = true;
3640 }
3641 }
3642
Mathias Agopian3165cc22012-08-08 19:42:09 -07003643 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003644 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003645 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3646 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003648 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003649 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003650 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003651 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003652 break;
chaviw13fdc492017-06-27 12:40:18 -07003653 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003654 // check if buffer size is set for color layer.
3655 if (w > 0 || h > 0) {
3656 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3657 int(w), int(h));
3658 return BAD_VALUE;
3659 }
3660
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003661 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3662 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003663 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003664 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003665 // check if buffer size is set for container layer.
3666 if (w > 0 || h > 0) {
3667 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3668 int(w), int(h));
3669 return BAD_VALUE;
3670 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003671 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3672 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003673 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003674 default:
3675 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003676 break;
3677 }
3678
Dan Stoza7d89d062015-04-30 13:29:25 -07003679 if (result != NO_ERROR) {
3680 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003681 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003682
Evan Roskya1f1e152019-01-24 16:17:46 -08003683 if (primaryDisplayOnly) {
3684 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003685 }
3686
Robert Carrb89ea9d2018-12-10 13:01:14 -08003687 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003688 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3689 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003690 if (result != NO_ERROR) {
3691 return result;
3692 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003693 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003694
3695 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003696 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697}
3698
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003699std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3700 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003701
3702 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003703 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003704
Dan Stoza436ccf32018-06-21 12:10:12 -07003705 // Grab the state lock since we're accessing mCurrentState
3706 Mutex::Autolock lock(mStateLock);
3707
Cody Northropbc755282017-03-31 12:00:08 -06003708 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003709 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003710 while (matchFound) {
3711 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003712 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003713 if (layer->getName() == uniqueName) {
3714 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003715 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003716 }
3717 });
3718 }
3719
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003720 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003721 return uniqueName;
3722}
3723
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003724status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003725 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003726 LayerMetadata metadata, PixelFormat& format,
3727 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003728 sp<IGraphicBufferProducer>* gbp,
3729 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003730 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003731 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732 case PIXEL_FORMAT_TRANSPARENT:
3733 case PIXEL_FORMAT_TRANSLUCENT:
3734 format = PIXEL_FORMAT_RGBA_8888;
3735 break;
3736 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003737 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 break;
3739 }
3740
chaviwb4c6e582019-08-16 14:35:07 -07003741 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003742 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003743 args.textureName = getNewTexture();
3744 {
3745 // Grab the SF state lock during this since it's the only safe way to access
3746 // RenderEngine when creating a BufferLayerConsumer
3747 // TODO: Check if this lock is still needed here
3748 Mutex::Autolock lock(mStateLock);
3749 layer = getFactory().createBufferQueueLayer(args);
3750 }
3751
Marissa Wallfd668622018-05-10 10:21:13 -07003752 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003753 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003754 *handle = layer->getHandle();
3755 *gbp = layer->getProducer();
3756 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003758
Marissa Wallfd668622018-05-10 10:21:13 -07003759 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003760 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003761}
3762
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003763status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003764 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003765 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003766 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003767 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003768 args.displayDevice = getDefaultDisplayDevice();
3769 args.textureName = getNewTexture();
3770 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003771 if (outTransformHint) {
3772 *outTransformHint = layer->getTransformHint();
3773 }
Marissa Wall61c58622018-07-18 10:12:20 -07003774 *handle = layer->getHandle();
3775 *outLayer = layer;
3776
3777 return NO_ERROR;
3778}
3779
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003780status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003781 uint32_t h, uint32_t flags, LayerMetadata metadata,
3782 sp<IBinder>* handle, sp<Layer>* outLayer) {
3783 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003784 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003785 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003787}
3788
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003789status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003790 uint32_t w, uint32_t h, uint32_t flags,
3791 LayerMetadata metadata, sp<IBinder>* handle,
3792 sp<Layer>* outLayer) {
3793 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003794 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003795 *handle = (*outLayer)->getHandle();
3796 return NO_ERROR;
3797}
3798
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003799void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003800 mLayersPendingRemoval.add(layer);
3801 mLayersRemoved = true;
3802 setTransactionFlags(eTransactionNeeded);
3803}
3804
Robert Carr695d5282018-12-18 15:27:58 -08003805void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003806{
Robert Carr2e102c92018-10-23 12:11:15 -07003807 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003808 // If a layer has a parent, we allow it to out-live it's handle
3809 // with the idea that the parent holds a reference and will eventually
3810 // be cleaned up. However no one cleans up the top-level so we do so
3811 // here.
3812 if (layer->getParent() == nullptr) {
3813 mCurrentState.layersSortedByZ.remove(layer);
3814 }
3815 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003816
3817 auto it = mLayersByLocalBinderToken.begin();
3818 while (it != mLayersByLocalBinderToken.end()) {
3819 if (it->second == layer) {
3820 it = mLayersByLocalBinderToken.erase(it);
3821 } else {
3822 it++;
3823 }
3824 }
3825
Robert Carr695d5282018-12-18 15:27:58 -08003826 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003827}
3828
Mathias Agopianb60314a2012-04-10 22:09:54 -07003829// ---------------------------------------------------------------------------
3830
Andy McFadden13a082e2012-08-24 10:16:42 -07003831void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003832 const auto display = getDefaultDisplayDeviceLocked();
3833 if (!display) return;
3834
3835 const sp<IBinder> token = display->getDisplayToken().promote();
3836 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003837
Jesse Hall01e29052013-02-19 16:13:35 -08003838 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003839 Vector<ComposerState> state;
3840 Vector<DisplayState> displays;
3841 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003842 d.what = DisplayState::eDisplayProjectionChanged |
3843 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003844 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003845 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003846 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003847 d.frame.makeInvalid();
3848 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003849 d.width = 0;
3850 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003851 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003852 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3853 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003854
Dominik Laskowskie9774092018-12-11 10:04:24 -08003855 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003856
Dominik Laskowski83b88212018-12-11 13:34:06 -08003857 const nsecs_t vsyncPeriod = getVsyncPeriod();
3858 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003859
Brian Andersond0010582017-03-07 13:20:31 -08003860 // Use phase of 0 since phase is not known.
3861 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003862 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003863 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003864}
3865
3866void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003867 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003868 postMessageAsync(
3869 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003870}
3871
Ady Abraham27c70212019-06-11 10:52:26 -07003872void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3873 if (mHWCVsyncState != enabled) {
3874 getHwComposer().setVsyncEnabled(displayId, enabled);
3875 mHWCVsyncState = enabled;
3876 }
3877}
3878
Dominik Laskowskie9774092018-12-11 10:04:24 -08003879void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003880 if (display->isVirtual()) {
3881 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003882 return;
3883 }
3884
Dominik Laskowski075d3172018-05-24 15:50:06 -07003885 const auto displayId = display->getId();
3886 LOG_ALWAYS_FATAL_IF(!displayId);
3887
Dominik Laskowski34157762018-10-31 13:07:19 -07003888 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003889
3890 int currentMode = display->getPowerMode();
3891 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003892 return;
3893 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003894
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895 display->setPowerMode(mode);
3896
Lloyd Pique4dccc412018-01-22 17:21:36 -08003897 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003898 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003899 }
3900
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003902 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003903 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003904 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003905 mScheduler->onScreenAcquired(mAppConnectionHandle);
3906 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003909 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003910 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003911 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003912
3913 struct sched_param param = {0};
3914 param.sched_priority = 1;
3915 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3916 ALOGW("Couldn't set SCHED_FIFO on display on");
3917 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003918 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003919 // Turn off the display
3920 struct sched_param param = {0};
3921 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3922 ALOGW("Couldn't set SCHED_OTHER on display off");
3923 }
3924
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003925 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003926 mScheduler->disableHardwareVsync(true);
3927 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003928 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003929
Ady Abraham27c70212019-06-11 10:52:26 -07003930 // Make sure HWVsync is disabled before turning off the display
3931 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3932
Dominik Laskowski075d3172018-05-24 15:50:06 -07003933 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003934 mVisibleRegionsDirty = true;
3935 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003936 } else if (mode == HWC_POWER_MODE_DOZE ||
3937 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003938 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003939 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003940 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003941 mScheduler->onScreenAcquired(mAppConnectionHandle);
3942 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003943 }
3944 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3945 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003947 mScheduler->disableHardwareVsync(true);
3948 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003949 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003950 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003951 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003952 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003953 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003954 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003955
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003956 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003957 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003958 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003959 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003960 }
3961
Dominik Laskowski34157762018-10-31 13:07:19 -07003962 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003963}
3964
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003965void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003966 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003967 const auto display = getDisplayDevice(displayToken);
3968 if (!display) {
3969 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3970 displayToken.get());
3971 } else if (display->isVirtual()) {
3972 ALOGW("Attempt to set power mode %d for virtual display", mode);
3973 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003974 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003975 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003976 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003977}
3978
3979// ---------------------------------------------------------------------------
3980
Dominik Laskowskic2867142019-01-21 11:33:38 -08003981status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3982 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003983 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003984
Mathias Agopianbd115332013-04-18 16:41:04 -07003985 IPCThreadState* ipc = IPCThreadState::self();
3986 const int pid = ipc->getCallingPid();
3987 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003988
Mathias Agopianbd115332013-04-18 16:41:04 -07003989 if ((uid != AID_SHELL) &&
3990 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003991 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3992 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003994 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003995 // (this would indicate SF is stuck, but we want to be able to
3996 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003997 status_t err = mStateLock.timedLock(s2ns(1));
3998 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003999 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004000 StringAppendF(&result,
4001 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4002 "(no locks held)\n",
4003 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004004 }
4005
Dominik Laskowskic2867142019-01-21 11:33:38 -08004006 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004007 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004008 {"--dispsync"s,
4009 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004010 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004011 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4012 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4013 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4014 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4015 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4016 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004017 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004018 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4019 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004020
Dominik Laskowskic2867142019-01-21 11:33:38 -08004021 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004022
Dominik Laskowski46470112019-08-02 13:13:11 -07004023 const auto it = dumpers.find(flag);
4024 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004025 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004026 } else if (!asProto) {
4027 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004028 }
4029
Mathias Agopian9795c422009-08-26 16:36:26 -07004030 if (locked) {
4031 mStateLock.unlock();
4032 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004033
Dominik Laskowski46470112019-08-02 13:13:11 -07004034 if (it == dumpers.end()) {
4035 const LayersProto layersProto = dumpProtoFromMainThread();
4036 if (asProto) {
4037 result.append(layersProto.SerializeAsString());
4038 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004039 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004040 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4041 result.append(LayerProtoParser::layerTreeToString(layerTree));
4042 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004043 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004044 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004046 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004047 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004048 return NO_ERROR;
4049}
4050
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004051status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4052 if (asProto && mTracing.isEnabled()) {
4053 mTracing.writeToFileAsync();
4054 }
4055
4056 return doDump(fd, DumpArgs(), asProto);
4057}
4058
Dominik Laskowskic2867142019-01-21 11:33:38 -08004059void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004060 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004061 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004062}
4063
Dominik Laskowskic2867142019-01-21 11:33:38 -08004064void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004065 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004066
Dominik Laskowskic2867142019-01-21 11:33:38 -08004067 if (args.size() > 1) {
4068 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004069 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004070 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004071 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004072 }
Robert Carr2047fae2016-11-28 14:09:09 -08004073 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004074 } else {
4075 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004076 }
4077}
4078
Dominik Laskowskic2867142019-01-21 11:33:38 -08004079void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004080 const bool clearAll = args.size() < 2;
4081 const auto name = clearAll ? String8() : String8(args[1]);
4082
Robert Carr2047fae2016-11-28 14:09:09 -08004083 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004084 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004085 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004086 }
Robert Carr2047fae2016-11-28 14:09:09 -08004087 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004088
Svetoslavd85084b2014-03-20 10:28:31 -07004089 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004090}
4091
Dominik Laskowskic2867142019-01-21 11:33:38 -08004092void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4093 mTimeStats->parseArgs(asProto, args, result);
4094}
4095
Jamie Gennis6547ff42013-07-16 20:12:42 -07004096// This should only be called from the main thread. Otherwise it would need
4097// the lock and should use mCurrentState rather than mDrawingState.
4098void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004099 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004100 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004101 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004102
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004103 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004104}
4105
Yiwei Zhang5434a782018-12-05 18:06:32 -08004106void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004107 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004108
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004109 if (isLayerTripleBufferingDisabled())
4110 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004111
Yiwei Zhang5434a782018-12-05 18:06:32 -08004112 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4113 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4114 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4115 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4116 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4117 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004118 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004119}
4120
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004121void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004122 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004123
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004124 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004125 result.append("\n");
4126
Ady Abraham9e16a482019-12-03 17:19:41 -08004127 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004128 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004129 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004130 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004131
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004132 HwcConfigIndexType defaultConfig;
4133 float minFps, maxFps;
4134 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004135 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004136 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004137 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004138 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004139 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4140 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004141
Ana Krulecc2870422019-01-29 19:00:58 -08004142 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004143}
4144
Yiwei Zhang5434a782018-12-05 18:06:32 -08004145void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4146 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004147 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4148 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004149 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004150 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004151 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004152 }
David Sodman4a36e932017-11-07 14:29:47 -08004153 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004154 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004155 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004156 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4157 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004158}
4159
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004160void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4161 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004162 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4163 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004164 for (const auto& segment : history) {
4165 if (!segment.usedThirdBuffer) {
4166 stats.twoBufferTime += segment.totalTime;
4167 }
4168 if (segment.occupancyAverage < 1.0f) {
4169 stats.doubleBufferedTime += segment.totalTime;
4170 } else if (segment.occupancyAverage < 2.0f) {
4171 stats.tripleBufferedTime += segment.totalTime;
4172 }
4173 ++stats.numSegments;
4174 stats.totalTime += segment.totalTime;
4175 }
4176}
4177
Yiwei Zhang5434a782018-12-05 18:06:32 -08004178void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4179 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004180
4181 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4182 const size_t count = currentLayers.size();
4183 for (size_t i=0 ; i<count ; i++) {
4184 currentLayers[i]->dumpFrameEvents(result);
4185 }
4186}
4187
Yiwei Zhang5434a782018-12-05 18:06:32 -08004188void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004189 result.append("Buffering stats:\n");
4190 result.append(" [Layer name] <Active time> <Two buffer> "
4191 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004192 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004193 typedef std::tuple<std::string, float, float, float> BufferTuple;
4194 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004195 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004196 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004197 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004198 if (stats.numSegments == 0) {
4199 continue;
4200 }
4201 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4202 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4203 stats.totalTime;
4204 float doubleBufferRatio = static_cast<float>(
4205 stats.doubleBufferedTime) / stats.totalTime;
4206 float tripleBufferRatio = static_cast<float>(
4207 stats.tripleBufferedTime) / stats.totalTime;
4208 sorted.insert({activeTime, {name, twoBufferRatio,
4209 doubleBufferRatio, tripleBufferRatio}});
4210 }
4211 for (const auto& sortedPair : sorted) {
4212 float activeTime = sortedPair.first;
4213 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004214 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4215 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004216 }
4217 result.append("\n");
4218}
4219
Yiwei Zhang5434a782018-12-05 18:06:32 -08004220void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004221 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004222 const auto displayId = display->getId();
4223 if (!displayId) {
4224 continue;
4225 }
4226 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004227 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004228 continue;
4229 }
4230
Yiwei Zhang5434a782018-12-05 18:06:32 -08004231 StringAppendF(&result,
4232 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4233 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004234 uint8_t port;
4235 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004236 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004237 result.append("no identification data\n");
4238 continue;
4239 }
4240
4241 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004242 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004243 continue;
4244 }
4245
4246 const auto edid = parseEdid(data);
4247 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004248 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004249 continue;
4250 }
4251
Yiwei Zhang5434a782018-12-05 18:06:32 -08004252 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004253 result.append(edid->displayName.data(), edid->displayName.length());
4254 result.append("\"\n");
4255 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004256}
4257
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004258void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4259 std::string& result) const {
4260 hwc2_display_t hwcDisplayId;
4261 uint8_t port;
4262 DisplayIdentificationData data;
4263
4264 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4265 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4266 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4267 }
4268}
4269
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004271 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004272 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4273 StringAppendF(&result, "DisplayColorSetting: %s\n",
4274 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004275
4276 // TODO: print out if wide-color mode is active or not
4277
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004278 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004279 const auto displayId = display->getId();
4280 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004281 continue;
4282 }
4283
Yiwei Zhang5434a782018-12-05 18:06:32 -08004284 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004285 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004286 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004287 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004288 }
4289
Lloyd Pique32cbe282018-10-19 13:09:22 -07004290 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004291 StringAppendF(&result, " Current color mode: %s (%d)\n",
4292 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004293 }
4294 result.append("\n");
4295}
4296
Vishnu Nair8406fd72019-07-30 11:29:31 -07004297LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004298 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004299 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4300 layer->writeToProto(layersProto, traceFlags);
4301 }
chaviw1d044282017-09-27 12:19:28 -07004302 return layersProto;
4303}
4304
Vishnu Nair0f085c62019-08-30 08:49:12 -07004305void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4306 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4307 // it.
4308 LayerProto* rootProto = layersProto.add_layers();
4309 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4310 rootProto->set_id(offscreenRootLayerId);
4311 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004312 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004313
4314 for (Layer* offscreenLayer : mOffscreenLayers) {
4315 // Add layer as child of the fake root
4316 rootProto->add_children(offscreenLayer->sequence);
4317
4318 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004319 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004320 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004321 }
4322}
4323
Vishnu Nair8406fd72019-07-30 11:29:31 -07004324LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4325 LayersProto layersProto;
4326 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4327 return layersProto;
4328}
4329
Vishnu Nair0f085c62019-08-30 08:49:12 -07004330void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4331 result.append("Offscreen Layers:\n");
4332 postMessageSync(new LambdaMessage([&]() {
4333 for (Layer* offscreenLayer : mOffscreenLayers) {
4334 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4335 layer->dumpCallingUidPid(result);
4336 });
4337 }
4338 }));
4339}
4340
Dominik Laskowskic2867142019-01-21 11:33:38 -08004341void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4342 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 Colorizer colorizer(colorize);
4344
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345 // figure out if we're stuck somewhere
4346 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004347 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4349
4350 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004351 * Dump library configuration.
4352 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004353
4354 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004355 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004357 appendSfConfigString(result);
4358 appendUiConfigString(result);
4359 appendGuiConfigString(result);
4360 result.append("\n");
4361
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004362 result.append("\nDisplay identification data:\n");
4363 dumpDisplayIdentificationData(result);
4364
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004365 result.append("\nWide-Color information:\n");
4366 dumpWideColorInfo(result);
4367
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004368 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004369 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004370 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004371 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004372 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004373
Andy McFadden41d67d72014-04-25 16:58:34 -07004374 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004375 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004376 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004377 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004378 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004379
Dan Stozab90cf072015-03-05 11:05:59 -08004380 dumpStaticScreenStats(result);
4381 result.append("\n");
4382
Alec Mouri40189b02019-03-05 15:07:54 -08004383 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4384 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4385 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004386
Dan Stozae77c7662016-05-13 11:37:28 -07004387 dumpBufferingStats(result);
4388
Andy McFadden4803b742012-09-24 19:07:20 -07004389 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 * Dump the visible layer list
4391 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004392 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004393 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4395 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004396 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004397
Chia-I Wu2f884132018-09-13 15:17:58 -07004398 {
Lloyd Pique207def92019-02-28 16:09:52 -08004399 StringAppendF(&result, "Composition layers\n");
4400 mDrawingState.traverseInZOrder([&](Layer* layer) {
4401 auto compositionLayer = layer->getCompositionLayer();
4402 if (compositionLayer) compositionLayer->dump(result);
4403 });
4404 }
4405
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004407 * Dump Display state
4408 */
4409
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004410 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004412 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004413 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004414 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004415 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004416 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004417
4418 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004419 * Dump CompositionEngine state
4420 */
4421
4422 mCompositionEngine->dump(result);
4423
4424 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425 * Dump SurfaceFlinger global state
4426 */
4427
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004429 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004430 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004431
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004432 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004433
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004434 DebugEGLImageTracker::getInstance()->dump(result);
4435
Dominik Laskowski075d3172018-05-24 15:50:06 -07004436 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004437 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4438 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004439 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4440 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004441 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 StringAppendF(&result,
4443 " transaction-flags : %08x\n"
4444 " gpu_to_cpu_unsupported : %d\n",
4445 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004446
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004447 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004448 displayId && getHwComposer().isConnected(*displayId)) {
4449 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004450 StringAppendF(&result,
4451 " refresh-rate : %f fps\n"
4452 " x-dpi : %f\n"
4453 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004454 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4455 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004456 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459
Dan Stozae22aec72016-08-01 13:20:59 -07004460 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004461 * Tracing state
4462 */
4463 mTracing.dump(result);
4464 result.append("\n");
4465
4466 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004467 * HWC layer minidump
4468 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004469 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004470 const auto displayId = display->getId();
4471 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004472 continue;
4473 }
4474
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004476 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004477 const sp<DisplayDevice> displayDevice = display;
4478 mCurrentState.traverseInZOrder(
4479 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004480 result.append("\n");
4481 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004482
4483 /*
4484 * Dump HWComposer state
4485 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004486 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004487 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004489 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004490 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004491 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004492
4493 /*
4494 * Dump gralloc state
4495 */
4496 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4497 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004498
4499 /*
4500 * Dump VrFlinger state if in use.
4501 */
4502 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4503 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004505 result.append("\n");
4506 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004507
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004508 result.append(mTimeStats->miniDump());
4509 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004510}
4511
Chia-I Wu28f320b2018-05-03 11:02:56 -07004512void SurfaceFlinger::updateColorMatrixLocked() {
4513 mat4 colorMatrix;
4514 if (mGlobalSaturationFactor != 1.0f) {
4515 // Rec.709 luma coefficients
4516 float3 luminance{0.213f, 0.715f, 0.072f};
4517 luminance *= 1.0f - mGlobalSaturationFactor;
4518 mat4 saturationMatrix = mat4(
4519 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4520 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4521 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4522 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4523 );
4524 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4525 } else {
4526 colorMatrix = mClientColorMatrix * mDaltonizer();
4527 }
4528
4529 if (mCurrentState.colorMatrix != colorMatrix) {
4530 mCurrentState.colorMatrix = colorMatrix;
4531 mCurrentState.colorMatrixChanged = true;
4532 setTransactionFlags(eTransactionNeeded);
4533 }
4534}
4535
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004536status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004537#pragma clang diagnostic push
4538#pragma clang diagnostic error "-Wswitch-enum"
4539 switch (static_cast<ISurfaceComposerTag>(code)) {
4540 // These methods should at minimum make sure that the client requested
4541 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004542 case BOOT_FINISHED:
4543 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004544 case CREATE_DISPLAY:
4545 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004546 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004547 case GET_ANIMATION_FRAME_STATS:
4548 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004549 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004550 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004551 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004552 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4553 case SET_AUTO_LOW_LATENCY_MODE:
4554 case GET_GAME_CONTENT_TYPE_SUPPORT:
4555 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004556 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004557 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004558 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004559 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004560 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004561 case NOTIFY_POWER_HINT:
4562 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004563 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4564 IPCThreadState* ipc = IPCThreadState::self();
4565 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4566 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004567 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 }
Robert Carr1db73f62016-12-21 12:58:51 -08004569 return OK;
4570 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004571 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004572 IPCThreadState* ipc = IPCThreadState::self();
4573 const int pid = ipc->getCallingPid();
4574 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004575 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4576 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004577 return PERMISSION_DENIED;
4578 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004579 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004580 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004581 // Used by apps to hook Choreographer to SurfaceFlinger.
4582 case CREATE_DISPLAY_EVENT_CONNECTION:
4583 // The following calls are currently used by clients that do not
4584 // request necessary permissions. However, they do not expose any secret
4585 // information, so it is OK to pass them.
4586 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004587 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004588 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004589 case GET_PHYSICAL_DISPLAY_IDS:
4590 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004591 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004592 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004593 case GET_DISPLAY_CONFIGS:
4594 case GET_DISPLAY_STATS:
4595 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4596 // Calling setTransactionState is safe, because you need to have been
4597 // granted a reference to Client* and Handle* to do anything with it.
4598 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004599 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004600 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004601 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004602 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004603 case IS_WIDE_COLOR_DISPLAY:
4604 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4605 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004606 return OK;
4607 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004608 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004609 case CAPTURE_SCREEN:
4610 case ADD_REGION_SAMPLING_LISTENER:
4611 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004612 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004613 IPCThreadState* ipc = IPCThreadState::self();
4614 const int pid = ipc->getCallingPid();
4615 const int uid = ipc->getCallingUid();
4616 if ((uid != AID_GRAPHICS) &&
4617 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4618 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4619 return PERMISSION_DENIED;
4620 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004621 return OK;
4622 }
4623 // The following codes are deprecated and should never be allowed to access SF.
4624 case CONNECT_DISPLAY_UNUSED:
4625 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4626 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4627 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004628 }
chaviw93df2ea2019-04-30 16:45:12 -07004629 case CAPTURE_SCREEN_BY_ID: {
4630 IPCThreadState* ipc = IPCThreadState::self();
4631 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004632 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004633 return OK;
4634 }
4635 return PERMISSION_DENIED;
4636 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004637 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004638
4639 // These codes are used for the IBinder protocol to either interrogate the recipient
4640 // side of the transaction for its canonical interface descriptor or to dump its state.
4641 // We let them pass by default.
4642 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4643 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4644 code == IBinder::SYSPROPS_TRANSACTION) {
4645 return OK;
4646 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004647 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004648 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004649 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004650 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4651 return OK;
4652 }
4653 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4654 return PERMISSION_DENIED;
4655#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004656}
4657
Ana Krulec13be8ad2018-08-21 02:43:56 +00004658status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4659 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004660 status_t credentialCheck = CheckTransactCodeCredentials(code);
4661 if (credentialCheck != OK) {
4662 return credentialCheck;
4663 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004665 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4666 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004667 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004668 IPCThreadState* ipc = IPCThreadState::self();
4669 const int uid = ipc->getCallingUid();
4670 if (CC_UNLIKELY(uid != AID_SYSTEM
4671 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004672 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004673 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004674 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004675 return PERMISSION_DENIED;
4676 }
4677 int n;
4678 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004679 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004680 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004681 return NO_ERROR;
4682 case 1002: // SHOW_UPDATES
4683 n = data.readInt32();
4684 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004685 invalidateHwcGeometry();
4686 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004688 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004689 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004690 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004692 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004693 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004694 setTransactionFlags(
4695 eTransactionNeeded|
4696 eDisplayTransactionNeeded|
4697 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004698 return NO_ERROR;
4699 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004700 case 1006:{ // send empty update
4701 signalRefresh();
4702 return NO_ERROR;
4703 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004704 case 1008: // toggle use of hw composer
4705 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004706 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004707 invalidateHwcGeometry();
4708 repaintEverything();
4709 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004710 case 1009: // toggle use of transform hint
4711 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004712 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004713 invalidateHwcGeometry();
4714 repaintEverything();
4715 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004716 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004717 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004718 reply->writeInt32(0);
4719 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004720 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004721 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004722 return NO_ERROR;
4723 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004724 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004725 if (!display) {
4726 return NAME_NOT_FOUND;
4727 }
4728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004729 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004730 return NO_ERROR;
4731 }
4732 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004733 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004734 // daltonize
4735 n = data.readInt32();
4736 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004737 case 1:
4738 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4739 break;
4740 case 2:
4741 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4742 break;
4743 case 3:
4744 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4745 break;
4746 default:
4747 mDaltonizer.setType(ColorBlindnessType::None);
4748 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004749 }
4750 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004751 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004752 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004753 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004754 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004755
4756 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004757 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004758 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004759 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004760 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004761 // apply a color matrix
4762 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004763 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004764 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004765 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004766 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004767 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004768 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004769 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004770 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004771 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004772 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004773
4774 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4775 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004776 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004777 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4778 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4779 }
4780
Chia-I Wu28f320b2018-05-03 11:02:56 -07004781 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004782 return NO_ERROR;
4783 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004784 case 1016: { // Unused.
4785 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004786 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004787 case 1017: {
4788 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004789 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004790 return NO_ERROR;
4791 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004792 case 1018: { // Modify Choreographer's phase offset
4793 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004794 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004795 return NO_ERROR;
4796 }
4797 case 1019: { // Modify SurfaceFlinger's phase offset
4798 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004799 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004800 return NO_ERROR;
4801 }
Irvel468051e2016-06-13 16:44:44 -07004802 case 1020: { // Layer updates interceptor
4803 n = data.readInt32();
4804 if (n) {
4805 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004806 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004807 }
4808 else{
4809 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004810 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004811 }
4812 return NO_ERROR;
4813 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004814 case 1021: { // Disable HWC virtual displays
4815 n = data.readInt32();
4816 mUseHwcVirtualDisplays = !n;
4817 return NO_ERROR;
4818 }
Romain Guy0147a172017-06-01 13:53:56 -07004819 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004820 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004821 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004822
Chia-I Wu28f320b2018-05-03 11:02:56 -07004823 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004824 return NO_ERROR;
4825 }
Romain Guy54f154a2017-10-24 21:40:32 +01004826 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004827 int32_t colorMode;
4828
Chia-I Wu0d711262018-05-21 15:19:35 -07004829 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004830 if (data.readInt32(&colorMode) == NO_ERROR) {
4831 mForceColorMode = static_cast<ColorMode>(colorMode);
4832 }
Romain Guy54f154a2017-10-24 21:40:32 +01004833 invalidateHwcGeometry();
4834 repaintEverything();
4835 return NO_ERROR;
4836 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004837 // Deprecate, use 1030 to check whether the device is color managed.
4838 case 1024: {
4839 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004840 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004841 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004842 n = data.readInt32();
4843 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004844 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004845 Mutex::Autolock lock(mStateLock);
4846 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004847 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004848 reply->writeInt32(NO_ERROR);
4849 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004850 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004851 bool writeFile = false;
4852 {
4853 Mutex::Autolock lock(mStateLock);
4854 mTracingEnabledChanged = true;
4855 writeFile = mTracing.disable();
4856 }
4857
4858 if (writeFile) {
4859 reply->writeInt32(mTracing.writeToFile());
4860 } else {
4861 reply->writeInt32(NO_ERROR);
4862 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004863 }
4864 return NO_ERROR;
4865 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004866 case 1026: { // Get layer tracing status
4867 reply->writeBool(mTracing.isEnabled());
4868 return NO_ERROR;
4869 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004870 // Is a DisplayColorSetting supported?
4871 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004872 const auto display = getDefaultDisplayDevice();
4873 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004874 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004875 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004876
4877 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4878 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004879 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004880 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004881 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004882 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004883 reply->writeBool(true);
4884 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004885 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004886 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004887 break;
4888 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004889 reply->writeBool(
4890 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004891 break;
4892 }
4893 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004894 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004895 // Is VrFlinger active?
4896 case 1028: {
4897 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004898 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004899 return NO_ERROR;
4900 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004901 // Set buffer size for SF tracing (value in KB)
4902 case 1029: {
4903 n = data.readInt32();
4904 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4905 ALOGW("Invalid buffer size: %d KB", n);
4906 reply->writeInt32(BAD_VALUE);
4907 return BAD_VALUE;
4908 }
4909
4910 ALOGD("Updating trace buffer to %d KB", n);
4911 mTracing.setBufferSize(n * 1024);
4912 reply->writeInt32(NO_ERROR);
4913 return NO_ERROR;
4914 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004915 // Is device color managed?
4916 case 1030: {
4917 reply->writeBool(useColorManagement);
4918 return NO_ERROR;
4919 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004920 // Override default composition data space
4921 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4922 // && adb shell stop zygote && adb shell start zygote
4923 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4924 // adb shell stop zygote && adb shell start zygote
4925 case 1031: {
4926 Mutex::Autolock _l(mStateLock);
4927 n = data.readInt32();
4928 if (n) {
4929 n = data.readInt32();
4930 if (n) {
4931 Dataspace dataspace = static_cast<Dataspace>(n);
4932 if (!validateCompositionDataspace(dataspace)) {
4933 return BAD_VALUE;
4934 }
4935 mDefaultCompositionDataspace = dataspace;
4936 }
4937 n = data.readInt32();
4938 if (n) {
4939 Dataspace dataspace = static_cast<Dataspace>(n);
4940 if (!validateCompositionDataspace(dataspace)) {
4941 return BAD_VALUE;
4942 }
4943 mWideColorGamutCompositionDataspace = dataspace;
4944 }
4945 } else {
4946 // restore composition data space.
4947 mDefaultCompositionDataspace = defaultCompositionDataspace;
4948 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4949 }
4950 return NO_ERROR;
4951 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004952 // Set trace flags
4953 case 1033: {
4954 n = data.readUint32();
4955 ALOGD("Updating trace flags to 0x%x", n);
4956 mTracing.setTraceFlags(n);
4957 reply->writeInt32(NO_ERROR);
4958 return NO_ERROR;
4959 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004960 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004961 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004962 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004963 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004964 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4965 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004966 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004967 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004968 } else {
4969 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004970 }
4971 return NO_ERROR;
4972 }
Ady Abraham34392f72019-04-10 11:29:27 -07004973 case 1035: {
4974 n = data.readInt32();
4975 mDebugDisplayConfigSetByBackdoor = false;
4976 if (n >= 0) {
4977 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004978 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004979 if (result != NO_ERROR) {
4980 return result;
4981 }
4982 mDebugDisplayConfigSetByBackdoor = true;
4983 }
4984 return NO_ERROR;
4985 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 }
4987 }
4988 return err;
4989}
4990
Steven Thomas6d8110b2017-08-31 18:24:21 -07004991void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004992 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004993 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004994}
4995
Ana Krulec7d1d6832018-12-27 11:10:09 -08004996void SurfaceFlinger::repaintEverythingForHWC() {
4997 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004998 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004999}
5000
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005001// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5002class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005003public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005004 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5005 ~WindowDisconnector() {
5006 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005007 }
5008
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005009private:
5010 ANativeWindow* mWindow;
5011 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005012};
5013
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005014status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005015 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005016 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5017 const Rect& sourceCrop, uint32_t reqWidth,
5018 uint32_t reqHeight, bool useIdentityTransform,
5019 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005020 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005022 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005023
Dominik Laskowski718f9602019-11-09 20:01:35 -08005024 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5025 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5026 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5027 renderAreaRotation = ui::Transform::ROT_0;
5028 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005029
Chia-I Wu20261cb2018-08-23 12:55:44 -07005030 sp<DisplayDevice> display;
5031 {
5032 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005033
Chia-I Wu20261cb2018-08-23 12:55:44 -07005034 display = getDisplayDeviceLocked(displayToken);
5035 if (!display) return BAD_VALUE;
5036
Chia-I Wucb023152018-08-28 12:57:23 -07005037 // set the requested width/height to the logical display viewport size
5038 // by default
5039 if (reqWidth == 0 || reqHeight == 0) {
5040 reqWidth = uint32_t(display->getViewport().width());
5041 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005042 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005043 }
5044
Peiyong Lin0e003c92018-09-17 11:09:51 -07005045 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005046 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005047
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005048 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5049 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005050 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005051 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005052}
5053
chaviw93df2ea2019-04-30 16:45:12 -07005054static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5055 switch (colorMode) {
5056 case ColorMode::DISPLAY_P3:
5057 case ColorMode::BT2100_PQ:
5058 case ColorMode::BT2100_HLG:
5059 case ColorMode::DISPLAY_BT2020:
5060 return Dataspace::DISPLAY_P3;
5061 default:
5062 return Dataspace::V0_SRGB;
5063 }
5064}
5065
5066const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5067 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5068 if (displayToken) {
5069 return getDisplayDeviceLocked(displayToken);
5070 }
5071 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5072 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005073 return getDisplayByLayerStack(displayOrLayerStack);
5074}
5075
5076const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005077 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005078 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005079 return display;
5080 }
5081 }
5082 return nullptr;
5083}
5084
5085status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5086 sp<GraphicBuffer>* outBuffer) {
5087 sp<DisplayDevice> display;
5088 uint32_t width;
5089 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005090 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005091 {
5092 Mutex::Autolock _l(mStateLock);
5093 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5094 if (!display) {
5095 return BAD_VALUE;
5096 }
5097
5098 width = uint32_t(display->getViewport().width());
5099 height = uint32_t(display->getViewport().height());
5100
Dominik Laskowski718f9602019-11-09 20:01:35 -08005101 const auto orientation = display->getOrientation();
5102 captureOrientation = ui::Transform::toRotationFlags(orientation);
5103
5104 switch (captureOrientation) {
5105 case ui::Transform::ROT_90:
5106 captureOrientation = ui::Transform::ROT_270;
5107 break;
5108
5109 case ui::Transform::ROT_270:
5110 captureOrientation = ui::Transform::ROT_90;
5111 break;
5112
5113 case ui::Transform::ROT_INVALID:
5114 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5115 captureOrientation = ui::Transform::ROT_0;
5116 break;
5117
5118 default:
5119 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005120 }
chaviw93df2ea2019-04-30 16:45:12 -07005121 *outDataspace =
5122 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5123 }
5124
5125 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5126 false /* captureSecureLayers */);
5127
5128 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5129 std::placeholders::_1);
5130 bool ignored = false;
5131 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5132 false /* useIdentityTransform */,
5133 ignored /* outCapturedSecureLayers */);
5134}
5135
Robert Carr866455f2019-04-02 16:28:26 -07005136status_t SurfaceFlinger::captureLayers(
5137 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5138 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5139 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5140 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005141 ATRACE_CALL();
5142
5143 class LayerRenderArea : public RenderArea {
5144 public:
Robert Carr578038f2018-03-09 12:25:24 -08005145 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005146 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005147 bool childrenOnly, const Rect& displayViewport)
5148 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005149 mLayer(layer),
5150 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005151 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005152 mFlinger(flinger),
5153 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005154 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005155 Rect getBounds() const override {
5156 const Layer::State& layerState(mLayer->getDrawingState());
5157 return mLayer->getBufferSize(layerState);
5158 }
Marissa Wall61c58622018-07-18 10:12:20 -07005159 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005160 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005161 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005162 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005163 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005164 }
chaviwa76b2712017-09-20 12:02:26 -07005165 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005166 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005167 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005168 Rect getSourceCrop() const override {
5169 if (mCrop.isEmpty()) {
5170 return getBounds();
5171 } else {
5172 return mCrop;
5173 }
5174 }
Robert Carr578038f2018-03-09 12:25:24 -08005175 class ReparentForDrawing {
5176 public:
5177 const sp<Layer>& oldParent;
5178 const sp<Layer>& newParent;
5179
Vishnu Nair4351ad52019-02-11 14:13:02 -08005180 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5181 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005182 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005183 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005184 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5185 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005186 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005187 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005188 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005189 };
5190
5191 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005192 const Rect sourceCrop = getSourceCrop();
5193 // no need to check rotation because there is none
5194 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5195 sourceCrop.height() != getReqHeight();
5196
Robert Carr578038f2018-03-09 12:25:24 -08005197 if (!mChildrenOnly) {
5198 mTransform = mLayer->getTransform().inverse();
5199 drawLayers();
5200 } else {
5201 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005202 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5203 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005204 // In the "childrenOnly" case we reparent the children to a screenshot
5205 // layer which has no properties set and which does not draw.
5206 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005207 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5208 "Screenshot Parent"s, w, h, 0,
5209 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005210
Vishnu Nair4351ad52019-02-11 14:13:02 -08005211 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005212 drawLayers();
5213 }
5214 }
chaviwa76b2712017-09-20 12:02:26 -07005215
chaviwa76b2712017-09-20 12:02:26 -07005216 private:
chaviw7206d492017-11-10 16:16:12 -08005217 const sp<Layer> mLayer;
5218 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005219
Peiyong Linefefaac2018-08-17 12:27:51 -07005220 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005221 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005222
5223 SurfaceFlinger* mFlinger;
5224 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005225 };
5226
Robert Carrc0df3122019-04-11 13:18:21 -07005227 int reqWidth = 0;
5228 int reqHeight = 0;
5229 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005230 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005231 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005232 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005233 {
5234 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005235
Robert Carrc0df3122019-04-11 13:18:21 -07005236 parent = fromHandle(layerHandleBinder);
5237 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5238 ALOGE("captureLayers called with an invalid or removed parent");
5239 return NAME_NOT_FOUND;
5240 }
5241
5242 const int uid = IPCThreadState::self()->getCallingUid();
5243 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5244 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5245 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5246 return PERMISSION_DENIED;
5247 }
5248
Vishnu Nairefc42e22019-12-03 17:36:12 -08005249 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005250 if (sourceCrop.width() <= 0) {
5251 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005252 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005253 }
5254
5255 if (sourceCrop.height() <= 0) {
5256 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005257 crop.bottom = parentSourceBounds.getHeight();
5258 }
5259
5260 if (crop.isEmpty() || frameScale <= 0.0f) {
5261 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5262 // crop was not specified, or an invalid frame scale was provided.
5263 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005264 }
5265 reqWidth = crop.width() * frameScale;
5266 reqHeight = crop.height() * frameScale;
5267
5268 for (const auto& handle : excludeHandles) {
5269 sp<Layer> excludeLayer = fromHandle(handle);
5270 if (excludeLayer != nullptr) {
5271 excludeLayers.emplace(excludeLayer);
5272 } else {
5273 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5274 return NAME_NOT_FOUND;
5275 }
5276 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005277
5278 auto display = getDisplayByLayerStack(parent->getLayerStack());
5279 if (!display) {
5280 return BAD_VALUE;
5281 }
5282
5283 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005284 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005285
Chia-I Wu20261cb2018-08-23 12:55:44 -07005286 // really small crop or frameScale
5287 if (reqWidth <= 0) {
5288 reqWidth = 1;
5289 }
5290 if (reqHeight <= 0) {
5291 reqHeight = 1;
5292 }
5293
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005294 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5295 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005296 auto traverseLayers = [parent, childrenOnly,
5297 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005298 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5299 if (!layer->isVisible()) {
5300 return;
Robert Carr578038f2018-03-09 12:25:24 -08005301 } else if (childrenOnly && layer == parent.get()) {
5302 return;
chaviwa76b2712017-09-20 12:02:26 -07005303 }
Robert Carr866455f2019-04-02 16:28:26 -07005304
5305 sp<Layer> p = layer;
5306 while (p != nullptr) {
5307 if (excludeLayers.count(p) != 0) {
5308 return;
5309 }
5310 p = p->getParent();
5311 }
5312
chaviwa76b2712017-09-20 12:02:26 -07005313 visitor(layer);
5314 });
5315 };
Robert Carr108b2c72019-04-02 16:32:58 -07005316
5317 bool outCapturedSecureLayers = false;
5318 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5319 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005320}
5321
5322status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5323 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005324 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005325 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005326 bool useIdentityTransform,
5327 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005328 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005329
Peiyong Lin0e003c92018-09-17 11:09:51 -07005330 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005331 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5332 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005333 *outBuffer =
5334 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5335 static_cast<android_pixel_format>(reqPixelFormat), 1,
5336 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005337
Robert Carr108b2c72019-04-02 16:32:58 -07005338 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5339 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005340}
5341
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005342status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5343 TraverseLayersFunction traverseLayers,
5344 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005345 bool useIdentityTransform,
5346 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005347 // This mutex protects syncFd and captureResult for communication of the return values from the
5348 // main thread back to this Binder thread
5349 std::mutex captureMutex;
5350 std::condition_variable captureCondition;
5351 std::unique_lock<std::mutex> captureLock(captureMutex);
5352 int syncFd = -1;
5353 std::optional<status_t> captureResult;
5354
Robert Carr03480e22018-01-04 16:02:06 -08005355 const int uid = IPCThreadState::self()->getCallingUid();
5356 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5357
Dominik Laskowski8c001672018-05-30 16:52:06 -07005358 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005359 // If there is a refresh pending, bug out early and tell the binder thread to try again
5360 // after the refresh.
5361 if (mRefreshPending) {
5362 ATRACE_NAME("Skipping screenshot for now");
5363 std::unique_lock<std::mutex> captureLock(captureMutex);
5364 captureResult = std::make_optional<status_t>(EAGAIN);
5365 captureCondition.notify_one();
5366 return;
5367 }
5368
5369 status_t result = NO_ERROR;
5370 int fd = -1;
5371 {
5372 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005373 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005374 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005375 useIdentityTransform, forSystem, &fd,
5376 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005377 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005378 }
5379
5380 {
5381 std::unique_lock<std::mutex> captureLock(captureMutex);
5382 syncFd = fd;
5383 captureResult = std::make_optional<status_t>(result);
5384 captureCondition.notify_one();
5385 }
5386 });
5387
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005388 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005389 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005390 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005391 while (*captureResult == EAGAIN) {
5392 captureResult.reset();
5393 result = postMessageAsync(message);
5394 if (result != NO_ERROR) {
5395 return result;
5396 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005397 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005398 }
5399 result = *captureResult;
5400 }
5401
5402 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005403 sync_wait(syncFd, -1);
5404 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005405 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005406
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005407 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005408}
5409
chaviwa76b2712017-09-20 12:02:26 -07005410void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005411 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005412 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5413 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005414 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005415
chaviwa76b2712017-09-20 12:02:26 -07005416 const auto reqWidth = renderArea.getReqWidth();
5417 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005418 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005419 const auto transform = renderArea.getTransform();
5420 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005421 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005422
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005423 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005424 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005425
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005426 // assume that bounds are never offset, and that they are the same as the
5427 // buffer bounds.
5428 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005429 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005430 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005431
5432 // Now take into account the rotation flag. We append a transform that
5433 // rotates the layer stack about the origin, then translate by buffer
5434 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005435 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005436 int displacementX = 0;
5437 int displacementY = 0;
5438 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5439 switch (rotation) {
5440 case ui::Transform::ROT_90:
5441 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005442 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005443 break;
5444 case ui::Transform::ROT_180:
5445 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005446 displacementY = renderArea.getBounds().getWidth();
5447 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005448 break;
5449 case ui::Transform::ROT_270:
5450 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005451 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005452 break;
5453 default:
5454 break;
5455 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005456
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005457 // We need to transform the clipping window into the right spot.
5458 // First, rotate the clipping rectangle by the rotation hint to get the
5459 // right orientation
5460 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5461 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5462 const vec4 rotClipTL = rotMatrix * clipTL;
5463 const vec4 rotClipBR = rotMatrix * clipBR;
5464 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5465 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5466 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5467 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5468
5469 // Now reposition the clipping rectangle with the displacement vector
5470 // computed above.
5471 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005472 clientCompositionDisplay.clip =
5473 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5474 newClipRight + displacementX, newClipBottom + displacementY);
5475
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005476 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005477 clientCompositionDisplay.globalTransform =
5478 clipTransform * clientCompositionDisplay.globalTransform;
5479
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005480 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5481 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005482
chaviw50da5042018-04-09 13:49:37 -07005483 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005484
Vishnu Nair9b079a22020-01-21 14:36:08 -08005485 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005486 fillLayer.source.buffer.buffer = nullptr;
5487 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5488 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5489 fillLayer.alpha = half(alpha);
5490 clientCompositionLayers.push_back(fillLayer);
5491
5492 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005493 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005494 const bool supportProtectedContent = false;
5495 Region clip(renderArea.getBounds());
5496 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5497 clip,
5498 useIdentityTransform,
5499 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5500 renderArea.isSecure(),
5501 supportProtectedContent,
5502 clearRegion,
5503 };
5504 auto result = layer->prepareClientComposition(targetSettings);
5505 if (result) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08005506 std::optional<compositionengine::LayerFE::LayerSettings> shadowLayer =
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005507 layer->prepareShadowClientComposition(*result, displayViewport,
5508 clientCompositionDisplay.outputDataspace);
5509 if (shadowLayer) {
5510 clientCompositionLayers.push_back(*shadowLayer);
5511 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005512 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005513 }
chaviwa76b2712017-09-20 12:02:26 -07005514 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005515
Vishnu Nair9b079a22020-01-21 14:36:08 -08005516 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5517 clientCompositionLayers.reserve(clientCompositionLayers.size());
5518 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5519 std::back_inserter(clientCompositionLayerPointers),
5520 [](compositionengine::LayerFE::LayerSettings& settings)
5521 -> renderengine::LayerSettings* { return &settings; });
5522
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005523 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005524 // Use an empty fence for the buffer fence, since we just created the buffer so
5525 // there is no need for synchronization with the GPU.
5526 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005527 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005528 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005529 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005530 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005531
5532 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005533}
5534
chaviwa76b2712017-09-20 12:02:26 -07005535status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5536 TraverseLayersFunction traverseLayers,
5537 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005538 bool useIdentityTransform, bool forSystem,
5539 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005540 ATRACE_CALL();
5541
chaviwa76b2712017-09-20 12:02:26 -07005542 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005543 outCapturedSecureLayers =
5544 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005545 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005546
Robert Carr03480e22018-01-04 16:02:06 -08005547 // We allow the system server to take screenshots of secure layers for
5548 // use in situations like the Screen-rotation animation and place
5549 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005550 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005551 ALOGW("FB is protected: PERMISSION_DENIED");
5552 return PERMISSION_DENIED;
5553 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005554 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005555 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005556}
5557
chaviw95ef3c42019-02-14 10:55:09 -08005558void SurfaceFlinger::setInputWindowsFinished() {
5559 Mutex::Autolock _l(mStateLock);
5560
5561 mPendingSyncInputWindows = false;
5562 mTransactionCV.broadcast();
5563}
chaviw5f21a5e2019-02-14 10:00:34 -08005564
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005565// ---------------------------------------------------------------------------
5566
Dan Stoza412903f2017-04-27 13:42:17 -07005567void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5568 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005569}
5570
Dan Stoza412903f2017-04-27 13:42:17 -07005571void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5572 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005573}
5574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005575void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005576 const LayerVector::Visitor& visitor) {
5577 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005578 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005579 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005580 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005581 continue;
5582 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005583 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005584 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005585 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005586 return;
5587 }
chaviwa76b2712017-09-20 12:02:26 -07005588 if (!layer->isVisible()) {
5589 return;
5590 }
5591 visitor(layer);
5592 });
5593 }
5594}
5595
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005596status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5597 HwcConfigIndexType defaultConfig,
5598 float minRefreshRate,
5599 float maxRefreshRate) {
5600 Mutex::Autolock lock(mStateLock);
5601
Dominik Laskowski22488f62019-03-28 09:53:04 -07005602 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005603 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5604 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5605 // it should go thru setDesiredActiveConfig, similar to primary display.
5606 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5607 const auto displayId = display->getId();
5608 LOG_ALWAYS_FATAL_IF(!displayId);
5609
5610 HWC2::VsyncPeriodChangeConstraints constraints;
5611 constraints.desiredTimeNanos = systemTime();
5612 constraints.seamlessRequired = false;
5613
5614 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005615 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5616 constraints, &timeline) < 0) {
5617 return BAD_VALUE;
5618 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005619 if (timeline.refreshRequired) {
5620 repaintEverythingForHWC();
5621 }
5622
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005623 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005624 display->setActiveConfig(configId);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005625 const nsecs_t vsyncPeriod =
5626 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).vsyncPeriod;
5627 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId,
5628 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005629 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005630 }
5631
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005632 if (mDebugDisplayConfigSetByBackdoor) {
5633 // ignore this request as config is overridden by backdoor
5634 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005635 }
5636
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005637 bool policyChanged;
5638 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5639 &policyChanged) < 0) {
5640 return BAD_VALUE;
5641 }
5642 if (!policyChanged) {
5643 return NO_ERROR;
5644 }
5645
5646 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5647 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005648
5649 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5650 // that listeners that care about a change in allowed configs can get the notification.
5651 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005652 const nsecs_t vsyncPeriod =
5653 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005654 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005655 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005656
Ady Abraham2139f732019-11-13 18:56:40 -08005657 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5658 auto configId = mScheduler->getPreferredConfigId();
5659 auto preferredRefreshRate = configId
5660 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5661 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5662 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5663 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5664 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5665 ALOGV("switching to Scheduler preferred config %d",
5666 preferredRefreshRate.configId.value());
5667 setDesiredActiveConfig(
5668 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5669 } else {
5670 // Set the highest allowed config
5671 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5672 Scheduler::ConfigEvent::Changed});
5673 }
5674 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005675 ALOGV("switching to config %d", defaultConfig.value());
5676 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005677 }
5678
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005679 return NO_ERROR;
5680}
5681
Ana Krulec0782b882019-10-15 17:34:54 -07005682status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005683 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005684 float maxRefreshRate) {
5685 ATRACE_CALL();
5686
5687 if (!displayToken) {
5688 return BAD_VALUE;
5689 }
5690
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005691 status_t result = NO_ERROR;
5692
Ana Krulec234bb162019-11-10 22:55:55 +01005693 postMessageSync(new LambdaMessage([&]() {
5694 const auto display = getDisplayDeviceLocked(displayToken);
5695 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005696 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005697 ALOGE("Attempt to set desired display configs for invalid display token %p",
5698 displayToken.get());
5699 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005700 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005701 ALOGW("Attempt to set desired display configs for virtual display");
5702 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005703 result =
5704 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5705 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005706 }
5707 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005708
5709 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005710}
5711
5712status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005713 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005714 float* outMinRefreshRate,
5715 float* outMaxRefreshRate) {
5716 ATRACE_CALL();
5717
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005718 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005719 return BAD_VALUE;
5720 }
5721
5722 Mutex::Autolock lock(mStateLock);
5723 const auto display = getDisplayDeviceLocked(displayToken);
5724 if (!display) {
5725 return NAME_NOT_FOUND;
5726 }
5727
5728 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005729 HwcConfigIndexType defaultConfig;
5730 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5731 *outDefaultConfig = defaultConfig.value();
5732 return NO_ERROR;
5733 } else if (display->isVirtual()) {
5734 return BAD_VALUE;
5735 } else {
5736 const auto displayId = display->getId();
5737 if (!displayId) {
5738 return BAD_VALUE;
5739 }
5740 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5741 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5742 *outMinRefreshRate = 1e9f / vsyncPeriod;
5743 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5744 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005745 }
Ana Krulec0782b882019-10-15 17:34:54 -07005746}
5747
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005748void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005749 mFlinger->setInputWindowsFinished();
5750}
5751
Robert Carrc0df3122019-04-11 13:18:21 -07005752sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005753 BBinder* b = nullptr;
5754 if (handle) {
5755 b = handle->localBinder();
5756 }
Robert Carrc0df3122019-04-11 13:18:21 -07005757 if (b == nullptr) {
5758 return nullptr;
5759 }
5760 auto it = mLayersByLocalBinderToken.find(b);
5761 if (it != mLayersByLocalBinderToken.end()) {
5762 return it->second.promote();
5763 }
5764 return nullptr;
5765}
5766
Dominik Laskowski75848362019-11-11 17:57:20 -08005767void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005768 mNumLayers++;
5769 mScheduler->registerLayer(layer);
5770}
5771
5772void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5773 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005774 removeFromOffscreenLayers(layer);
5775}
5776
5777// WARNING: ONLY CALL THIS FROM LAYER DTOR
5778// Here we add children in the current state to offscreen layers and remove the
5779// layer itself from the offscreen layer list. Since
5780// this is the dtor, it is safe to access the current state. This keeps us
5781// from dangling children layers such that they are not reachable from the
5782// Drawing state nor the offscreen layer list
5783// See b/141111965
5784void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5785 for (auto& child : layer->getCurrentChildren()) {
5786 mOffscreenLayers.emplace(child.get());
5787 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005788 mOffscreenLayers.erase(layer);
5789}
5790
Alec Mouri4545a8a2019-08-08 20:05:32 -07005791void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5792 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5793}
5794
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005795status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5796 float lightPosY, float lightPosZ,
5797 float lightRadius) {
5798 Mutex::Autolock _l(mStateLock);
5799 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5800 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5801 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5802 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5803 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5804
5805 // these values are overridden when calculating the shadow settings for a layer.
5806 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5807 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005808 return NO_ERROR;
5809}
5810
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005811} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005812
Mathias Agopian3f844832013-08-07 21:24:32 -07005813#if defined(__gl_h_)
5814#error "don't include gl/gl.h in this file"
5815#endif
5816
5817#if defined(__gl2_h_)
5818#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005819#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005820
5821// TODO(b/129481165): remove the #pragma below and fix conversion issues
5822#pragma clang diagnostic pop // ignored "-Wconversion"