blob: 06a9b1f6255fd0eaf96c9c6091ed04e7769f9914 [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
Yiwei Zhang243b3782018-05-15 17:40:04 -0700341 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700342 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
343 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
344
Dan Stozaec460082018-12-17 15:35:09 -0800345 property_get("debug.sf.luma_sampling", value, "1");
346 mLumaSampling = atoi(value);
347
Romain Guy11d63f42017-07-20 12:47:14 -0700348 // We should be reading 'persist.sys.sf.color_saturation' here
349 // but since /data may be encrypted, we need to wait until after vold
350 // comes online to attempt to read the property. The property is
351 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800352
353 if (useTrebleTestingOverride()) {
354 // Without the override SurfaceFlinger cannot connect to HIDL
355 // services that are not listed in the manifests. Considered
356 // deriving the setting from the set service name, but it
357 // would be brittle if the name that's not 'default' is used
358 // for production purposes later on.
359 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
360 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361}
362
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363void SurfaceFlinger::onFirstRef()
364{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800365 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800366}
367
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700368SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369
Dan Stozac7014012014-02-14 15:03:43 -0800370void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371{
372 // the window manager died on us. prepare its eulogy.
373
Andy McFadden13a082e2012-08-24 10:16:42 -0700374 // restore initial conditions (default device unblank, etc)
375 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800376
377 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700378 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800379}
380
Robert Carr1db73f62016-12-21 12:58:51 -0800381static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700382 status_t err = client->initCheck();
383 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800384 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 }
Robert Carr1db73f62016-12-21 12:58:51 -0800386 return nullptr;
387}
388
389sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
390 return initClient(new Client(this));
391}
392
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700393sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
394 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700395{
396 class DisplayToken : public BBinder {
397 sp<SurfaceFlinger> flinger;
398 virtual ~DisplayToken() {
399 // no more references, this display must be terminated
400 Mutex::Autolock _l(flinger->mStateLock);
401 flinger->mCurrentState.displays.removeItem(this);
402 flinger->setTransactionFlags(eDisplayTransactionNeeded);
403 }
404 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700405 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406 : flinger(flinger) {
407 }
408 };
409
410 sp<BBinder> token = new DisplayToken(this);
411
412 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700413 // Display ID is assigned when virtual display is allocated by HWC.
414 DisplayDeviceState state;
415 state.isSecure = secure;
416 state.displayName = displayName;
417 mCurrentState.displays.add(token, state);
418 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700419 return token;
420}
421
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700422void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700423 Mutex::Autolock _l(mStateLock);
424
Dominik Laskowski075d3172018-05-24 15:50:06 -0700425 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
426 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700427 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700428 return;
429 }
430
Dominik Laskowski075d3172018-05-24 15:50:06 -0700431 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
432 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700433 ALOGE("destroyDisplay called for non-virtual display");
434 return;
435 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700436 mInterceptor->saveDisplayDeletion(state.sequenceId);
437 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700438 setTransactionFlags(eDisplayTransactionNeeded);
439}
440
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800441std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
442 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700443
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800444 const auto internalDisplayId = getInternalDisplayIdLocked();
445 if (!internalDisplayId) {
446 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 }
448
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800449 std::vector<PhysicalDisplayId> displayIds;
450 displayIds.reserve(mPhysicalDisplayTokens.size());
451 displayIds.push_back(internalDisplayId->value);
452
453 for (const auto& [id, token] : mPhysicalDisplayTokens) {
454 if (id != *internalDisplayId) {
455 displayIds.push_back(id.value);
456 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800459 return displayIds;
460}
461
462sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
463 Mutex::Autolock lock(mStateLock);
464 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465}
466
Ady Abraham37965d42018-11-01 13:43:32 -0700467status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
468 if (!outGetColorManagement) {
469 return BAD_VALUE;
470 }
471 *outGetColorManagement = useColorManagement;
472 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700473}
474
Lloyd Pique441d5042018-10-18 16:49:51 -0700475HWComposer& SurfaceFlinger::getHwComposer() const {
476 return mCompositionEngine->getHwComposer();
477}
478
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700479renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
480 return mCompositionEngine->getRenderEngine();
481}
482
Lloyd Pique70d91362018-10-18 16:02:55 -0700483compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
484 return *mCompositionEngine.get();
485}
486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487void SurfaceFlinger::bootFinished()
488{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700489 if (mStartPropertySetThread->join() != NO_ERROR) {
490 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800492 const nsecs_t now = systemTime();
493 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000494 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700495
Mikael Pessa90092f42019-08-26 17:22:04 -0700496 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000497 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700498
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700499 // wait patiently for the window manager death
500 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700501 mWindowManager = defaultServiceManager()->getService(name);
502 if (mWindowManager != 0) {
503 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700504 }
Robert Carr720e5062018-07-30 17:45:14 -0700505 sp<IBinder> input(defaultServiceManager()->getService(
506 String16("inputflinger")));
507 if (input == nullptr) {
508 ALOGE("Failed to link to input service");
509 } else {
510 mInputFlinger = interface_cast<IInputFlinger>(input);
511 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512
Steven Thomas050b2c82017-03-06 11:45:16 -0800513 if (mVrFlinger) {
514 mVrFlinger->OnBootFinished();
515 }
516
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700518 // formerly we would just kill the process, but we now ask it to exit so it
519 // can choose where to stop the animation.
520 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700521
522 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
523 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
524 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700525
Ana Krulecbd6654b2019-02-15 15:18:15 -0800526 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800527 readPersistentProperties();
528 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800529
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700530 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
531 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800532 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
533 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800534 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800535 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800536}
537
Dan Stoza436ccf32018-06-21 12:10:12 -0700538uint32_t SurfaceFlinger::getNewTexture() {
539 {
540 std::lock_guard lock(mTexturePoolMutex);
541 if (!mTexturePool.empty()) {
542 uint32_t name = mTexturePool.back();
543 mTexturePool.pop_back();
544 ATRACE_INT("TexturePoolSize", mTexturePool.size());
545 return name;
546 }
547
548 // The pool was too small, so increase it for the future
549 ++mTexturePoolSize;
550 }
551
552 // The pool was empty, so we need to get a new texture name directly using a
553 // blocking call to the main thread
554 uint32_t name = 0;
555 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
556 return name;
557}
558
Mathias Agopian3f844832013-08-07 21:24:32 -0700559void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700560 std::lock_guard lock(mTexturePoolMutex);
561 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
562 // to actually delete this or not based on mTexturePoolSize
563 mTexturePool.push_back(texture);
564 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700565}
566
Wei Wangf9b05ee2017-07-19 20:59:39 -0700567// Do not call property_set on main thread which will be blocked by init
568// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700570 ALOGI( "SurfaceFlinger's main thread ready to run. "
571 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700572 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800573
Steven Thomasb02664d2017-07-26 18:48:28 -0700574 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700575 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800576 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d72019-10-09 10:39:09 -0700577 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
578 renderengine::RenderEngineCreationArgs::Builder()
579 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
580 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
581 .setUseColorManagerment(useColorManagement)
582 .setEnableProtectedContext(enable_protected_contents(false))
583 .setPrecacheToneMapperShaderOnly(false)
584 .setContextPriority(useContextPriority
585 ? renderengine::RenderEngine::ContextPriority::HIGH
586 : renderengine::RenderEngine::ContextPriority::MEDIUM)
587 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800588 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700589
590 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
591 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700592 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
593 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800594 // Process any initial hotplug and resulting display changes.
595 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700596 const auto display = getDefaultDisplayDeviceLocked();
597 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700598 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700599 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800600
Steven Thomas050b2c82017-03-06 11:45:16 -0800601 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700602 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700603 // This callback is called from the vr flinger dispatch thread. We
604 // need to call signalTransaction(), which requires holding
605 // mStateLock when we're not on the main thread. Acquiring
606 // mStateLock from the vr flinger dispatch thread might trigger a
607 // deadlock in surface flinger (see b/66916578), so post a message
608 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700610 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
611 mVrFlingerRequestsDisplay = requestDisplay;
612 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800614 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700615 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
616 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700617 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700618 .value_or(0),
619 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800620 if (!mVrFlinger) {
621 ALOGE("Failed to start vrflinger");
622 }
623 }
624
Mathias Agopian92a979a2012-08-02 18:32:23 -0700625 // initialize our drawing state
626 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700627
Andy McFadden13a082e2012-08-24 10:16:42 -0700628 // set initial conditions (e.g. unblank default device)
629 initializeDisplays();
630
Steven Thomas137d4bc2019-07-25 16:55:14 -0700631 char primeShaderCache[PROPERTY_VALUE_MAX];
632 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
633 if (atoi(primeShaderCache)) {
634 getRenderEngine().primeCache();
635 }
Dan Stoza4e637772016-07-28 13:31:51 -0700636
Wei Wangf9b05ee2017-07-19 20:59:39 -0700637 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700638
639 const bool presentFenceReliable =
640 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
641 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700642
643 if (mStartPropertySetThread->Start() != NO_ERROR) {
644 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700648}
649
Romain Guy11d63f42017-07-20 12:47:14 -0700650void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700651 Mutex::Autolock _l(mStateLock);
652
Romain Guy11d63f42017-07-20 12:47:14 -0700653 char value[PROPERTY_VALUE_MAX];
654
655 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800656 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700657 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800658 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100659
660 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700661 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800662
663 property_get("persist.sys.sf.color_mode", value, "0");
664 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700665}
666
Mathias Agopiana67e4182012-06-19 17:26:12 -0700667void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800668 // Start boot animation service by setting a property mailbox
669 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700670 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800671 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700672 if (mStartPropertySetThread->join() != NO_ERROR) {
673 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700675}
676
Mathias Agopian875d8e12013-06-07 15:35:48 -0700677size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700678 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700679}
680
Mathias Agopian875d8e12013-06-07 15:35:48 -0700681size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700682 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700683}
684
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800686
Jamie Gennis582270d2011-08-17 18:19:00 -0700687bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800688 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800689 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800690 return authenticateSurfaceTextureLocked(bufferProducer);
691}
692
693bool SurfaceFlinger::authenticateSurfaceTextureLocked(
694 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800695 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800696 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800697}
698
Brian Anderson6b376712017-04-04 10:51:39 -0700699status_t SurfaceFlinger::getSupportedFrameTimestamps(
700 std::vector<FrameEvent>* outSupported) const {
701 *outSupported = {
702 FrameEvent::REQUESTED_PRESENT,
703 FrameEvent::ACQUIRE,
704 FrameEvent::LATCH,
705 FrameEvent::FIRST_REFRESH_START,
706 FrameEvent::LAST_REFRESH_START,
707 FrameEvent::GPU_COMPOSITION_DONE,
708 FrameEvent::DEQUEUE_READY,
709 FrameEvent::RELEASE,
710 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700711 ConditionalLock _l(mStateLock,
712 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700713 if (!getHwComposer().hasCapability(
714 HWC2::Capability::PresentFenceIsNotReliable)) {
715 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
716 }
717 return NO_ERROR;
718}
719
Dominik Laskowski22488f62019-03-28 09:53:04 -0700720status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
721 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700722 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700723 return BAD_VALUE;
724 }
725
Dominik Laskowski22488f62019-03-28 09:53:04 -0700726 Mutex::Autolock lock(mStateLock);
727
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800728 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700729 if (!displayId) {
730 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700731 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700732
Mathias Agopian8b736f12012-08-13 17:54:26 -0700733 // TODO: Not sure if display density should handled by SF any longer
734 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700735 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700736 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700737 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800738 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700739 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700740 }
741 return density;
742 }
743 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700744 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700746 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700747 return getDensityFromProperty("ro.sf.lcd_density"); }
748 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700749
Dan Stoza7f7da322014-05-02 15:26:25 -0700750 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700751
Dominik Laskowski075d3172018-05-24 15:50:06 -0700752 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700753 DisplayInfo info = DisplayInfo();
754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 float xdpi = hwConfig->getDpiX();
756 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700757
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700758 info.w = hwConfig->getWidth();
759 info.h = hwConfig->getHeight();
760 // Default display viewport to display width and height
761 info.viewportW = info.w;
762 info.viewportH = info.h;
763
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800764 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 // The density of the device is provided by a build property
766 float density = Density::getBuildDensity() / 160.0f;
767 if (density == 0) {
768 // the build doesn't provide a density -- this is wrong!
769 // use xdpi instead
770 ALOGE("ro.sf.lcd_density must be defined as a build property");
771 density = xdpi / 160.0f;
772 }
773 if (Density::getEmuDensity()) {
774 // if "qemu.sf.lcd_density" is specified, it overrides everything
775 xdpi = ydpi = density = Density::getEmuDensity();
776 density /= 160.0f;
777 }
778 info.density = density;
779
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700780 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800781 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700782
783 // This is for screenrecord
784 const Rect viewport = display->getViewport();
785 if (viewport.isValid()) {
786 info.viewportW = uint32_t(viewport.getWidth());
787 info.viewportH = uint32_t(viewport.getHeight());
788 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700789 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700790 } else {
791 // TODO: where should this value come from?
792 static const int TV_DENSITY = 213;
793 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700794
795 const auto display = getDisplayDeviceLocked(displayToken);
796 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 }
798
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 info.xdpi = xdpi;
800 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800801 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800802
Ady Abraham9e16a482019-12-03 17:19:41 -0800803 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700804 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800805
Andy McFadden91b2ca82014-06-13 14:04:23 -0700806 // This is how far in advance a buffer must be queued for
807 // presentation at a given time. If you want a buffer to appear
808 // on the screen at time N, you must submit the buffer before
809 // (N - presentationDeadline).
810 //
811 // Normally it's one full refresh period (to give SF a chance to
812 // latch the buffer), but this can be reduced by configuring a
813 // DispSync offset. Any additional delays introduced by the hardware
814 // composer or panel must be accounted for here.
815 //
816 // We add an additional 1ms to allow for processing time and
817 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700818 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700819
820 // All non-virtual displays are currently considered secure.
821 info.secure = true;
822
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800823 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800824 (internalDisplayOrientation == ui::ROTATION_90 ||
825 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800826 std::swap(info.w, info.h);
827 }
828
Michael Wright28f24d02016-07-12 13:30:53 -0700829 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 }
831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 return NO_ERROR;
833}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700834
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700835status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
836 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700837 return BAD_VALUE;
838 }
839
Ana Krulecc2870422019-01-29 19:00:58 -0800840 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700841 return NO_ERROR;
842}
843
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700844int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
845 const auto display = getDisplayDevice(displayToken);
846 if (!display) {
847 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800848 return BAD_VALUE;
849 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700850
Steven Thomasc9098452019-09-30 17:15:05 -0700851 if (display->isPrimary()) {
852 std::lock_guard<std::mutex> lock(mActiveConfigLock);
853 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800854 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700855 }
Steven Thomasc9098452019-09-30 17:15:05 -0700856 }
Ady Abraham2139f732019-11-13 18:56:40 -0800857
858 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700859}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700860
Ady Abraham03b02dd2019-03-21 15:40:11 -0700861void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800862 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800863 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
864 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800865
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800866 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800867 // config twice. However event generation config might have changed so we need to update it
868 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800869 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700870 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
871 mDesiredActiveConfig = info;
872 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800873
874 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800875 // This will trigger HWC refresh without resetting the idle timer.
876 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700877 // Start receiving vsync samples now, so that we can detect a period
878 // switch.
879 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700880 // As we called to set period, we will call to onRefreshRateChangeCompleted once
881 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700882 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800883
Ady Abraham9e16a482019-12-03 17:19:41 -0800884 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
885 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800886 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800887 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700888
889 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800890 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700891 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800892}
893
894status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
895 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800896
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100897 if (!displayToken) {
898 return BAD_VALUE;
899 }
Ady Abraham838de062019-02-04 10:24:03 -0800900
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100901 status_t result = NO_ERROR;
902
903 postMessageSync(new LambdaMessage([&]() {
904 const auto display = getDisplayDeviceLocked(displayToken);
905 if (!display) {
906 ALOGE("Attempt to set allowed display configs for invalid display token %p",
907 displayToken.get());
908 result = BAD_VALUE;
909 } else if (display->isVirtual()) {
910 ALOGW("Attempt to set allowed display configs for virtual display");
911 result = BAD_VALUE;
912 } else {
913 HwcConfigIndexType config(mode);
914 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
915 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
916 refreshRate.fps);
917 }
918 }));
919
920 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800921}
922
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800923void SurfaceFlinger::setActiveConfigInternal() {
924 ATRACE_CALL();
925
Dominik Laskowski22488f62019-03-28 09:53:04 -0700926 const auto display = getDefaultDisplayDeviceLocked();
927 if (!display) {
928 return;
929 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930
Dominik Laskowski22488f62019-03-28 09:53:04 -0700931 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800932 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700933 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800934 display->setActiveConfig(mUpcomingActiveConfig.configId);
935
Ady Abraham2139f732019-11-13 18:56:40 -0800936 auto refreshRate =
937 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800938 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
939 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800940 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700941
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800942 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700943 const nsecs_t vsyncPeriod =
944 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
945 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800946 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700947 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800948 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949}
950
Ady Abraham53852a52019-05-28 18:07:44 -0700951void SurfaceFlinger::desiredActiveConfigChangeDone() {
952 std::lock_guard<std::mutex> lock(mActiveConfigLock);
953 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
954 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700955
956 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800957 auto refreshRate =
958 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800959 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
960 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700961}
962
Dominik Laskowski22488f62019-03-28 09:53:04 -0700963bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800964 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800965 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800966 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700967 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700969 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800970 return true;
971 }
972
973 // We received the present fence from the HWC, so we assume it successfully updated
974 // the config, hence we update SF.
975 mCheckPendingFence = false;
976 setActiveConfigInternal();
977 }
978
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 // Store the local variable to release the lock.
980 ActiveConfigInfo desiredActiveConfig;
981 {
982 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 if (!mDesiredActiveConfigChanged) {
984 return false;
985 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 desiredActiveConfig = mDesiredActiveConfig;
987 }
988
Ady Abraham2139f732019-11-13 18:56:40 -0800989 auto refreshRate =
990 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
991 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
992 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -0700993 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800994 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
995 // display is not valid or we are already in the requested mode
996 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700997 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800998 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000
Ady Abraham838de062019-02-04 10:24:03 -08001001 // Desired active config was set, it is different than the config currently in use, however
1002 // allowed configs might have change by the time we process the refresh.
1003 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001004 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001005 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001006 return false;
1007 }
Alec Mouri7f015182019-07-11 13:56:22 -07001008
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 mUpcomingActiveConfig = desiredActiveConfig;
1010 const auto displayId = display->getId();
1011 LOG_ALWAYS_FATAL_IF(!displayId);
1012
Ady Abraham2139f732019-11-13 18:56:40 -08001013 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001015 // TODO(b/142753666) use constrains
1016 HWC2::VsyncPeriodChangeConstraints constraints;
1017 constraints.desiredTimeNanos = systemTime();
1018 constraints.seamlessRequired = false;
1019
1020 HWC2::VsyncPeriodChangeTimeline outTimeline;
1021 auto status =
1022 getHwComposer().setActiveConfigWithConstraints(*displayId,
1023 mUpcomingActiveConfig.configId.value(),
1024 constraints, &outTimeline);
1025 if (status != NO_ERROR) {
1026 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1027 return false;
1028 }
1029
1030 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1031 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001033 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001034}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001035
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1037 Vector<ColorMode>* outColorModes) {
1038 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001039 return BAD_VALUE;
1040 }
1041
Peiyong Lina52f0292018-03-14 17:26:31 -07001042 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001043 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001044 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001045 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1046
1047 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1048 if (!displayId) {
1049 return NAME_NOT_FOUND;
1050 }
1051
Dominik Laskowski075d3172018-05-24 15:50:06 -07001052 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001053 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001054 }
Michael Wright28f24d02016-07-12 13:30:53 -07001055 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001056
1057 // If it's built-in display and the configuration claims it's not wide color capable,
1058 // filter out all wide color modes. The typical reason why this happens is that the
1059 // hardware is not good enough to support GPU composition of wide color, and thus the
1060 // OEMs choose to disable this capability.
1061 if (isInternalDisplay && !hasWideColorDisplay) {
1062 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1063 isWideColorMode);
1064 } else {
1065 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1066 }
Michael Wright28f24d02016-07-12 13:30:53 -07001067
1068 return NO_ERROR;
1069}
1070
Daniel Solomon42d04562019-01-20 21:03:19 -08001071status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1072 ui::DisplayPrimaries &primaries) {
1073 if (!displayToken) {
1074 return BAD_VALUE;
1075 }
1076
1077 // Currently we only support this API for a single internal display.
1078 if (getInternalDisplayToken() != displayToken) {
1079 return BAD_VALUE;
1080 }
1081
1082 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1087 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001088 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001089 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001090 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001091}
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001094 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 Vector<ColorMode> modes;
1096 getDisplayColorModes(displayToken, &modes);
1097 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1098 if (mode < ColorMode::NATIVE || !exists) {
1099 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1100 decodeColorMode(mode).c_str(), mode, displayToken.get());
1101 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001102 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 const auto display = getDisplayDevice(displayToken);
1104 if (!display) {
1105 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1106 decodeColorMode(mode).c_str(), mode, displayToken.get());
1107 } else if (display->isVirtual()) {
1108 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1109 decodeColorMode(mode).c_str(), mode);
1110 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001111 display->getCompositionDisplay()->setColorProfile(
1112 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1113 RenderIntent::COLORIMETRIC,
1114 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 }
1116 }));
1117
Michael Wright28f24d02016-07-12 13:30:53 -07001118 return NO_ERROR;
1119}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001120
Galia Peycheva5492cb52019-10-30 14:13:16 +01001121status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1122 bool* outSupport) const {
1123 Mutex::Autolock _l(mStateLock);
1124
1125 if (!displayToken) {
1126 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1127 return BAD_VALUE;
1128 }
1129 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1130 if (!displayId) {
1131 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1132 displayToken.get());
1133 return NAME_NOT_FOUND;
1134 }
1135 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1136 HWC2::DisplayCapability::AutoLowLatencyMode);
1137 return NO_ERROR;
1138}
1139
1140void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1141 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1142}
1143
1144void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1145 if (!displayToken) {
1146 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1147 return;
1148 }
1149 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1150 if (!displayId) {
1151 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1152 displayToken.get());
1153 return;
1154 }
1155
1156 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1157}
1158
1159status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1160 bool* outSupport) const {
1161 Mutex::Autolock _l(mStateLock);
1162
1163 if (!displayToken) {
1164 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1165 return BAD_VALUE;
1166 }
1167 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1168 if (!displayId) {
1169 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1170 displayToken.get());
1171 return NAME_NOT_FOUND;
1172 }
1173
1174 std::vector<HWC2::ContentType> outSupportedContentTypes;
1175 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1176 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1177 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1178 return NO_ERROR;
1179}
1180
1181void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1182 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1183}
1184
1185void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1186 if (!displayToken) {
1187 ALOGE("setGameContentType() failed. Missing display token.");
1188 return;
1189 }
1190 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1191 if (!displayId) {
1192 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1193 displayToken.get());
1194 return;
1195 }
1196
1197 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1198 getHwComposer().setContentType(*displayId, type);
1199}
1200
Svetoslavd85084b2014-03-20 10:28:31 -07001201status_t SurfaceFlinger::clearAnimationFrameStats() {
1202 Mutex::Autolock _l(mStateLock);
1203 mAnimFrameTracker.clearStats();
1204 return NO_ERROR;
1205}
1206
1207status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1208 Mutex::Autolock _l(mStateLock);
1209 mAnimFrameTracker.getStats(outStats);
1210 return NO_ERROR;
1211}
1212
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001213status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1214 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001215 Mutex::Autolock _l(mStateLock);
1216
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001217 const auto display = getDisplayDeviceLocked(displayToken);
1218 if (!display) {
1219 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001220 return BAD_VALUE;
1221 }
1222
Peiyong Linfb069302018-04-25 14:34:31 -07001223 // At this point the DisplayDeivce should already be set up,
1224 // meaning the luminance information is already queried from
1225 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001226 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001227 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1228 capabilities.getDesiredMaxLuminance(),
1229 capabilities.getDesiredMaxAverageLuminance(),
1230 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001231
1232 return NO_ERROR;
1233}
1234
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001235status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1236 ui::PixelFormat* outFormat,
1237 ui::Dataspace* outDataspace,
1238 uint8_t* outComponentMask) const {
1239 if (!outFormat || !outDataspace || !outComponentMask) {
1240 return BAD_VALUE;
1241 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001242 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001243 if (!display || !display->getId()) {
1244 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1245 return BAD_VALUE;
1246 }
1247 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1248 outDataspace, outComponentMask);
1249}
1250
Kevin DuBois74e53772018-11-19 10:52:38 -08001251status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1252 bool enable, uint8_t componentMask,
1253 uint64_t maxFrames) const {
1254 const auto display = getDisplayDevice(displayToken);
1255 if (!display || !display->getId()) {
1256 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1257 return BAD_VALUE;
1258 }
1259
1260 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1261 componentMask, maxFrames);
1262}
1263
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001264status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1265 uint64_t maxFrames, uint64_t timestamp,
1266 DisplayedFrameStats* outStats) const {
1267 const auto display = getDisplayDevice(displayToken);
1268 if (!display || !display->getId()) {
1269 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1270 return BAD_VALUE;
1271 }
1272
1273 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1274 outStats);
1275}
1276
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001277status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1278 if (!outSupported) {
1279 return BAD_VALUE;
1280 }
1281 *outSupported = getRenderEngine().supportsProtectedContent();
1282 return NO_ERROR;
1283}
1284
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001285status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1286 bool* outIsWideColorDisplay) const {
1287 if (!displayToken || !outIsWideColorDisplay) {
1288 return BAD_VALUE;
1289 }
1290 Mutex::Autolock _l(mStateLock);
1291 const auto display = getDisplayDeviceLocked(displayToken);
1292 if (!display) {
1293 return BAD_VALUE;
1294 }
Peiyong Linff84a152019-05-17 18:36:19 -07001295
1296 // Use hasWideColorDisplay to override built-in display.
1297 const auto displayId = display->getId();
1298 if (displayId && displayId == getInternalDisplayIdLocked()) {
1299 *outIsWideColorDisplay = hasWideColorDisplay;
1300 return NO_ERROR;
1301 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001302 *outIsWideColorDisplay = display->hasWideColorGamut();
1303 return NO_ERROR;
1304}
1305
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001306status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001307 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001308 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001309
Dominik Laskowski6505f792019-09-18 11:10:05 -07001310 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1311 mEventQueue->setEventConnection(
1312 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001313 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001314 }));
1315
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001316 return NO_ERROR;
1317}
1318
1319status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001320 Mutex::Autolock lock(mStateLock);
1321 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001322}
1323
Lloyd Pique755e3192018-01-31 16:46:15 -08001324status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1325 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001326 // Try to acquire a lock for 1s, fail gracefully
1327 const status_t err = mStateLock.timedLock(s2ns(1));
1328 const bool locked = (err == NO_ERROR);
1329 if (!locked) {
1330 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1331 return TIMED_OUT;
1332 }
1333
1334 outLayers->clear();
1335 mCurrentState.traverseInZOrder([&](Layer* layer) {
1336 outLayers->push_back(layer->getLayerDebugInfo());
1337 });
1338
1339 mStateLock.unlock();
1340 return NO_ERROR;
1341}
1342
Peiyong Linc6780972018-10-28 15:24:08 -07001343status_t SurfaceFlinger::getCompositionPreference(
1344 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1345 Dataspace* outWideColorGamutDataspace,
1346 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001347 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001348 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001349 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001350 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001351 return NO_ERROR;
1352}
1353
Dan Stozaec460082018-12-17 15:35:09 -08001354status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1355 const sp<IBinder>& stopLayerHandle,
1356 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001357 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001358 return BAD_VALUE;
1359 }
1360 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001361 return NO_ERROR;
1362}
1363
Dan Stozaec460082018-12-17 15:35:09 -08001364status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001365 if (!listener) {
1366 return BAD_VALUE;
1367 }
Dan Stozaec460082018-12-17 15:35:09 -08001368 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001369 return NO_ERROR;
1370}
Dan Gittik57e63c52019-01-18 16:37:54 +00001371
1372status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1373 bool* outSupport) const {
1374 if (!displayToken || !outSupport) {
1375 return BAD_VALUE;
1376 }
1377 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1378 if (!displayId) {
1379 return NAME_NOT_FOUND;
1380 }
1381 *outSupport =
1382 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1383 return NO_ERROR;
1384}
1385
1386status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1387 float brightness) const {
1388 if (!displayToken) {
1389 return BAD_VALUE;
1390 }
1391 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1392 if (!displayId) {
1393 return NAME_NOT_FOUND;
1394 }
1395 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1396}
1397
Ady Abraham8532d012019-05-08 14:50:56 -07001398status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1399 PowerHint powerHint = static_cast<PowerHint>(hintId);
1400
1401 if (powerHint == PowerHint::INTERACTION) {
1402 mScheduler->notifyTouchEvent();
1403 }
1404
1405 return NO_ERROR;
1406}
1407
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001408// ----------------------------------------------------------------------------
1409
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001410sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001411 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001412 const auto& handle =
1413 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001414
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001415 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001416}
1417
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001418// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001419
1420void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001421 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001422}
1423
1424void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001425 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001426 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001427}
1428
1429void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001430 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001431 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432}
1433
1434void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001435 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001436 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001437}
1438
1439status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001440 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001441 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001442}
1443
1444status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001445 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001446 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001447 if (res == NO_ERROR) {
1448 msg->wait();
1449 }
1450 return res;
1451}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001452
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001453void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001454 do {
1455 waitForEvent();
1456 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001457}
1458
Dominik Laskowski83b88212018-12-11 13:34:06 -08001459nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001460 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001461 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1462 return 0;
1463 }
1464
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001465 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001466}
1467
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001468void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001469 int64_t timestamp,
1470 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001471 ATRACE_NAME("SF onVsync");
1472
Ady Abraham7159f572019-10-11 11:10:18 -07001473 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1474
Steven Thomas3cfac282017-02-06 12:29:30 -08001475 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001477 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 return;
1479 }
1480
Dominik Laskowski075d3172018-05-24 15:50:06 -07001481 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001482 return;
1483 }
1484
Dominik Laskowski075d3172018-05-24 15:50:06 -07001485 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001486 // For now, we don't do anything with external display vsyncs.
1487 return;
1488 }
1489
Alec Mourif8e689c2019-05-20 18:32:22 -07001490 bool periodFlushed = false;
1491 mScheduler->addResyncSample(timestamp, &periodFlushed);
1492 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001493 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001494 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001495}
1496
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001497void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001498 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1499 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001500}
1501
Ady Abraham2139f732019-11-13 18:56:40 -08001502bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001503 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001504}
1505
Ady Abraham2139f732019-11-13 18:56:40 -08001506void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1507 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001508 const auto display = getDefaultDisplayDeviceLocked();
1509 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001510 return;
1511 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001512 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001513
Ana Krulec7d1d6832018-12-27 11:10:09 -08001514 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001515 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1516 ALOGV("Skipping config %d as it is not part of allowed configs",
1517 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001518 return;
1519 }
1520
Ady Abraham2139f732019-11-13 18:56:40 -08001521 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522}
1523
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001524void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001525 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001526 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001527 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001528
Lloyd Piqueba04e622017-12-14 17:11:26 -08001529 // Ignore events that do not have the right sequenceId.
1530 if (sequenceId != getBE().mComposerSequenceId) {
1531 return;
1532 }
1533
Steven Thomasb02664d2017-07-26 18:48:28 -07001534 // Only lock if we're not on the main thread. This function is normally
1535 // called on a hwbinder thread, but for the primary display it's called on
1536 // the main thread with the state lock already held, so don't attempt to
1537 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001538 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001539
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001540 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001541
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001542 if (std::this_thread::get_id() == mMainThreadId) {
1543 // Process all pending hot plug events immediately if we are on the main thread.
1544 processDisplayHotplugEventsLocked();
1545 }
1546
Lloyd Piqueba04e622017-12-14 17:11:26 -08001547 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001548}
1549
Ady Abraham7159f572019-10-11 11:10:18 -07001550void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001551 int32_t sequenceId, hwc2_display_t /*display*/,
1552 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1553 Mutex::Autolock lock(mStateLock);
1554 if (sequenceId != getBE().mComposerSequenceId) {
1555 return;
1556 }
1557 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001558}
1559
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001560void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1561 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1562 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1563}
1564
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001565void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001566 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001567 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001568 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001569 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001570 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001571}
1572
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001573void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001574 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001575
1576 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1577 // display power state.
1578 postMessageAsync(new LambdaMessage(
1579 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1580}
1581
1582void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1583 ATRACE_CALL();
1584
Ady Abraham27c70212019-06-11 10:52:26 -07001585 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1586
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001587 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001588 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1589 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001590 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001591 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001592 }
Mathias Agopian86303202012-07-24 22:46:10 -07001593}
1594
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001596void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001597 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001598 // Clear the drawing state so that the logic inside of
1599 // handleTransactionLocked will fire. It will determine the delta between
1600 // mCurrentState and mDrawingState and re-apply all changes when we make the
1601 // transition.
1602 mDrawingState.displays.clear();
1603 mDisplays.clear();
1604}
1605
Steven Thomas050b2c82017-03-06 11:45:16 -08001606void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001607 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001608 if (!mVrFlinger)
1609 return;
1610 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001611 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001612 return;
1613 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001614
Lloyd Pique441d5042018-10-18 16:49:51 -07001615 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 ALOGE("Vr flinger is only supported for remote hardware composer"
1617 " service connections. Ignoring request to transition to vr"
1618 " flinger.");
1619 mVrFlingerRequestsDisplay = false;
1620 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001621 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001622
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001623 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001624
Steven Thomas0123ac62018-07-12 11:32:34 -07001625 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001626 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001627
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001628 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001629
1630 // Clear out all the output layers from the composition engine for all
1631 // displays before destroying the hardware composer interface. This ensures
1632 // any HWC layers are destroyed through that interface before it becomes
1633 // invalid.
1634 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001635 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001636 }
1637
Steven Thomas0123ac62018-07-12 11:32:34 -07001638 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1639 // called below. Clear the reference now so we don't accidentally use it
1640 // later.
1641 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001642
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001644 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001645 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001646
Steven Thomasb02664d2017-07-26 18:48:28 -07001647 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001648 // Delete the current instance before creating the new one
1649 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1650 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1651 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1652 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001653
Lloyd Pique441d5042018-10-18 16:49:51 -07001654 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001655 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001656
1657 if (vrFlingerRequestsDisplay) {
1658 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001659 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001660
1661 mVisibleRegionsDirty = true;
1662 invalidateHwcGeometry();
1663
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001664 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001665 display = getDefaultDisplayDeviceLocked();
1666 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001667 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001668
Steven Thomasb02664d2017-07-26 18:48:28 -07001669 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001670 const nsecs_t vsyncPeriod = getVsyncPeriod();
1671 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001672
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001673 // The present fences returned from vr_hwc are not an accurate
1674 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001675 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001676
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 // Use phase of 0 since phase is not known.
1678 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001679 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001680 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001681
Ana Krulecc2870422019-01-29 19:00:58 -08001682 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001683
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001684 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001686}
1687
Ady Abraham11579302019-09-19 12:35:58 -07001688bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1689 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001690 // We are storing the last 2 present fences. If sf's phase offset is to be
1691 // woken up before the actual vsync but targeting the next vsync, we need to check
1692 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001693 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1694 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001695
Ady Abraham11579302019-09-19 12:35:58 -07001696 if (fence == Fence::NO_FENCE) {
1697 return false;
1698 }
1699
1700 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1701 fence->wait(graceTimeMs);
1702 }
1703
1704 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001705}
1706
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001707void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001708 DisplayStatInfo stats;
1709 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001710 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001711 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001712 mExpectedPresentTime.store(
1713 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001714}
1715
Dominik Laskowski22488f62019-03-28 09:53:04 -07001716void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001717 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001718 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001719 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001720 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001721 // calculate the expected present time once and use the cached
1722 // value throughout this frame to make sure all layers are
1723 // seeing this same value.
1724 populateExpectedPresentTime();
1725
Ady Abraham11579302019-09-19 12:35:58 -07001726 // When Backpressure propagation is enabled we want to give a small grace period
1727 // for the present fence to fire instead of just giving up on this frame to handle cases
1728 // where present fence is just about to get signaled.
1729 const int graceTimeForPresentFenceMs =
1730 (mPropagateBackpressure &&
1731 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1732 ? 1
1733 : 0;
1734 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1735 previousFrameMissed(
1736 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001737 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1738 mHadDeviceComposition && frameMissed};
1739 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1740 mHadClientComposition && frameMissed};
1741
Alec Mouricc0fc602019-02-26 21:45:19 -08001742 if (frameMissed) {
1743 mFrameMissedCount++;
1744 mTimeStats->incrementMissedFrames();
1745 }
1746
Alec Mouri40189b02019-03-05 15:07:54 -08001747 if (hwcFrameMissed) {
1748 mHwcFrameMissedCount++;
1749 }
1750
1751 if (gpuFrameMissed) {
1752 mGpuFrameMissedCount++;
1753 }
1754
Ady Abrahamadb9a992019-09-19 21:21:55 +00001755 if (frameMissed && mPropagateBackpressure) {
1756 if ((hwcFrameMissed && !gpuFrameMissed) ||
1757 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001758 signalLayerUpdate();
1759 break;
1760 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001761 }
Dan Stoza50182882016-07-08 12:02:20 -07001762
Steven Thomas050b2c82017-03-06 11:45:16 -08001763 // Now that we're going to make it to the handleMessageTransaction()
1764 // call below it's safe to call updateVrFlinger(), which will
1765 // potentially trigger a display handoff.
1766 updateVrFlinger();
1767
Dan Stoza6b9454d2014-11-07 16:00:59 -08001768 bool refreshNeeded = handleMessageTransaction();
1769 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001770
Ana Krulecc84d09b2019-11-02 23:10:29 +01001771 // Layers need to get updated (in the previous line) before we can use them for
1772 // choosing the refresh rate.
1773 mScheduler->chooseRefreshRateForContent();
1774 if (performSetActiveConfig()) {
1775 break;
1776 }
1777
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001778 updateCursorAsync();
1779 updateInputFlinger();
1780
Dan Stoza58784442014-12-02 16:58:17 -08001781 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001782 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001783 // Signal a refresh if a transaction modified the window state,
1784 // a new buffer was latched, or if HWC has requested a full
1785 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001786 if (mFrameStartTime <= 0) {
1787 // We should only use the time of the first invalidate
1788 // message that signals a refresh as the beginning of the
1789 // frame. Otherwise the real frame time will be
1790 // underestimated.
1791 mFrameStartTime = frameStart;
1792 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001793 signalRefresh();
1794 }
1795 break;
1796 }
1797 case MessageQueue::REFRESH: {
1798 handleMessageRefresh();
1799 break;
1800 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001801 }
1802}
1803
Dan Stoza6b9454d2014-11-07 16:00:59 -08001804bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001805 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001806 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001807
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001808 bool flushedATransaction = flushTransactionQueues();
1809
1810 bool runHandleTransaction = transactionFlags &&
1811 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1812
1813 if (runHandleTransaction) {
1814 handleTransaction(eTransactionMask);
1815 } else {
1816 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001817 }
1818
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001819 if (transactionFlushNeeded()) {
1820 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001821 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001822
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001823 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001824}
1825
Mathias Agopian4fec8732012-06-29 14:12:52 -07001826void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001828
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001829 mRefreshPending = false;
1830
Lloyd Piqueab039b52019-02-13 14:22:42 -08001831 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001832 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001833 for (const auto& [_, display] : mDisplays) {
1834 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1835 }
1836 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1837 auto compositionLayer = layer->getCompositionLayer();
1838 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1839 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001840 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1841 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1842 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001843 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001844 }
1845
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001846 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001847 refreshArgs.outputColorSetting = useColorManagement
1848 ? mDisplayColorSetting
1849 : compositionengine::OutputColorSetting::kUnmanaged;
1850 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1851 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001852
1853 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1854 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001855
1856 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1857 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1858 mDrawingState.colorMatrixChanged = false;
1859 }
1860
1861 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1862
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001863 if (mDebugRegion != 0) {
1864 refreshArgs.devOptFlashDirtyRegionsDelay =
1865 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1866 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001867
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001868 mGeometryInvalid = false;
1869
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001870 // Store the present time just before calling to the composition engine so we could notify
1871 // the scheduler.
1872 const auto presentTime = systemTime();
1873
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001874 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001875 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1876 // Reset the frame start time now that we've recorded this frame.
1877 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001878
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001879 mScheduler->onDisplayRefreshed(presentTime);
1880
David Sodmanfa9b2af2017-12-24 13:28:59 -08001881 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001882 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001883
Lloyd Pique66d68602019-02-13 14:23:31 -08001884 mHadClientComposition =
1885 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1886 auto& displayDevice = tokenDisplayPair.second;
1887 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1888 });
1889 mHadDeviceComposition =
1890 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1891 auto& displayDevice = tokenDisplayPair.second;
1892 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1893 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001894
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001895 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001896
David Sodman7e4ae112018-02-09 15:02:28 -08001897 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001898 if (mVisibleRegionsDirty) {
1899 mVisibleRegionsDirty = false;
1900 if (mTracingEnabled) {
1901 mTracing.notify("visibleRegionsDirty");
1902 }
1903 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001904
1905 if (mCompositionEngine->needsAnotherUpdate()) {
1906 signalLayerUpdate();
1907 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001908}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001909
David Sodmanfa9b2af2017-12-24 13:28:59 -08001910
1911bool SurfaceFlinger::handleMessageInvalidate() {
1912 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001913 bool refreshNeeded = handlePageFlip();
1914
Vishnu Nair4351ad52019-02-11 14:13:02 -08001915 if (mVisibleRegionsDirty) {
1916 computeLayerBounds();
1917 }
1918
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001919 for (auto& layer : mLayersPendingRefresh) {
1920 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001921 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001922 invalidateLayerStack(layer, visibleReg);
1923 }
1924 mLayersPendingRefresh.clear();
1925 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001926}
1927
Ana Krulece588e312018-09-18 12:32:24 -07001928void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1929 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930 // Update queue of past composite+present times and determine the
1931 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001932 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001933 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001934 while (!getBE().mCompositePresentTimes.empty()) {
1935 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936 // Cached values should have been updated before calling this method,
1937 // which helps avoid duplicate syscalls.
1938 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1939 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1940 break;
1941 }
1942 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001943 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 }
1945
1946 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001947 while (getBE().mCompositePresentTimes.size() > 16) {
1948 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949 }
1950
Ana Krulece588e312018-09-18 12:32:24 -07001951 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001952}
1953
Ana Krulece588e312018-09-18 12:32:24 -07001954void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1955 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001956 // Integer division and modulo round toward 0 not -inf, so we need to
1957 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001958 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1959 ? (stats.vsyncPeriod -
1960 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1961 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962
Ady Abraham9e16a482019-12-03 17:19:41 -08001963 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001964 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001965 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001966 }
1967
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001968 // Snap the latency to a value that removes scheduling jitter from the
1969 // composition and present times, which often have >1ms of jitter.
1970 // Reducing jitter is important if an app attempts to extrapolate
1971 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001972 // Snapping also allows an app to precisely calculate
1973 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001974 nsecs_t bias = stats.vsyncPeriod / 2;
1975 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1976 nsecs_t snappedCompositeToPresentLatency =
1977 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978
David Sodman99974d22017-11-28 12:04:33 -08001979 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001980 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1981 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001982 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983}
1984
David Sodman2b406362017-12-15 13:33:47 -08001985void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001986{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001987 ATRACE_CALL();
1988 ALOGV("postComposition");
1989
Brian Anderson3546a3f2016-07-14 11:51:14 -07001990 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001991 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001992 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001993 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001994 }
1995
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001996 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001997 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001998
David Sodman73beded2017-11-15 11:56:06 -08001999 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002000 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002001 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002002 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002003 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2004 ->getRenderSurface()
2005 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002006 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007 } else {
2008 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2009 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002010
David Sodman73beded2017-11-15 11:56:06 -08002011 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002012 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2013 mPreviousPresentFences[0] = displayDevice
2014 ? getHwComposer().getPresentFence(*displayDevice->getId())
2015 : Fence::NO_FENCE;
2016 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002017 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018
Ana Krulece588e312018-09-18 12:32:24 -07002019 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002020 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021
Lloyd Piqueab039b52019-02-13 14:22:42 -08002022 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2023 // be sampled a little later than when we started doing work for this frame,
2024 // but that should be okay since updateCompositorTiming has snapping logic.
2025 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2026 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002027 CompositorTiming compositorTiming;
2028 {
David Sodman99974d22017-11-28 12:04:33 -08002029 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2030 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002031 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032
Robert Carr2047fae2016-11-28 14:09:09 -08002033 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002034 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2035 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002036 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002037 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002038 }
Robert Carr2047fae2016-11-28 14:09:09 -08002039 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002040
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002041 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002042 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002043 }
2044
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002045 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002046 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2047 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002048 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002049 }
2050 }
2051
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002052 if (mAnimCompositionPending) {
2053 mAnimCompositionPending = false;
2054
Brian Anderson4e606e32017-03-16 15:34:57 -07002055 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002057 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002058 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002059 // The HWC doesn't support present fences, so use the refresh
2060 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002061 const nsecs_t presentTime =
2062 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002063 mAnimFrameTracker.setActualPresentTime(presentTime);
2064 }
2065 mAnimFrameTracker.advanceFrame();
2066 }
Dan Stozab90cf072015-03-05 11:05:59 -08002067
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002068 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002069 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002070 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002071 }
2072
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002073 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002074
Lloyd Pique32cbe282018-10-19 13:09:22 -07002075 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2076 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002077 return;
2078 }
2079
2080 nsecs_t currentTime = systemTime();
2081 if (mHasPoweredOff) {
2082 mHasPoweredOff = false;
2083 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002084 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002085 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002086 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2087 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002088 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002089 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002090 }
David Sodman4a36e932017-11-07 14:29:47 -08002091 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002092 }
David Sodman4a36e932017-11-07 14:29:47 -08002093 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002094
2095 {
2096 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002097 if (mTexturePool.size() < mTexturePoolSize) {
2098 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002099 const size_t offset = mTexturePool.size();
2100 mTexturePool.resize(mTexturePoolSize);
2101 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2102 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002103 } else if (mTexturePool.size() > mTexturePoolSize) {
2104 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2105 const size_t offset = mTexturePoolSize;
2106 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2107 mTexturePool.resize(mTexturePoolSize);
2108 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002109 }
2110 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002111
Ady Abrahambe0f9482019-04-24 15:41:53 -07002112 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002113 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002114
Kevin DuBois413287f2019-02-25 08:46:47 -08002115 if (mLumaSampling && mRegionSamplingThread) {
2116 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002117 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002118
2119 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2120 // side-effect of getTotalSize(), so we check that again here
2121 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002122 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002123 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2124 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125}
2126
Vishnu Nair4351ad52019-02-11 14:13:02 -08002127void SurfaceFlinger::computeLayerBounds() {
2128 for (const auto& pair : mDisplays) {
2129 const auto& displayDevice = pair.second;
2130 const auto display = displayDevice->getCompositionDisplay();
2131 for (const auto& layer : mDrawingState.layersSortedByZ) {
2132 // only consider the layers on the given layer stack
2133 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002134 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002135 }
2136
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002137 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2138 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002139 }
2140 }
2141}
2142
David Sodmanfa9b2af2017-12-24 13:28:59 -08002143void SurfaceFlinger::postFrame()
2144{
2145 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002146 const auto display = getDefaultDisplayDeviceLocked();
2147 if (display && getHwComposer().isConnected(*display->getId())) {
2148 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002149 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2150 logFrameStats();
2151 }
2152 }
2153}
2154
Mathias Agopian87baae12012-07-31 12:38:26 -07002155void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002156{
Mathias Agopian841cde52012-03-01 15:44:37 -08002157 ATRACE_CALL();
2158
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002159 // here we keep a copy of the drawing state (that is the state that's
2160 // going to be overwritten by handleTransactionLocked()) outside of
2161 // mStateLock so that the side-effects of the State assignment
2162 // don't happen with mStateLock held (which can cause deadlocks).
2163 State drawingState(mDrawingState);
2164
Mathias Agopianca4d3602011-05-19 15:38:14 -07002165 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002166 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167
Mathias Agopianca4d3602011-05-19 15:38:14 -07002168 // Here we're guaranteed that some transaction flags are set
2169 // so we can call handleTransactionLocked() unconditionally.
2170 // We call getTransactionFlags(), which will also clear the flags,
2171 // with mStateLock held to guarantee that mCurrentState won't change
2172 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002173
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002174 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002175 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002176 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002177
Mathias Agopianca4d3602011-05-19 15:38:14 -07002178 mDebugInTransaction = 0;
2179 invalidateHwcGeometry();
2180 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002181}
2182
Lloyd Piqueba04e622017-12-14 17:11:26 -08002183void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2184 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002185 const std::optional<DisplayIdentificationInfo> info =
2186 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002187
Dominik Laskowski075d3172018-05-24 15:50:06 -07002188 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002189 continue;
2190 }
2191
Lloyd Piqueba04e622017-12-14 17:11:26 -08002192 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002193 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002194 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002195 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2196 initScheduler(info->id);
2197 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002198 mPhysicalDisplayTokens[info->id] = new BBinder();
2199 DisplayDeviceState state;
2200 state.displayId = info->id;
2201 state.isSecure = true; // All physical displays are currently considered secure.
2202 state.displayName = info->name;
2203 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2204 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002205 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002206 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002207 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002208
Dominik Laskowski075d3172018-05-24 15:50:06 -07002209 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2210 if (index >= 0) {
2211 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2212 mInterceptor->saveDisplayDeletion(state.sequenceId);
2213 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002214 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216 }
2217
2218 processDisplayChangesLocked();
2219 }
2220
2221 mPendingHotplugEvents.clear();
2222}
2223
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002224void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002225 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2226 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002227}
2228
Lloyd Pique99d3da52018-01-22 17:48:03 -08002229sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002230 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002231 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002232 const sp<IGraphicBufferProducer>& producer) {
2233 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002234 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002235 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002236 creationArgs.isSecure = state.isSecure;
2237 creationArgs.displaySurface = dispSurface;
2238 creationArgs.hasWideColorGamut = false;
2239 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002240 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002241
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002242 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002243 creationArgs.isPrimary = isInternalDisplay;
2244
2245 if (useColorManagement && displayId) {
2246 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002247 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002248 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002249 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002250 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002251
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002253 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002254 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255 }
tangrobin6753a022018-08-10 10:58:54 +08002256 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002257
Dominik Laskowski075d3172018-05-24 15:50:06 -07002258 if (displayId) {
2259 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002260 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002261 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002262 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263
Lloyd Pique90c115d2018-09-18 21:39:42 -07002264 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002266 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267
Lloyd Pique99d3da52018-01-22 17:48:03 -08002268 // Make sure that composition can never be stalled by a virtual display
2269 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002270 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002271 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2273 }
2274
Dominik Laskowski718f9602019-11-09 20:01:35 -08002275 creationArgs.physicalOrientation =
2276 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002277
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002279 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280
Lloyd Pique90c115d2018-09-18 21:39:42 -07002281 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282
2283 if (maxFrameBufferAcquiredBuffers >= 3) {
2284 nativeWindowSurface->preallocateBuffers();
2285 }
2286
2287 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002289 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002291 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002293 display->getCompositionDisplay()->setColorProfile(
2294 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2295 RenderIntent::COLORIMETRIC,
2296 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002297 if (!state.isVirtual()) {
2298 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002299 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2300 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002301 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002302
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 display->setLayerStack(state.layerStack);
2304 display->setProjection(state.orientation, state.viewport, state.frame);
2305 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002306
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002307 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002308}
2309
Lloyd Pique347200f2017-12-14 17:00:15 -08002310void SurfaceFlinger::processDisplayChangesLocked() {
2311 // here we take advantage of Vector's copy-on-write semantics to
2312 // improve performance by skipping the transaction entirely when
2313 // know that the lists are identical
2314 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2315 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2316 if (!curr.isIdenticalTo(draw)) {
2317 mVisibleRegionsDirty = true;
2318 const size_t cc = curr.size();
2319 size_t dc = draw.size();
2320
2321 // find the displays that were removed
2322 // (ie: in drawing state but not in current state)
2323 // also handle displays that changed
2324 // (ie: displays that are in both lists)
2325 for (size_t i = 0; i < dc;) {
2326 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2327 if (j < 0) {
2328 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002329 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002330 // Save display ID before disconnecting.
2331 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002332 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002333
2334 if (!display->isVirtual()) {
2335 LOG_ALWAYS_FATAL_IF(!displayId);
2336 dispatchDisplayHotplugEvent(displayId->value, false);
2337 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002339
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002340 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002341 } else {
2342 // this display is in both lists. see if something changed.
2343 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002344 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002345 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2346 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2347 if (state_binder != draw_binder) {
2348 // changing the surface is like destroying and
2349 // recreating the DisplayDevice, so we just remove it
2350 // from the drawing state, so that it get re-added
2351 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002352 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002353 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002355 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002356 mDrawingState.displays.removeItemsAt(i);
2357 dc--;
2358 // at this point we must loop to the next item
2359 continue;
2360 }
2361
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002364 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002365 }
2366 if ((state.orientation != draw[i].orientation) ||
2367 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002368 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002369 }
2370 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002372 }
2373 }
2374 }
2375 ++i;
2376 }
2377
2378 // find displays that were added
2379 // (ie: in current state but not in drawing state)
2380 for (size_t i = 0; i < cc; i++) {
2381 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2382 const DisplayDeviceState& state(curr[i]);
2383
Lloyd Pique542307f2018-10-19 13:24:08 -07002384 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002385 sp<IGraphicBufferProducer> producer;
2386 sp<IGraphicBufferProducer> bqProducer;
2387 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002388 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002389
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002391 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 // Virtual displays without a surface are dormant:
2393 // they have external state (layer stack, projection,
2394 // etc.) but no internal state (i.e. a DisplayDevice).
2395 if (state.surface != nullptr) {
2396 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002397 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002398 int width = 0;
2399 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2400 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2401 int height = 0;
2402 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2403 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2404 int intFormat = 0;
2405 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2406 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002407 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002408
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 displayId =
2410 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002411 }
2412
2413 // TODO: Plumb requested format back up to consumer
2414
2415 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002416 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002417 bqProducer, bqConsumer,
2418 state.displayName);
2419
2420 dispSurface = vds;
2421 producer = vds;
2422 }
2423 } else {
2424 ALOGE_IF(state.surface != nullptr,
2425 "adding a supported display, but rendering "
2426 "surface is provided (%p), ignoring it",
2427 state.surface.get());
2428
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 displayId = state.displayId;
2430 LOG_ALWAYS_FATAL_IF(!displayId);
2431 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002432 producer = bqProducer;
2433 }
2434
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002435 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002436 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002437 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002438 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002439 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002440 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002442 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002443 }
2444 }
2445 }
2446 }
2447 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002448
2449 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002450}
2451
Mathias Agopian87baae12012-07-31 12:38:26 -07002452void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002453{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002454 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2455
Dan Stoza7dde5992015-05-22 09:51:44 -07002456 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002457 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2458 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002459 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002460
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 /*
2462 * Traversal of the children
2463 * (perform the transaction for each of them if needed)
2464 */
2465
Marissa Wall06255332019-03-27 13:48:27 -07002466 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002467 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002469 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470
2471 const uint32_t flags = layer->doTransaction(0);
2472 if (flags & Layer::eVisibleRegion)
2473 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002474
2475 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002476 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002477 }
Robert Carr2047fae2016-11-28 14:09:09 -08002478 });
Marissa Wall06255332019-03-27 13:48:27 -07002479 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 }
2481
2482 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002483 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 */
2485
Mathias Agopiane57f2922012-08-09 16:29:12 -07002486 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002491 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002492 // The transform hint might have changed for some layers
2493 // (either because a display has changed, or because a layer
2494 // as changed).
2495 //
2496 // Walk through all the layers in currentLayers,
2497 // and update their transform hint.
2498 //
2499 // If a layer is visible only on a single display, then that
2500 // display is used to calculate the hint, otherwise we use the
2501 // default display.
2502 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002503 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002504 // the hint is set before we acquire a buffer from the surface texture.
2505 //
2506 // NOTE: layer transactions have taken place already, so we use their
2507 // drawing state. However, SurfaceFlinger's own transaction has not
2508 // happened yet, so we must use the current state layer list
2509 // (soon to become the drawing state list).
2510 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002511 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002512 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002513 bool first = true;
2514 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002515 // NOTE: we rely on the fact that layers are sorted by
2516 // layerStack first (so we don't have to traverse the list
2517 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002518 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002519 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002520 currentlayerStack = layerStack;
2521 // figure out if this layerstack is mirrored
2522 // (more than one display) if so, pick the default display,
2523 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002524 hintDisplay = nullptr;
2525 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002526 if (display->getCompositionDisplay()
2527 ->belongsInOutput(layer->getLayerStack(),
2528 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002529 if (hintDisplay) {
2530 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002531 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002533 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002534 }
2535 }
2536 }
2537 }
Chet Haase91d25932013-04-11 15:24:55 -07002538
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002539 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002540 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2541 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002542
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002543 // could be null when this layer is using a layerStack
2544 // that is not visible on any display. Also can occur at
2545 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002546 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002547 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002548
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002549 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002550 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 if (hintDisplay) {
2552 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002553 }
Robert Carr2047fae2016-11-28 14:09:09 -08002554
2555 first = false;
2556 });
Mathias Agopian84300952012-11-21 16:02:13 -08002557 }
2558
2559
Mathias Agopian3559b072012-08-15 13:46:03 -07002560 /*
2561 * Perform our own transaction if needed
2562 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002563
2564 if (mLayersAdded) {
2565 mLayersAdded = false;
2566 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002567 mVisibleRegionsDirty = true;
2568 }
2569
2570 // some layers might have been removed, so
2571 // we need to update the regions they're exposing.
2572 if (mLayersRemoved) {
2573 mLayersRemoved = false;
2574 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002575 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002576 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002577 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002578 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002579 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002580 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002581 }
Robert Carr2047fae2016-11-28 14:09:09 -08002582 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 }
2584
Vishnu Nairec0ab382019-02-13 15:32:56 -08002585 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002587}
2588
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002589void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002590 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002591 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002592 return;
2593 }
2594
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002595 if (mVisibleRegionsDirty || mInputInfoChanged) {
2596 mInputInfoChanged = false;
2597 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002598 } else if (mInputWindowCommands.syncInputWindows) {
2599 // If the caller requested to sync input windows, but there are no
2600 // changes to input windows, notify immediately.
2601 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002602 }
2603
Arthur Hung6cbb9752019-09-05 16:38:18 +08002604 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002605}
2606
2607void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002608 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002609
2610 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2611 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002612 // When calculating the screen bounds we ignore the transparent region since it may
2613 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002614 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002615 }
2616 });
chaviw291d88a2019-02-14 10:33:58 -08002617
2618 mInputFlinger->setInputWindows(inputHandles,
2619 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2620 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002621}
2622
Vishnu Nairec0ab382019-02-13 15:32:56 -08002623void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002624 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002625 mPendingInputWindowCommands.clear();
2626}
2627
Riley Andrews03414a12014-07-01 14:22:59 -07002628void SurfaceFlinger::updateCursorAsync()
2629{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002630 compositionengine::CompositionRefreshArgs refreshArgs;
2631 for (const auto& [_, display] : mDisplays) {
2632 if (display->getId()) {
2633 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002634 }
2635 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002636
2637 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002638}
2639
Ady Abraham2139f732019-11-13 18:56:40 -08002640void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2641 Scheduler::ConfigEvent event) {
2642 Mutex::Autolock lock(mStateLock);
2643 changeRefreshRateLocked(refreshRate, event);
2644}
2645
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002646void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2647 if (mScheduler) {
2648 // In practice it's not allowed to hotplug in/out the primary display once it's been
2649 // connected during startup, but some tests do it, so just warn and return.
2650 ALOGW("Can't re-init scheduler");
2651 return;
2652 }
2653
Ady Abraham2139f732019-11-13 18:56:40 -08002654 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002655 mRefreshRateConfigs =
2656 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2657 getHwComposer().getConfigs(
2658 primaryDisplayId),
2659 currentConfig);
2660 mRefreshRateStats =
2661 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2662 currentConfig, HWC_POWER_MODE_OFF);
2663 mRefreshRateStats->setConfigMode(currentConfig);
2664
Ady Abraham9e16a482019-12-03 17:19:41 -08002665 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2666
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002667 // start the EventThread
2668 mScheduler =
2669 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002670 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002671 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002672 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002673 impl::EventThread::InterceptVSyncsCallback());
2674 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002675 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002676 [this](nsecs_t timestamp) {
2677 mInterceptor->saveVSyncEvent(timestamp);
2678 });
2679
2680 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2681 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002682 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002683
2684 mRegionSamplingThread =
2685 new RegionSamplingThread(*this, *mScheduler,
2686 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002687 // Dispatch a config change request for the primary display on scheduler
2688 // initialization, so that the EventThreads always contain a reference to a
2689 // prior configuration.
2690 //
2691 // This is a bit hacky, but this avoids a back-pointer into the main SF
2692 // classes from EventThread, and there should be no run-time binder cost
2693 // anyway since there are no connected apps at this point.
2694 const nsecs_t vsyncPeriod =
2695 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2696 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2697 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002698}
2699
Mathias Agopian4fec8732012-06-29 14:12:52 -07002700void SurfaceFlinger::commitTransaction()
2701{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002702 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002703
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002704 mTransactionPending = false;
2705 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002706 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707}
2708
Lloyd Pique58e24a32019-08-01 15:50:14 -07002709void SurfaceFlinger::commitTransactionLocked() {
2710 if (!mLayersPendingRemoval.isEmpty()) {
2711 // Notify removed layers now that they can't be drawn from
2712 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002713 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002714
2715 // Ensure any buffers set to display on any children are released.
2716 if (l->isRemovedFromCurrentState()) {
2717 l->latchAndReleaseBuffer();
2718 }
2719
2720 // If the layer has been removed and has no parent, then it will not be reachable
2721 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2722 // ensure we can copy its current to drawing state.
2723 if (!l->getParent()) {
2724 mOffscreenLayers.emplace(l.get());
2725 }
2726 }
2727 mLayersPendingRemoval.clear();
2728 }
2729
2730 // If this transaction is part of a window animation then the next frame
2731 // we composite should be considered an animation as well.
2732 mAnimCompositionPending = mAnimTransactionPending;
2733
2734 mDrawingState = mCurrentState;
2735 // clear the "changed" flags in current state
2736 mCurrentState.colorMatrixChanged = false;
2737
2738 mDrawingState.traverseInZOrder([&](Layer* layer) {
2739 layer->commitChildList();
2740
2741 // If the layer can be reached when traversing mDrawingState, then the layer is no
2742 // longer offscreen. Remove the layer from the offscreenLayer set.
2743 if (mOffscreenLayers.count(layer)) {
2744 mOffscreenLayers.erase(layer);
2745 }
2746 });
2747
2748 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002749 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002750}
2751
Nataniel Borges2b796da2019-02-15 13:32:18 -08002752void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2753 if (mTracingEnabledChanged) {
2754 mTracingEnabled = mTracing.isEnabled();
2755 mTracingEnabledChanged = false;
2756 }
2757
2758 // Synchronize with Tracing thread
2759 std::unique_lock<std::mutex> lock;
2760 if (mTracingEnabled) {
2761 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2762 }
2763
2764 lockedOperation();
2765
2766 // Synchronize with Tracing thread
2767 if (mTracingEnabled) {
2768 lock.unlock();
2769 }
2770}
2771
chaviw74d90ad2019-04-26 14:45:26 -07002772void SurfaceFlinger::commitOffscreenLayers() {
2773 for (Layer* offscreenLayer : mOffscreenLayers) {
2774 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2775 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2776 if (!trFlags) return;
2777
2778 layer->doTransaction(0);
2779 layer->commitChildList();
2780 });
2781 }
2782}
2783
Chia-I Wuab0c3192017-08-01 11:29:00 -07002784void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002785 for (const auto& [token, displayDevice] : mDisplays) {
2786 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002787 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002788 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002789 }
2790 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002791}
2792
Dan Stoza6b9454d2014-11-07 16:00:59 -08002793bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794{
Ady Abraham09bd3922019-04-08 10:44:56 -07002795 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 ALOGV("handlePageFlip");
2797
Brian Andersond6927fb2016-07-23 23:37:30 -07002798 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799
Mathias Agopian4fec8732012-06-29 14:12:52 -07002800 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002802 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002803
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002804 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2805
Eric Penner51c59cd2014-07-28 19:51:58 -07002806 // Store the set of layers that need updates. This set must not change as
2807 // buffers are being latched, as this could result in a deadlock.
2808 // Example: Two producers share the same command stream and:
2809 // 1.) Layer 0 is latched
2810 // 2.) Layer 0 gets a new frame
2811 // 2.) Layer 1 gets a new frame
2812 // 3.) Layer 1 is latched.
2813 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2814 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002815 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002816 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002817 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002818 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002819 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002820 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002821 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002822 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002823 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002824 } else {
2825 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002826 }
Robert Carr2047fae2016-11-28 14:09:09 -08002827 });
2828
chaviw49a108c2019-08-12 11:23:06 -07002829 // The client can continue submitting buffers for offscreen layers, but they will not
2830 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2831 // layers to ensure dequeueBuffer doesn't block indefinitely.
2832 for (Layer* offscreenLayer : mOffscreenLayers) {
2833 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2834 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2835 }
2836
Lloyd Piquef2c79392018-12-20 16:23:33 -08002837 if (!mLayersWithQueuedFrames.empty()) {
2838 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2839 // writes to Layer current state. See also b/119481871
2840 Mutex::Autolock lock(mStateLock);
2841
2842 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002843 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002844 mLayersPendingRefresh.push_back(layer);
2845 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002846 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002847 if (layer->isBufferLatched()) {
2848 newDataLatched = true;
2849 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002850 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002851 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002852
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002853 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002854
2855 // If we will need to wake up at some time in the future to deal with a
2856 // queued frame that shouldn't be displayed during this vsync period, wake
2857 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002858 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002859 signalLayerUpdate();
2860 }
2861
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002862 // enter boot animation on first buffer latch
2863 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2864 ALOGI("Enter boot animation");
2865 mBootStage = BootStage::BOOTANIMATION;
2866 }
2867
chaviw74b03172019-08-19 11:09:03 -07002868 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2869
Dan Stoza6b9454d2014-11-07 16:00:59 -08002870 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002871 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872}
2873
Mathias Agopianad456f92011-01-13 17:53:01 -08002874void SurfaceFlinger::invalidateHwcGeometry()
2875{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002876 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002877}
2878
Robert Carrc0df3122019-04-11 13:18:21 -07002879status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2880 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2881 const sp<IBinder>& parentHandle,
2882 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002883 // add this layer to the current state list
2884 {
2885 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002886 sp<Layer> parent;
2887 if (parentHandle != nullptr) {
2888 parent = fromHandle(parentHandle);
2889 if (parent == nullptr) {
2890 return NAME_NOT_FOUND;
2891 }
2892 } else {
2893 parent = parentLayer;
2894 }
2895
Robert Carr1f0a16a2016-10-24 16:27:39 -07002896 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002897 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002898 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002899 return NO_MEMORY;
2900 }
Robert Carrc0df3122019-04-11 13:18:21 -07002901
2902 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2903
Robert Carrb89ea9d2018-12-10 13:01:14 -08002904 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002906 } else if (parent == nullptr) {
2907 lbc->onRemovedFromCurrentState();
2908 } else if (parent->isRemovedFromCurrentState()) {
2909 parent->addChild(lbc);
2910 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002911 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 parent->addChild(lbc);
2913 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002914
Yiwei Zhang243b3782018-05-15 17:40:04 -07002915 if (gbc != nullptr) {
2916 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2917 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2918 mMaxGraphicBufferProducerListSize,
2919 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2920 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002921 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002922 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002924 }
2925
Mathias Agopian96f08192010-06-02 23:28:45 -07002926 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002927 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002928
Dan Stoza7d89d062015-04-30 13:29:25 -07002929 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002930}
2931
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002932uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002933 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002934}
2935
Mathias Agopian3f844832013-08-07 21:24:32 -07002936uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002937 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938}
2939
Mathias Agopian3f844832013-08-07 21:24:32 -07002940uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002941 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002942}
2943
2944uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002945 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002946 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002947 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002949 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950 }
2951 return old;
2952}
2953
Marissa Wall713b63f2018-10-17 15:42:43 -07002954bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002955 // to prevent onHandleDestroyed from being called while the lock is held,
2956 // we must keep a copy of the transactions (specifically the composer
2957 // states) around outside the scope of the lock
2958 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002959 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002960 {
2961 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002962
Valerie Haufce31b82019-04-30 16:41:14 -07002963 auto it = mTransactionQueues.begin();
2964 while (it != mTransactionQueues.end()) {
2965 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002966
Valerie Haufce31b82019-04-30 16:41:14 -07002967 while (!transactionQueue.empty()) {
2968 const auto& transaction = transactionQueue.front();
2969 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002970 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002971 transaction.states)) {
2972 setTransactionFlags(eTransactionFlushNeeded);
2973 break;
2974 }
2975 transactions.push_back(transaction);
2976 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2977 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002978 transaction.buffer, transaction.postTime,
2979 transaction.privileged, transaction.hasListenerCallbacks,
2980 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002981 transactionQueue.pop();
2982 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002983 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002984
Valerie Haufce31b82019-04-30 16:41:14 -07002985 if (transactionQueue.empty()) {
2986 it = mTransactionQueues.erase(it);
2987 mTransactionCV.broadcast();
2988 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002989 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002990 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002991 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002992 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002993 return flushedATransaction;
2994}
2995
2996bool SurfaceFlinger::transactionFlushNeeded() {
2997 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002998}
2999
chaviwca27f252018-02-06 16:46:39 -08003000
Marissa Wall17b4e452018-12-26 16:32:34 -08003001bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003002 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003003 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003004 if (!useCachedExpectedPresentTime)
3005 populateExpectedPresentTime();
3006
3007 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003008 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3009 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3010 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3011 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3012 return false;
3013 }
3014
Marissa Wall713b63f2018-10-17 15:42:43 -07003015 for (const ComposerState& state : states) {
3016 const layer_state_t& s = state.state;
3017 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3018 continue;
3019 }
3020 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003021 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003022 }
3023 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003024 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003025}
3026
Valerie Hau9dab9732019-08-20 09:29:25 -07003027void SurfaceFlinger::setTransactionState(
3028 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3029 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3030 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3031 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003032 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003033
Valerie Haubc6ddb12019-03-08 11:10:15 -08003034 const int64_t postTime = systemTime();
3035
Robert Carr14167e02019-02-13 13:50:55 -08003036 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3037
Mathias Agopian698c0872011-06-28 19:09:31 -07003038 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003039
Marissa Wall713b63f2018-10-17 15:42:43 -07003040 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003041 auto itr = mTransactionQueues.find(applyToken);
3042 // if this is an animation frame, wait until prior animation frame has
3043 // been applied by SF
3044 if (flags & eAnimation) {
3045 while (itr != mTransactionQueues.end()) {
3046 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3047 if (CC_UNLIKELY(err != NO_ERROR)) {
3048 ALOGW_IF(err == TIMED_OUT,
3049 "setTransactionState timed out "
3050 "waiting for animation frame to apply");
3051 break;
3052 }
3053 itr = mTransactionQueues.find(applyToken);
3054 }
3055 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003056
3057 // Expected present time is computed and cached on invalidate, so it may be stale.
3058 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3059 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003060 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003061 uncacheBuffer, postTime, privileged,
3062 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003063 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003064 return;
3065 }
3066
Valerie Haubc6ddb12019-03-08 11:10:15 -08003067 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003068 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3069 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003070}
3071
Valerie Hau9dab9732019-08-20 09:29:25 -07003072void SurfaceFlinger::applyTransactionState(
3073 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3074 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3075 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3076 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3077 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003078 uint32_t transactionFlags = 0;
3079
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003080 if (flags & eAnimation) {
3081 // For window updates that are part of an animation we must wait for
3082 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003083 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003084 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003085 if (CC_UNLIKELY(err != NO_ERROR)) {
3086 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003087 // caller after a few seconds.
3088 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3089 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003090 mAnimTransactionPending = false;
3091 break;
3092 }
3093 }
3094 }
3095
chaviwca27f252018-02-06 16:46:39 -08003096 for (const DisplayState& display : displays) {
3097 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003098 }
3099
Valerie Hau9dab9732019-08-20 09:29:25 -07003100 // start and end registration for listeners w/ no surface so they can get their callback. Note
3101 // that listeners with SurfaceControls will start registration during setClientStateLocked
3102 // below.
3103 for (const auto& listener : listenerCallbacks) {
3104 mTransactionCompletedThread.startRegistration(listener);
3105 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003106 }
3107
Valerie Hau9dab9732019-08-20 09:29:25 -07003108 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003109 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003110 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003111 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3112 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003113 }
3114
Valerie Hau9dab9732019-08-20 09:29:25 -07003115 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003116 mTransactionCompletedThread.endRegistration(listenerCallback);
3117 }
3118
Marissa Walle2ffb422018-10-12 11:33:52 -07003119 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003120 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003121 mTransactionCompletedThread.sendCallbacks();
3122 }
3123 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003124
chaviw273171b2018-12-26 11:46:30 -08003125 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3126
Marissa Wall947d34e2019-03-29 14:03:53 -07003127 if (uncacheBuffer.isValid()) {
3128 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003129 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003130 }
3131
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003132 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3133 // anyway. This can be used as a flush mechanism for previous async transactions.
3134 // Empty animation transaction can be used to simulate back-pressure, so also force a
3135 // transaction for empty animation transactions.
3136 if (transactionFlags == 0 &&
3137 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003138 transactionFlags = eTransactionNeeded;
3139 }
3140
Marissa Wall06255332019-03-27 13:48:27 -07003141 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3142 // so we don't have to wake up again next frame to preform an uneeded traversal.
3143 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3144 transactionFlags = transactionFlags & (~eTraversalNeeded);
3145 mTraversalNeededMainThread = true;
3146 }
3147
Mathias Agopian386aa982011-11-07 21:58:03 -08003148 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003149 if (mInterceptor->isEnabled()) {
3150 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003151 }
Irvel468051e2016-06-13 16:44:44 -07003152
Mathias Agopian386aa982011-11-07 21:58:03 -08003153 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003154 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3155 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003156 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003157
3158 // if this is a synchronous transaction, wait for it to take effect
3159 // before returning.
3160 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003161 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003162 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003163 if (flags & eAnimation) {
3164 mAnimTransactionPending = true;
3165 }
chaviw4fe36852019-04-15 16:25:49 -07003166 if (mPendingInputWindowCommands.syncInputWindows) {
3167 mPendingSyncInputWindows = true;
3168 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003169
3170 // applyTransactionState can be called by either the main SF thread or by
3171 // another process through setTransactionState. While a given process may wish
3172 // to wait on synchronous transactions, the main SF thread should never
3173 // be blocked. Therefore, we only wait if isMainThread is false.
3174 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003175 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3176 if (CC_UNLIKELY(err != NO_ERROR)) {
3177 // just in case something goes wrong in SF, return to the
3178 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003179 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3180 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003181 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003182 break;
3183 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003184 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 }
3186}
3187
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003188uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3189 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3190 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003191
Mathias Agopiane57f2922012-08-09 16:29:12 -07003192 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003193 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3194
3195 const uint32_t what = s.what;
3196 if (what & DisplayState::eSurfaceChanged) {
3197 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3198 state.surface = s.surface;
3199 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003200 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003201 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003202 if (what & DisplayState::eLayerStackChanged) {
3203 if (state.layerStack != s.layerStack) {
3204 state.layerStack = s.layerStack;
3205 flags |= eDisplayTransactionNeeded;
3206 }
3207 }
3208 if (what & DisplayState::eDisplayProjectionChanged) {
3209 if (state.orientation != s.orientation) {
3210 state.orientation = s.orientation;
3211 flags |= eDisplayTransactionNeeded;
3212 }
3213 if (state.frame != s.frame) {
3214 state.frame = s.frame;
3215 flags |= eDisplayTransactionNeeded;
3216 }
3217 if (state.viewport != s.viewport) {
3218 state.viewport = s.viewport;
3219 flags |= eDisplayTransactionNeeded;
3220 }
3221 }
3222 if (what & DisplayState::eDisplaySizeChanged) {
3223 if (state.width != s.width) {
3224 state.width = s.width;
3225 flags |= eDisplayTransactionNeeded;
3226 }
3227 if (state.height != s.height) {
3228 state.height = s.height;
3229 flags |= eDisplayTransactionNeeded;
3230 }
3231 }
3232
Mathias Agopiane57f2922012-08-09 16:29:12 -07003233 return flags;
3234}
3235
Robert Carr14167e02019-02-13 13:50:55 -08003236bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003237 IPCThreadState* ipc = IPCThreadState::self();
3238 const int pid = ipc->getCallingPid();
3239 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003240 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003241 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003242 return false;
3243 }
3244 return true;
3245}
3246
Marissa Wall3dad52d2019-03-22 14:03:19 -07003247uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003248 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3249 bool privileged,
3250 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003251 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003252
Valerie Hau9dab9732019-08-20 09:29:25 -07003253 for (auto& listener : s.listeners) {
3254 // note that startRegistration will not re-register if the listener has
3255 // already be registered for a prior surface control
3256 mTransactionCompletedThread.startRegistration(listener);
3257 listenerCallbacks.insert(listener);
3258 }
3259
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003260 sp<Layer> layer = nullptr;
3261 if (s.surface) {
3262 layer = fromHandle(s.surface);
3263 } else {
3264 // The client may provide us a null handle. Treat it as if the layer was removed.
3265 ALOGW("Attempt to set client state with a null layer handle");
3266 }
chaviw8b3871a2017-11-01 17:41:01 -07003267 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003268 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003269 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003270 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003271 }
chaviw8b3871a2017-11-01 17:41:01 -07003272 return 0;
3273 }
3274
chaviw8b3871a2017-11-01 17:41:01 -07003275 uint32_t flags = 0;
3276
Garfield Tan8a3083e2018-12-03 13:21:07 -08003277 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003278
3279 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3280 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003281 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003282 layer->pushPendingState();
3283 }
3284
chaviw8b3871a2017-11-01 17:41:01 -07003285 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003286 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003287 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003288 }
chaviw8b3871a2017-11-01 17:41:01 -07003289 }
3290 if (what & layer_state_t::eLayerChanged) {
3291 // NOTE: index needs to be calculated before we update the state
3292 const auto& p = layer->getParent();
3293 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003294 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003295 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003296 mCurrentState.layersSortedByZ.removeAt(idx);
3297 mCurrentState.layersSortedByZ.add(layer);
3298 // we need traversal (state changed)
3299 // AND transaction (list changed)
3300 flags |= eTransactionNeeded|eTraversalNeeded;
3301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 } else {
3303 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003304 flags |= eTransactionNeeded|eTraversalNeeded;
3305 }
3306 }
chaviw8b3871a2017-11-01 17:41:01 -07003307 }
3308 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003309 // NOTE: index needs to be calculated before we update the state
3310 const auto& p = layer->getParent();
3311 if (p == nullptr) {
3312 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3313 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3314 mCurrentState.layersSortedByZ.removeAt(idx);
3315 mCurrentState.layersSortedByZ.add(layer);
3316 // we need traversal (state changed)
3317 // AND transaction (list changed)
3318 flags |= eTransactionNeeded|eTraversalNeeded;
3319 }
3320 } else {
3321 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3322 flags |= eTransactionNeeded|eTraversalNeeded;
3323 }
chaviw8b3871a2017-11-01 17:41:01 -07003324 }
3325 }
3326 if (what & layer_state_t::eSizeChanged) {
3327 if (layer->setSize(s.w, s.h)) {
3328 flags |= eTraversalNeeded;
3329 }
3330 }
3331 if (what & layer_state_t::eAlphaChanged) {
3332 if (layer->setAlpha(s.alpha))
3333 flags |= eTraversalNeeded;
3334 }
3335 if (what & layer_state_t::eColorChanged) {
3336 if (layer->setColor(s.color))
3337 flags |= eTraversalNeeded;
3338 }
Peiyong Lind3788632018-09-18 16:01:31 -07003339 if (what & layer_state_t::eColorTransformChanged) {
3340 if (layer->setColorTransform(s.colorTransform)) {
3341 flags |= eTraversalNeeded;
3342 }
3343 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003344 if (what & layer_state_t::eBackgroundColorChanged) {
3345 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3346 flags |= eTraversalNeeded;
3347 }
3348 }
chaviw8b3871a2017-11-01 17:41:01 -07003349 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003350 // TODO: b/109894387
3351 //
3352 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3353 // rotation. To see the problem observe that if we have a square parent, and a child
3354 // of the same size, then we rotate the child 45 degrees around it's center, the child
3355 // must now be cropped to a non rectangular 8 sided region.
3356 //
3357 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3358 // private API, and the WindowManager only uses rotation in one case, which is on a top
3359 // level layer in which cropping is not an issue.
3360 //
3361 // However given that abuse of rotation matrices could lead to surfaces extending outside
3362 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3363 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3364 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003365 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003366 flags |= eTraversalNeeded;
3367 }
3368 if (what & layer_state_t::eTransparentRegionChanged) {
3369 if (layer->setTransparentRegionHint(s.transparentRegion))
3370 flags |= eTraversalNeeded;
3371 }
3372 if (what & layer_state_t::eFlagsChanged) {
3373 if (layer->setFlags(s.flags, s.mask))
3374 flags |= eTraversalNeeded;
3375 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003376 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003377 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003378 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003379 if (what & layer_state_t::eCornerRadiusChanged) {
3380 if (layer->setCornerRadius(s.cornerRadius))
3381 flags |= eTraversalNeeded;
3382 }
chaviw8b3871a2017-11-01 17:41:01 -07003383 if (what & layer_state_t::eLayerStackChanged) {
3384 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3385 // We only allow setting layer stacks for top level layers,
3386 // everything else inherits layer stack from its parent.
3387 if (layer->hasParent()) {
3388 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003389 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003390 } else if (idx < 0) {
3391 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003392 "that also does not appear in the top level layer list. Something"
3393 " has gone wrong.",
3394 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003395 } else if (layer->setLayerStack(s.layerStack)) {
3396 mCurrentState.layersSortedByZ.removeAt(idx);
3397 mCurrentState.layersSortedByZ.add(layer);
3398 // we need traversal (state changed)
3399 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003400 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003401 }
3402 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003403 if (what & layer_state_t::eDeferTransaction_legacy) {
3404 if (s.barrierHandle_legacy != nullptr) {
3405 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3406 } else if (s.barrierGbp_legacy != nullptr) {
3407 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003408 if (authenticateSurfaceTextureLocked(gbp)) {
3409 const auto& otherLayer =
3410 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003411 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003412 } else {
3413 ALOGE("Attempt to defer transaction to to an"
3414 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003415 }
3416 }
chaviw8b3871a2017-11-01 17:41:01 -07003417 // We don't trigger a traversal here because if no other state is
3418 // changed, we don't want this to cause any more work
3419 }
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (what & layer_state_t::eReparentChildren) {
3421 if (layer->reparentChildren(s.reparentHandle)) {
3422 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003423 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 if (what & layer_state_t::eDetachChildren) {
3426 layer->detachChildren();
3427 }
3428 if (what & layer_state_t::eOverrideScalingModeChanged) {
3429 layer->setOverrideScalingMode(s.overrideScalingMode);
3430 // We don't trigger a traversal here because if no other state is
3431 // changed, we don't want this to cause any more work
3432 }
Marissa Wall61c58622018-07-18 10:12:20 -07003433 if (what & layer_state_t::eTransformChanged) {
3434 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3435 }
3436 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3437 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3438 flags |= eTraversalNeeded;
3439 }
3440 if (what & layer_state_t::eCropChanged) {
3441 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3442 }
Marissa Wall861616d2018-10-22 12:52:23 -07003443 if (what & layer_state_t::eFrameChanged) {
3444 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3445 }
Marissa Wall61c58622018-07-18 10:12:20 -07003446 if (what & layer_state_t::eAcquireFenceChanged) {
3447 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3448 }
3449 if (what & layer_state_t::eDataspaceChanged) {
3450 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eHdrMetadataChanged) {
3453 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3454 }
3455 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3456 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3457 }
3458 if (what & layer_state_t::eApiChanged) {
3459 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eSidebandStreamChanged) {
3462 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3463 }
Robert Carr720e5062018-07-30 17:45:14 -07003464 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003465 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003466 layer->setInputInfo(s.inputInfo);
3467 flags |= eTraversalNeeded;
3468 } else {
3469 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3470 }
Robert Carr720e5062018-07-30 17:45:14 -07003471 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003472 if (what & layer_state_t::eMetadataChanged) {
3473 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3474 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003475 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3476 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3477 flags |= eTraversalNeeded;
3478 }
3479 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003480 if (what & layer_state_t::eShadowRadiusChanged) {
3481 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3482 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003483 if (what & layer_state_t::eFrameRateSelectionPriority) {
3484 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3485 flags |= eTraversalNeeded;
3486 }
3487 }
Steven Thomas3172e202020-01-06 19:25:30 -08003488 if (what & layer_state_t::eFrameRateChanged) {
3489 if (layer->setFrameRate(s.frameRate)) flags |= eTraversalNeeded;
3490 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003491 // This has to happen after we reparent children because when we reparent to null we remove
3492 // child layers from current state and remove its relative z. If the children are reparented in
3493 // the same transaction, then we have to make sure we reparent the children first so we do not
3494 // lose its relative z order.
3495 if (what & layer_state_t::eReparent) {
3496 bool hadParent = layer->hasParent();
3497 if (layer->reparent(s.parentHandleForChild)) {
3498 if (!hadParent) {
3499 mCurrentState.layersSortedByZ.remove(layer);
3500 }
3501 flags |= eTransactionNeeded | eTraversalNeeded;
3502 }
3503 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003504 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003505 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3506 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003507 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3508 }
3509 }
Marissa Wall78b72202019-03-15 14:58:34 -07003510 bool bufferChanged = what & layer_state_t::eBufferChanged;
3511 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3512 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003513 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003514 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003515 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3516 if (success) {
3517 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3518 success = ClientCache::getInstance()
3519 .registerErasedRecipient(s.cachedBuffer,
3520 wp<ClientCache::ErasedRecipient>(this));
3521 if (!success) {
3522 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3523 }
3524 }
Marissa Wall78b72202019-03-15 14:58:34 -07003525 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003526 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003527 } else if (bufferChanged) {
3528 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003529 }
Marissa Wall78b72202019-03-15 14:58:34 -07003530 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003531 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003532 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003533 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003534 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003535 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3536 // Do not put anything that updates layer state or modifies flags after
3537 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003538 return flags;
3539}
3540
chaviw273171b2018-12-26 11:46:30 -08003541uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3542 uint32_t flags = 0;
3543 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3544 flags |= eTraversalNeeded;
3545 }
3546
chaviwa911b102019-02-14 10:18:33 -08003547 if (inputWindowCommands.syncInputWindows) {
3548 flags |= eTraversalNeeded;
3549 }
3550
Vishnu Nairec0ab382019-02-13 15:32:56 -08003551 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003552 return flags;
3553}
3554
chaviwfe94a222019-08-21 13:52:59 -07003555status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3556 sp<IBinder>* outHandle) {
3557 if (!mirrorFromHandle) {
3558 return NAME_NOT_FOUND;
3559 }
3560
3561 sp<Layer> mirrorLayer;
3562 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003563 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003564
3565 {
3566 Mutex::Autolock _l(mStateLock);
3567 mirrorFrom = fromHandle(mirrorFromHandle);
3568 if (!mirrorFrom) {
3569 return NAME_NOT_FOUND;
3570 }
3571
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003572 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3573 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003574 if (result != NO_ERROR) {
3575 return result;
3576 }
3577
3578 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3579 }
3580
3581 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3582}
3583
Marissa Wall2d814fb2019-04-09 18:52:57 +00003584status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3585 uint32_t h, PixelFormat format, uint32_t flags,
3586 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003587 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003588 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3589 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003590 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003591 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003592 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003594 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003595
Robert Carrc0df3122019-04-11 13:18:21 -07003596 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3597 "Expected only one of parentLayer or parentHandle to be non-null. "
3598 "Programmer error?");
3599
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003600 status_t result = NO_ERROR;
3601
3602 sp<Layer> layer;
3603
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003604 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003605
Evan Roskya1f1e152019-01-24 16:17:46 -08003606 bool primaryDisplayOnly = false;
3607
3608 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3609 // TODO b/64227542
3610 if (metadata.has(METADATA_WINDOW_TYPE)) {
3611 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3612 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003613 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003614 primaryDisplayOnly = true;
3615 }
3616 }
3617
Mathias Agopian3165cc22012-08-08 19:42:09 -07003618 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003619 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003620 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3621 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003622
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003624 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003625 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003626 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003627 break;
chaviw13fdc492017-06-27 12:40:18 -07003628 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003629 // check if buffer size is set for color layer.
3630 if (w > 0 || h > 0) {
3631 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3632 int(w), int(h));
3633 return BAD_VALUE;
3634 }
3635
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003636 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3637 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003638 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003639 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003640 // check if buffer size is set for container layer.
3641 if (w > 0 || h > 0) {
3642 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3643 int(w), int(h));
3644 return BAD_VALUE;
3645 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003646 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3647 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003648 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 default:
3650 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 break;
3652 }
3653
Dan Stoza7d89d062015-04-30 13:29:25 -07003654 if (result != NO_ERROR) {
3655 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003656 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003657
Evan Roskya1f1e152019-01-24 16:17:46 -08003658 if (primaryDisplayOnly) {
3659 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003660 }
3661
Robert Carrb89ea9d2018-12-10 13:01:14 -08003662 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003663 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3664 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003665 if (result != NO_ERROR) {
3666 return result;
3667 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003668 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003669
3670 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003671 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672}
3673
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003674std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3675 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003676
3677 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003678 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003679
Dan Stoza436ccf32018-06-21 12:10:12 -07003680 // Grab the state lock since we're accessing mCurrentState
3681 Mutex::Autolock lock(mStateLock);
3682
Cody Northropbc755282017-03-31 12:00:08 -06003683 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003684 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003685 while (matchFound) {
3686 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003687 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003688 if (layer->getName() == uniqueName) {
3689 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003690 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003691 }
3692 });
3693 }
3694
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003695 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003696 return uniqueName;
3697}
3698
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003699status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003700 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003701 LayerMetadata metadata, PixelFormat& format,
3702 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003703 sp<IGraphicBufferProducer>* gbp,
3704 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003706 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 case PIXEL_FORMAT_TRANSPARENT:
3708 case PIXEL_FORMAT_TRANSLUCENT:
3709 format = PIXEL_FORMAT_RGBA_8888;
3710 break;
3711 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003712 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003713 break;
3714 }
3715
chaviwb4c6e582019-08-16 14:35:07 -07003716 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003717 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003718 args.textureName = getNewTexture();
3719 {
3720 // Grab the SF state lock during this since it's the only safe way to access
3721 // RenderEngine when creating a BufferLayerConsumer
3722 // TODO: Check if this lock is still needed here
3723 Mutex::Autolock lock(mStateLock);
3724 layer = getFactory().createBufferQueueLayer(args);
3725 }
3726
Marissa Wallfd668622018-05-10 10:21:13 -07003727 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003729 *handle = layer->getHandle();
3730 *gbp = layer->getProducer();
3731 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003733
Marissa Wallfd668622018-05-10 10:21:13 -07003734 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003736}
3737
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003738status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003739 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003740 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003741 uint32_t* outTransformHint, sp<Layer>* outLayer) {
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.displayDevice = getDefaultDisplayDevice();
3744 args.textureName = getNewTexture();
3745 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003746 if (outTransformHint) {
3747 *outTransformHint = layer->getTransformHint();
3748 }
Marissa Wall61c58622018-07-18 10:12:20 -07003749 *handle = layer->getHandle();
3750 *outLayer = layer;
3751
3752 return NO_ERROR;
3753}
3754
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003755status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003756 uint32_t h, uint32_t flags, LayerMetadata metadata,
3757 sp<IBinder>* handle, sp<Layer>* outLayer) {
3758 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003760 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003761 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003762}
3763
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003764status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003765 uint32_t w, uint32_t h, uint32_t flags,
3766 LayerMetadata metadata, sp<IBinder>* handle,
3767 sp<Layer>* outLayer) {
3768 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003769 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003770 *handle = (*outLayer)->getHandle();
3771 return NO_ERROR;
3772}
3773
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003774void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003775 mLayersPendingRemoval.add(layer);
3776 mLayersRemoved = true;
3777 setTransactionFlags(eTransactionNeeded);
3778}
3779
Robert Carr695d5282018-12-18 15:27:58 -08003780void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003781{
Robert Carr2e102c92018-10-23 12:11:15 -07003782 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003783 // If a layer has a parent, we allow it to out-live it's handle
3784 // with the idea that the parent holds a reference and will eventually
3785 // be cleaned up. However no one cleans up the top-level so we do so
3786 // here.
3787 if (layer->getParent() == nullptr) {
3788 mCurrentState.layersSortedByZ.remove(layer);
3789 }
3790 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003791
3792 auto it = mLayersByLocalBinderToken.begin();
3793 while (it != mLayersByLocalBinderToken.end()) {
3794 if (it->second == layer) {
3795 it = mLayersByLocalBinderToken.erase(it);
3796 } else {
3797 it++;
3798 }
3799 }
3800
Robert Carr695d5282018-12-18 15:27:58 -08003801 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003802}
3803
Mathias Agopianb60314a2012-04-10 22:09:54 -07003804// ---------------------------------------------------------------------------
3805
Andy McFadden13a082e2012-08-24 10:16:42 -07003806void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003807 const auto display = getDefaultDisplayDeviceLocked();
3808 if (!display) return;
3809
3810 const sp<IBinder> token = display->getDisplayToken().promote();
3811 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003812
Jesse Hall01e29052013-02-19 16:13:35 -08003813 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003814 Vector<ComposerState> state;
3815 Vector<DisplayState> displays;
3816 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003817 d.what = DisplayState::eDisplayProjectionChanged |
3818 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003819 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003820 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003821 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003822 d.frame.makeInvalid();
3823 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003824 d.width = 0;
3825 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003826 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003827 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3828 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003829
Dominik Laskowskie9774092018-12-11 10:04:24 -08003830 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003831
Dominik Laskowski83b88212018-12-11 13:34:06 -08003832 const nsecs_t vsyncPeriod = getVsyncPeriod();
3833 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003834
Brian Andersond0010582017-03-07 13:20:31 -08003835 // Use phase of 0 since phase is not known.
3836 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003837 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003838 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003839}
3840
3841void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003842 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003843 postMessageAsync(
3844 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003845}
3846
Ady Abraham27c70212019-06-11 10:52:26 -07003847void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3848 if (mHWCVsyncState != enabled) {
3849 getHwComposer().setVsyncEnabled(displayId, enabled);
3850 mHWCVsyncState = enabled;
3851 }
3852}
3853
Dominik Laskowskie9774092018-12-11 10:04:24 -08003854void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003855 if (display->isVirtual()) {
3856 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003857 return;
3858 }
3859
Dominik Laskowski075d3172018-05-24 15:50:06 -07003860 const auto displayId = display->getId();
3861 LOG_ALWAYS_FATAL_IF(!displayId);
3862
Dominik Laskowski34157762018-10-31 13:07:19 -07003863 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003864
3865 int currentMode = display->getPowerMode();
3866 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003867 return;
3868 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003870 display->setPowerMode(mode);
3871
Lloyd Pique4dccc412018-01-22 17:21:36 -08003872 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003873 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003874 }
3875
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003876 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003877 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003878 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003879 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003880 mScheduler->onScreenAcquired(mAppConnectionHandle);
3881 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003882 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003883
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003884 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003885 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003886 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003887
3888 struct sched_param param = {0};
3889 param.sched_priority = 1;
3890 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3891 ALOGW("Couldn't set SCHED_FIFO on display on");
3892 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003893 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003894 // Turn off the display
3895 struct sched_param param = {0};
3896 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3897 ALOGW("Couldn't set SCHED_OTHER on display off");
3898 }
3899
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003900 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003901 mScheduler->disableHardwareVsync(true);
3902 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003903 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003904
Ady Abraham27c70212019-06-11 10:52:26 -07003905 // Make sure HWVsync is disabled before turning off the display
3906 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3907
Dominik Laskowski075d3172018-05-24 15:50:06 -07003908 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003909 mVisibleRegionsDirty = true;
3910 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003911 } else if (mode == HWC_POWER_MODE_DOZE ||
3912 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003913 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003914 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003915 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003916 mScheduler->onScreenAcquired(mAppConnectionHandle);
3917 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003918 }
3919 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3920 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003921 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003922 mScheduler->disableHardwareVsync(true);
3923 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003924 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003925 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003926 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003927 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003928 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003929 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003930
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003931 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003932 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003933 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003934 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003935 }
3936
Dominik Laskowski34157762018-10-31 13:07:19 -07003937 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003938}
3939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003940void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003941 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003942 const auto display = getDisplayDevice(displayToken);
3943 if (!display) {
3944 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3945 displayToken.get());
3946 } else if (display->isVirtual()) {
3947 ALOGW("Attempt to set power mode %d for virtual display", mode);
3948 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003949 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003950 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003952}
3953
3954// ---------------------------------------------------------------------------
3955
Dominik Laskowskic2867142019-01-21 11:33:38 -08003956status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3957 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003958 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003959
Mathias Agopianbd115332013-04-18 16:41:04 -07003960 IPCThreadState* ipc = IPCThreadState::self();
3961 const int pid = ipc->getCallingPid();
3962 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003963
Mathias Agopianbd115332013-04-18 16:41:04 -07003964 if ((uid != AID_SHELL) &&
3965 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003966 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3967 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003969 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003970 // (this would indicate SF is stuck, but we want to be able to
3971 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003972 status_t err = mStateLock.timedLock(s2ns(1));
3973 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003974 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003975 StringAppendF(&result,
3976 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3977 "(no locks held)\n",
3978 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003979 }
3980
Dominik Laskowskic2867142019-01-21 11:33:38 -08003981 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003982 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003983 {"--dispsync"s,
3984 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003985 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003986 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3987 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3988 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3989 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3990 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3991 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003992 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003993 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3994 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003995
Dominik Laskowskic2867142019-01-21 11:33:38 -08003996 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003997
Dominik Laskowski46470112019-08-02 13:13:11 -07003998 const auto it = dumpers.find(flag);
3999 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004000 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004001 } else if (!asProto) {
4002 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004003 }
4004
Mathias Agopian9795c422009-08-26 16:36:26 -07004005 if (locked) {
4006 mStateLock.unlock();
4007 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004008
Dominik Laskowski46470112019-08-02 13:13:11 -07004009 if (it == dumpers.end()) {
4010 const LayersProto layersProto = dumpProtoFromMainThread();
4011 if (asProto) {
4012 result.append(layersProto.SerializeAsString());
4013 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004014 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004015 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4016 result.append(LayerProtoParser::layerTreeToString(layerTree));
4017 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004018 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004019 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004020 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004021 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004022 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023 return NO_ERROR;
4024}
4025
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004026status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4027 if (asProto && mTracing.isEnabled()) {
4028 mTracing.writeToFileAsync();
4029 }
4030
4031 return doDump(fd, DumpArgs(), asProto);
4032}
4033
Dominik Laskowskic2867142019-01-21 11:33:38 -08004034void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004035 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004036 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004037}
4038
Dominik Laskowskic2867142019-01-21 11:33:38 -08004039void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004040 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004041
Dominik Laskowskic2867142019-01-21 11:33:38 -08004042 if (args.size() > 1) {
4043 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004044 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004045 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004046 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004047 }
Robert Carr2047fae2016-11-28 14:09:09 -08004048 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004049 } else {
4050 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004051 }
4052}
4053
Dominik Laskowskic2867142019-01-21 11:33:38 -08004054void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004055 const bool clearAll = args.size() < 2;
4056 const auto name = clearAll ? String8() : String8(args[1]);
4057
Robert Carr2047fae2016-11-28 14:09:09 -08004058 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004059 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004060 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004061 }
Robert Carr2047fae2016-11-28 14:09:09 -08004062 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004063
Svetoslavd85084b2014-03-20 10:28:31 -07004064 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065}
4066
Dominik Laskowskic2867142019-01-21 11:33:38 -08004067void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4068 mTimeStats->parseArgs(asProto, args, result);
4069}
4070
Jamie Gennis6547ff42013-07-16 20:12:42 -07004071// This should only be called from the main thread. Otherwise it would need
4072// the lock and should use mCurrentState rather than mDrawingState.
4073void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004074 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004075 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004076 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004077
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004078 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004079}
4080
Yiwei Zhang5434a782018-12-05 18:06:32 -08004081void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004082 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004083
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004084 if (isLayerTripleBufferingDisabled())
4085 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004086
Yiwei Zhang5434a782018-12-05 18:06:32 -08004087 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4088 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4089 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4090 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4091 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4092 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004093 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004094}
4095
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004096void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004097 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004098
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004099 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004100 result.append("\n");
4101
Ady Abraham9e16a482019-12-03 17:19:41 -08004102 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004103 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004104 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004105 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004106
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004107 HwcConfigIndexType defaultConfig;
4108 float minFps, maxFps;
4109 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004110 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004111 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004112 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004113 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004114 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4115 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004116
Ana Krulecc2870422019-01-29 19:00:58 -08004117 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004118}
4119
Yiwei Zhang5434a782018-12-05 18:06:32 -08004120void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4121 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004122 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4123 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004124 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004125 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004126 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004127 }
David Sodman4a36e932017-11-07 14:29:47 -08004128 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004129 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004130 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004131 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4132 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004133}
4134
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004135void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4136 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004137 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4138 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004139 for (const auto& segment : history) {
4140 if (!segment.usedThirdBuffer) {
4141 stats.twoBufferTime += segment.totalTime;
4142 }
4143 if (segment.occupancyAverage < 1.0f) {
4144 stats.doubleBufferedTime += segment.totalTime;
4145 } else if (segment.occupancyAverage < 2.0f) {
4146 stats.tripleBufferedTime += segment.totalTime;
4147 }
4148 ++stats.numSegments;
4149 stats.totalTime += segment.totalTime;
4150 }
4151}
4152
Yiwei Zhang5434a782018-12-05 18:06:32 -08004153void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4154 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004155
4156 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4157 const size_t count = currentLayers.size();
4158 for (size_t i=0 ; i<count ; i++) {
4159 currentLayers[i]->dumpFrameEvents(result);
4160 }
4161}
4162
Yiwei Zhang5434a782018-12-05 18:06:32 -08004163void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004164 result.append("Buffering stats:\n");
4165 result.append(" [Layer name] <Active time> <Two buffer> "
4166 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004167 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004168 typedef std::tuple<std::string, float, float, float> BufferTuple;
4169 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004170 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004171 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004172 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004173 if (stats.numSegments == 0) {
4174 continue;
4175 }
4176 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4177 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4178 stats.totalTime;
4179 float doubleBufferRatio = static_cast<float>(
4180 stats.doubleBufferedTime) / stats.totalTime;
4181 float tripleBufferRatio = static_cast<float>(
4182 stats.tripleBufferedTime) / stats.totalTime;
4183 sorted.insert({activeTime, {name, twoBufferRatio,
4184 doubleBufferRatio, tripleBufferRatio}});
4185 }
4186 for (const auto& sortedPair : sorted) {
4187 float activeTime = sortedPair.first;
4188 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004189 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4190 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004191 }
4192 result.append("\n");
4193}
4194
Yiwei Zhang5434a782018-12-05 18:06:32 -08004195void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004196 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004197 const auto displayId = display->getId();
4198 if (!displayId) {
4199 continue;
4200 }
4201 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004202 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004203 continue;
4204 }
4205
Yiwei Zhang5434a782018-12-05 18:06:32 -08004206 StringAppendF(&result,
4207 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4208 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004209 uint8_t port;
4210 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004211 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004212 result.append("no identification data\n");
4213 continue;
4214 }
4215
4216 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004217 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004218 continue;
4219 }
4220
4221 const auto edid = parseEdid(data);
4222 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004223 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004224 continue;
4225 }
4226
Yiwei Zhang5434a782018-12-05 18:06:32 -08004227 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004228 result.append(edid->displayName.data(), edid->displayName.length());
4229 result.append("\"\n");
4230 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004231}
4232
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004233void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4234 std::string& result) const {
4235 hwc2_display_t hwcDisplayId;
4236 uint8_t port;
4237 DisplayIdentificationData data;
4238
4239 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4240 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4241 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4242 }
4243}
4244
Yiwei Zhang5434a782018-12-05 18:06:32 -08004245void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004246 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004247 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4248 StringAppendF(&result, "DisplayColorSetting: %s\n",
4249 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004250
4251 // TODO: print out if wide-color mode is active or not
4252
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004253 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 const auto displayId = display->getId();
4255 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004256 continue;
4257 }
4258
Yiwei Zhang5434a782018-12-05 18:06:32 -08004259 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004261 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004262 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004263 }
4264
Lloyd Pique32cbe282018-10-19 13:09:22 -07004265 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 StringAppendF(&result, " Current color mode: %s (%d)\n",
4267 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004268 }
4269 result.append("\n");
4270}
4271
Vishnu Nair8406fd72019-07-30 11:29:31 -07004272LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004273 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004274 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4275 layer->writeToProto(layersProto, traceFlags);
4276 }
chaviw1d044282017-09-27 12:19:28 -07004277 return layersProto;
4278}
4279
Vishnu Nair0f085c62019-08-30 08:49:12 -07004280void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4281 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4282 // it.
4283 LayerProto* rootProto = layersProto.add_layers();
4284 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4285 rootProto->set_id(offscreenRootLayerId);
4286 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004287 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004288
4289 for (Layer* offscreenLayer : mOffscreenLayers) {
4290 // Add layer as child of the fake root
4291 rootProto->add_children(offscreenLayer->sequence);
4292
4293 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004294 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004295 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004296 }
4297}
4298
Vishnu Nair8406fd72019-07-30 11:29:31 -07004299LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4300 LayersProto layersProto;
4301 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4302 return layersProto;
4303}
4304
Vishnu Nair0f085c62019-08-30 08:49:12 -07004305void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4306 result.append("Offscreen Layers:\n");
4307 postMessageSync(new LambdaMessage([&]() {
4308 for (Layer* offscreenLayer : mOffscreenLayers) {
4309 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4310 layer->dumpCallingUidPid(result);
4311 });
4312 }
4313 }));
4314}
4315
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4317 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004318 Colorizer colorizer(colorize);
4319
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004320 // figure out if we're stuck somewhere
4321 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004322 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4324
4325 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004326 * Dump library configuration.
4327 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004328
4329 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004330 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004331 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004332 appendSfConfigString(result);
4333 appendUiConfigString(result);
4334 appendGuiConfigString(result);
4335 result.append("\n");
4336
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004337 result.append("\nDisplay identification data:\n");
4338 dumpDisplayIdentificationData(result);
4339
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004340 result.append("\nWide-Color information:\n");
4341 dumpWideColorInfo(result);
4342
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004344 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004345 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004346 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004347 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004348
Andy McFadden41d67d72014-04-25 16:58:34 -07004349 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004350 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004351 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004352 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004353 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004354
Dan Stozab90cf072015-03-05 11:05:59 -08004355 dumpStaticScreenStats(result);
4356 result.append("\n");
4357
Alec Mouri40189b02019-03-05 15:07:54 -08004358 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4359 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4360 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004361
Dan Stozae77c7662016-05-13 11:37:28 -07004362 dumpBufferingStats(result);
4363
Andy McFadden4803b742012-09-24 19:07:20 -07004364 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365 * Dump the visible layer list
4366 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004367 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004368 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004369 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4370 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004371 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004372
Chia-I Wu2f884132018-09-13 15:17:58 -07004373 {
Lloyd Pique207def92019-02-28 16:09:52 -08004374 StringAppendF(&result, "Composition layers\n");
4375 mDrawingState.traverseInZOrder([&](Layer* layer) {
4376 auto compositionLayer = layer->getCompositionLayer();
4377 if (compositionLayer) compositionLayer->dump(result);
4378 });
4379 }
4380
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004381 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004382 * Dump Display state
4383 */
4384
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004385 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004386 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004387 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004388 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004389 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004390 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004391 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004392
4393 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004394 * Dump CompositionEngine state
4395 */
4396
4397 mCompositionEngine->dump(result);
4398
4399 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004400 * Dump SurfaceFlinger global state
4401 */
4402
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004403 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004404 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004405 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004406
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004407 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004409 DebugEGLImageTracker::getInstance()->dump(result);
4410
Dominik Laskowski075d3172018-05-24 15:50:06 -07004411 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004412 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4413 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004414 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4415 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004416 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004417 StringAppendF(&result,
4418 " transaction-flags : %08x\n"
4419 " gpu_to_cpu_unsupported : %d\n",
4420 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004421
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004422 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004423 displayId && getHwComposer().isConnected(*displayId)) {
4424 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425 StringAppendF(&result,
4426 " refresh-rate : %f fps\n"
4427 " x-dpi : %f\n"
4428 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004429 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4430 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004431 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004432
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004434
Dan Stozae22aec72016-08-01 13:20:59 -07004435 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004436 * Tracing state
4437 */
4438 mTracing.dump(result);
4439 result.append("\n");
4440
4441 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004442 * HWC layer minidump
4443 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004444 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004445 const auto displayId = display->getId();
4446 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004447 continue;
4448 }
4449
Yiwei Zhang5434a782018-12-05 18:06:32 -08004450 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004451 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004452 const sp<DisplayDevice> displayDevice = display;
4453 mCurrentState.traverseInZOrder(
4454 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004455 result.append("\n");
4456 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457
4458 /*
4459 * Dump HWComposer state
4460 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004461 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004462 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004463 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004464 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004466 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004467
4468 /*
4469 * Dump gralloc state
4470 */
4471 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4472 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004473
4474 /*
4475 * Dump VrFlinger state if in use.
4476 */
4477 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4478 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004480 result.append("\n");
4481 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004482
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004483 result.append(mTimeStats->miniDump());
4484 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004485}
4486
Chia-I Wu28f320b2018-05-03 11:02:56 -07004487void SurfaceFlinger::updateColorMatrixLocked() {
4488 mat4 colorMatrix;
4489 if (mGlobalSaturationFactor != 1.0f) {
4490 // Rec.709 luma coefficients
4491 float3 luminance{0.213f, 0.715f, 0.072f};
4492 luminance *= 1.0f - mGlobalSaturationFactor;
4493 mat4 saturationMatrix = mat4(
4494 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4495 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4496 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4497 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4498 );
4499 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4500 } else {
4501 colorMatrix = mClientColorMatrix * mDaltonizer();
4502 }
4503
4504 if (mCurrentState.colorMatrix != colorMatrix) {
4505 mCurrentState.colorMatrix = colorMatrix;
4506 mCurrentState.colorMatrixChanged = true;
4507 setTransactionFlags(eTransactionNeeded);
4508 }
4509}
4510
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004511status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004512#pragma clang diagnostic push
4513#pragma clang diagnostic error "-Wswitch-enum"
4514 switch (static_cast<ISurfaceComposerTag>(code)) {
4515 // These methods should at minimum make sure that the client requested
4516 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004517 case BOOT_FINISHED:
4518 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004519 case CREATE_DISPLAY:
4520 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004521 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004522 case GET_ANIMATION_FRAME_STATS:
4523 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004524 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004525 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004526 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004527 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4528 case SET_AUTO_LOW_LATENCY_MODE:
4529 case GET_GAME_CONTENT_TYPE_SUPPORT:
4530 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004531 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004532 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004533 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004534 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004535 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004536 case NOTIFY_POWER_HINT:
4537 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004538 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4539 IPCThreadState* ipc = IPCThreadState::self();
4540 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4541 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004542 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 }
Robert Carr1db73f62016-12-21 12:58:51 -08004544 return OK;
4545 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004546 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004547 IPCThreadState* ipc = IPCThreadState::self();
4548 const int pid = ipc->getCallingPid();
4549 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004550 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4551 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004552 return PERMISSION_DENIED;
4553 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004554 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004555 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004556 // Used by apps to hook Choreographer to SurfaceFlinger.
4557 case CREATE_DISPLAY_EVENT_CONNECTION:
4558 // The following calls are currently used by clients that do not
4559 // request necessary permissions. However, they do not expose any secret
4560 // information, so it is OK to pass them.
4561 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004562 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004563 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004564 case GET_PHYSICAL_DISPLAY_IDS:
4565 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004566 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004567 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004568 case GET_DISPLAY_CONFIGS:
4569 case GET_DISPLAY_STATS:
4570 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4571 // Calling setTransactionState is safe, because you need to have been
4572 // granted a reference to Client* and Handle* to do anything with it.
4573 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004574 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004575 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004576 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004577 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004578 case IS_WIDE_COLOR_DISPLAY:
4579 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4580 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004581 return OK;
4582 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004583 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004584 case CAPTURE_SCREEN:
4585 case ADD_REGION_SAMPLING_LISTENER:
4586 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004587 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004588 IPCThreadState* ipc = IPCThreadState::self();
4589 const int pid = ipc->getCallingPid();
4590 const int uid = ipc->getCallingUid();
4591 if ((uid != AID_GRAPHICS) &&
4592 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4593 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4594 return PERMISSION_DENIED;
4595 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004596 return OK;
4597 }
4598 // The following codes are deprecated and should never be allowed to access SF.
4599 case CONNECT_DISPLAY_UNUSED:
4600 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4601 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4602 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004603 }
chaviw93df2ea2019-04-30 16:45:12 -07004604 case CAPTURE_SCREEN_BY_ID: {
4605 IPCThreadState* ipc = IPCThreadState::self();
4606 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004607 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004608 return OK;
4609 }
4610 return PERMISSION_DENIED;
4611 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004613
4614 // These codes are used for the IBinder protocol to either interrogate the recipient
4615 // side of the transaction for its canonical interface descriptor or to dump its state.
4616 // We let them pass by default.
4617 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4618 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4619 code == IBinder::SYSPROPS_TRANSACTION) {
4620 return OK;
4621 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004622 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004623 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004624 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004625 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4626 return OK;
4627 }
4628 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4629 return PERMISSION_DENIED;
4630#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004631}
4632
Ana Krulec13be8ad2018-08-21 02:43:56 +00004633status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4634 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004635 status_t credentialCheck = CheckTransactCodeCredentials(code);
4636 if (credentialCheck != OK) {
4637 return credentialCheck;
4638 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004639
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004640 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4641 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004642 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004643 IPCThreadState* ipc = IPCThreadState::self();
4644 const int uid = ipc->getCallingUid();
4645 if (CC_UNLIKELY(uid != AID_SYSTEM
4646 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004647 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004648 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004649 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004650 return PERMISSION_DENIED;
4651 }
4652 int n;
4653 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004654 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004655 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004656 return NO_ERROR;
4657 case 1002: // SHOW_UPDATES
4658 n = data.readInt32();
4659 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004660 invalidateHwcGeometry();
4661 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004663 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004664 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004665 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004666 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004667 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004668 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004669 setTransactionFlags(
4670 eTransactionNeeded|
4671 eDisplayTransactionNeeded|
4672 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004673 return NO_ERROR;
4674 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004675 case 1006:{ // send empty update
4676 signalRefresh();
4677 return NO_ERROR;
4678 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004679 case 1008: // toggle use of hw composer
4680 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004681 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004682 invalidateHwcGeometry();
4683 repaintEverything();
4684 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004685 case 1009: // toggle use of transform hint
4686 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004687 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004688 invalidateHwcGeometry();
4689 repaintEverything();
4690 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004691 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004692 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 reply->writeInt32(0);
4694 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004695 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004696 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004697 return NO_ERROR;
4698 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004699 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004700 if (!display) {
4701 return NAME_NOT_FOUND;
4702 }
4703
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004704 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004705 return NO_ERROR;
4706 }
4707 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004708 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004709 // daltonize
4710 n = data.readInt32();
4711 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004712 case 1:
4713 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4714 break;
4715 case 2:
4716 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4717 break;
4718 case 3:
4719 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4720 break;
4721 default:
4722 mDaltonizer.setType(ColorBlindnessType::None);
4723 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004724 }
4725 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004726 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004727 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004728 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004729 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004730
4731 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004732 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004733 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004734 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004735 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004736 // apply a color matrix
4737 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004738 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004739 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004740 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004741 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004742 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004743 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004744 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004745 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004746 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004747 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004748
4749 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4750 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004751 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004752 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4753 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4754 }
4755
Chia-I Wu28f320b2018-05-03 11:02:56 -07004756 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004757 return NO_ERROR;
4758 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004759 case 1016: { // Unused.
4760 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004761 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004762 case 1017: {
4763 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004764 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004765 return NO_ERROR;
4766 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004767 case 1018: { // Modify Choreographer's phase offset
4768 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004769 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004770 return NO_ERROR;
4771 }
4772 case 1019: { // Modify SurfaceFlinger's phase offset
4773 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004774 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004775 return NO_ERROR;
4776 }
Irvel468051e2016-06-13 16:44:44 -07004777 case 1020: { // Layer updates interceptor
4778 n = data.readInt32();
4779 if (n) {
4780 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004781 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004782 }
4783 else{
4784 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004785 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004786 }
4787 return NO_ERROR;
4788 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004789 case 1021: { // Disable HWC virtual displays
4790 n = data.readInt32();
4791 mUseHwcVirtualDisplays = !n;
4792 return NO_ERROR;
4793 }
Romain Guy0147a172017-06-01 13:53:56 -07004794 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004795 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004796 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004797
Chia-I Wu28f320b2018-05-03 11:02:56 -07004798 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004799 return NO_ERROR;
4800 }
Romain Guy54f154a2017-10-24 21:40:32 +01004801 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004802 int32_t colorMode;
4803
Chia-I Wu0d711262018-05-21 15:19:35 -07004804 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004805 if (data.readInt32(&colorMode) == NO_ERROR) {
4806 mForceColorMode = static_cast<ColorMode>(colorMode);
4807 }
Romain Guy54f154a2017-10-24 21:40:32 +01004808 invalidateHwcGeometry();
4809 repaintEverything();
4810 return NO_ERROR;
4811 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004812 // Deprecate, use 1030 to check whether the device is color managed.
4813 case 1024: {
4814 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004815 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004816 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004817 n = data.readInt32();
4818 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004819 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004820 Mutex::Autolock lock(mStateLock);
4821 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004822 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004823 reply->writeInt32(NO_ERROR);
4824 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004825 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004826 bool writeFile = false;
4827 {
4828 Mutex::Autolock lock(mStateLock);
4829 mTracingEnabledChanged = true;
4830 writeFile = mTracing.disable();
4831 }
4832
4833 if (writeFile) {
4834 reply->writeInt32(mTracing.writeToFile());
4835 } else {
4836 reply->writeInt32(NO_ERROR);
4837 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004838 }
4839 return NO_ERROR;
4840 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004841 case 1026: { // Get layer tracing status
4842 reply->writeBool(mTracing.isEnabled());
4843 return NO_ERROR;
4844 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004845 // Is a DisplayColorSetting supported?
4846 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004847 const auto display = getDefaultDisplayDevice();
4848 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004849 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004850 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004851
4852 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4853 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004854 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004855 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004856 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004857 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004858 reply->writeBool(true);
4859 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004860 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004861 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004862 break;
4863 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004864 reply->writeBool(
4865 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004866 break;
4867 }
4868 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004869 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004870 // Is VrFlinger active?
4871 case 1028: {
4872 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004873 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004874 return NO_ERROR;
4875 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004876 // Set buffer size for SF tracing (value in KB)
4877 case 1029: {
4878 n = data.readInt32();
4879 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4880 ALOGW("Invalid buffer size: %d KB", n);
4881 reply->writeInt32(BAD_VALUE);
4882 return BAD_VALUE;
4883 }
4884
4885 ALOGD("Updating trace buffer to %d KB", n);
4886 mTracing.setBufferSize(n * 1024);
4887 reply->writeInt32(NO_ERROR);
4888 return NO_ERROR;
4889 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004890 // Is device color managed?
4891 case 1030: {
4892 reply->writeBool(useColorManagement);
4893 return NO_ERROR;
4894 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004895 // Override default composition data space
4896 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4897 // && adb shell stop zygote && adb shell start zygote
4898 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4899 // adb shell stop zygote && adb shell start zygote
4900 case 1031: {
4901 Mutex::Autolock _l(mStateLock);
4902 n = data.readInt32();
4903 if (n) {
4904 n = data.readInt32();
4905 if (n) {
4906 Dataspace dataspace = static_cast<Dataspace>(n);
4907 if (!validateCompositionDataspace(dataspace)) {
4908 return BAD_VALUE;
4909 }
4910 mDefaultCompositionDataspace = dataspace;
4911 }
4912 n = data.readInt32();
4913 if (n) {
4914 Dataspace dataspace = static_cast<Dataspace>(n);
4915 if (!validateCompositionDataspace(dataspace)) {
4916 return BAD_VALUE;
4917 }
4918 mWideColorGamutCompositionDataspace = dataspace;
4919 }
4920 } else {
4921 // restore composition data space.
4922 mDefaultCompositionDataspace = defaultCompositionDataspace;
4923 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4924 }
4925 return NO_ERROR;
4926 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004927 // Set trace flags
4928 case 1033: {
4929 n = data.readUint32();
4930 ALOGD("Updating trace flags to 0x%x", n);
4931 mTracing.setTraceFlags(n);
4932 reply->writeInt32(NO_ERROR);
4933 return NO_ERROR;
4934 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004935 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004936 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004937 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004938 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004939 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4940 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004941 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004942 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004943 } else {
4944 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004945 }
4946 return NO_ERROR;
4947 }
Ady Abraham34392f72019-04-10 11:29:27 -07004948 case 1035: {
4949 n = data.readInt32();
4950 mDebugDisplayConfigSetByBackdoor = false;
4951 if (n >= 0) {
4952 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004953 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004954 if (result != NO_ERROR) {
4955 return result;
4956 }
4957 mDebugDisplayConfigSetByBackdoor = true;
4958 }
4959 return NO_ERROR;
4960 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 }
4962 }
4963 return err;
4964}
4965
Steven Thomas6d8110b2017-08-31 18:24:21 -07004966void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004967 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004968 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004969}
4970
Ana Krulec7d1d6832018-12-27 11:10:09 -08004971void SurfaceFlinger::repaintEverythingForHWC() {
4972 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004973 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004974}
4975
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004976// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4977class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004978public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004979 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4980 ~WindowDisconnector() {
4981 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004982 }
4983
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004984private:
4985 ANativeWindow* mWindow;
4986 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004987};
4988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004989status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004990 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08004991 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
4992 const Rect& sourceCrop, uint32_t reqWidth,
4993 uint32_t reqHeight, bool useIdentityTransform,
4994 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004995 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004996
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004997 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004998
Dominik Laskowski718f9602019-11-09 20:01:35 -08004999 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5000 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5001 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5002 renderAreaRotation = ui::Transform::ROT_0;
5003 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005004
Chia-I Wu20261cb2018-08-23 12:55:44 -07005005 sp<DisplayDevice> display;
5006 {
5007 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005008
Chia-I Wu20261cb2018-08-23 12:55:44 -07005009 display = getDisplayDeviceLocked(displayToken);
5010 if (!display) return BAD_VALUE;
5011
Chia-I Wucb023152018-08-28 12:57:23 -07005012 // set the requested width/height to the logical display viewport size
5013 // by default
5014 if (reqWidth == 0 || reqHeight == 0) {
5015 reqWidth = uint32_t(display->getViewport().width());
5016 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005017 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005018 }
5019
Peiyong Lin0e003c92018-09-17 11:09:51 -07005020 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005021 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005022
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005023 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5024 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005025 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005026 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005027}
5028
chaviw93df2ea2019-04-30 16:45:12 -07005029static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5030 switch (colorMode) {
5031 case ColorMode::DISPLAY_P3:
5032 case ColorMode::BT2100_PQ:
5033 case ColorMode::BT2100_HLG:
5034 case ColorMode::DISPLAY_BT2020:
5035 return Dataspace::DISPLAY_P3;
5036 default:
5037 return Dataspace::V0_SRGB;
5038 }
5039}
5040
5041const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5042 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5043 if (displayToken) {
5044 return getDisplayDeviceLocked(displayToken);
5045 }
5046 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5047 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005048 return getDisplayByLayerStack(displayOrLayerStack);
5049}
5050
5051const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005052 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005053 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005054 return display;
5055 }
5056 }
5057 return nullptr;
5058}
5059
5060status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5061 sp<GraphicBuffer>* outBuffer) {
5062 sp<DisplayDevice> display;
5063 uint32_t width;
5064 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005065 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005066 {
5067 Mutex::Autolock _l(mStateLock);
5068 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5069 if (!display) {
5070 return BAD_VALUE;
5071 }
5072
5073 width = uint32_t(display->getViewport().width());
5074 height = uint32_t(display->getViewport().height());
5075
Dominik Laskowski718f9602019-11-09 20:01:35 -08005076 const auto orientation = display->getOrientation();
5077 captureOrientation = ui::Transform::toRotationFlags(orientation);
5078
5079 switch (captureOrientation) {
5080 case ui::Transform::ROT_90:
5081 captureOrientation = ui::Transform::ROT_270;
5082 break;
5083
5084 case ui::Transform::ROT_270:
5085 captureOrientation = ui::Transform::ROT_90;
5086 break;
5087
5088 case ui::Transform::ROT_INVALID:
5089 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5090 captureOrientation = ui::Transform::ROT_0;
5091 break;
5092
5093 default:
5094 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005095 }
chaviw93df2ea2019-04-30 16:45:12 -07005096 *outDataspace =
5097 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5098 }
5099
5100 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5101 false /* captureSecureLayers */);
5102
5103 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5104 std::placeholders::_1);
5105 bool ignored = false;
5106 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5107 false /* useIdentityTransform */,
5108 ignored /* outCapturedSecureLayers */);
5109}
5110
Robert Carr866455f2019-04-02 16:28:26 -07005111status_t SurfaceFlinger::captureLayers(
5112 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5113 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5114 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5115 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005116 ATRACE_CALL();
5117
5118 class LayerRenderArea : public RenderArea {
5119 public:
Robert Carr578038f2018-03-09 12:25:24 -08005120 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005121 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005122 bool childrenOnly, const Rect& displayViewport)
5123 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005124 mLayer(layer),
5125 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005126 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005127 mFlinger(flinger),
5128 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005129 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005130 Rect getBounds() const override {
5131 const Layer::State& layerState(mLayer->getDrawingState());
5132 return mLayer->getBufferSize(layerState);
5133 }
Marissa Wall61c58622018-07-18 10:12:20 -07005134 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005135 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005136 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005137 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005138 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005139 }
chaviwa76b2712017-09-20 12:02:26 -07005140 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005141 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005142 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005143 Rect getSourceCrop() const override {
5144 if (mCrop.isEmpty()) {
5145 return getBounds();
5146 } else {
5147 return mCrop;
5148 }
5149 }
Robert Carr578038f2018-03-09 12:25:24 -08005150 class ReparentForDrawing {
5151 public:
5152 const sp<Layer>& oldParent;
5153 const sp<Layer>& newParent;
5154
Vishnu Nair4351ad52019-02-11 14:13:02 -08005155 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5156 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005157 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005158 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005159 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5160 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005161 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005162 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005163 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005164 };
5165
5166 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005167 const Rect sourceCrop = getSourceCrop();
5168 // no need to check rotation because there is none
5169 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5170 sourceCrop.height() != getReqHeight();
5171
Robert Carr578038f2018-03-09 12:25:24 -08005172 if (!mChildrenOnly) {
5173 mTransform = mLayer->getTransform().inverse();
5174 drawLayers();
5175 } else {
5176 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005177 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5178 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005179 // In the "childrenOnly" case we reparent the children to a screenshot
5180 // layer which has no properties set and which does not draw.
5181 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005182 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5183 "Screenshot Parent"s, w, h, 0,
5184 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005185
Vishnu Nair4351ad52019-02-11 14:13:02 -08005186 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005187 drawLayers();
5188 }
5189 }
chaviwa76b2712017-09-20 12:02:26 -07005190
chaviwa76b2712017-09-20 12:02:26 -07005191 private:
chaviw7206d492017-11-10 16:16:12 -08005192 const sp<Layer> mLayer;
5193 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005194
Peiyong Linefefaac2018-08-17 12:27:51 -07005195 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005196 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005197
5198 SurfaceFlinger* mFlinger;
5199 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005200 };
5201
Robert Carrc0df3122019-04-11 13:18:21 -07005202 int reqWidth = 0;
5203 int reqHeight = 0;
5204 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005205 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005206 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005207 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005208 {
5209 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005210
Robert Carrc0df3122019-04-11 13:18:21 -07005211 parent = fromHandle(layerHandleBinder);
5212 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5213 ALOGE("captureLayers called with an invalid or removed parent");
5214 return NAME_NOT_FOUND;
5215 }
5216
5217 const int uid = IPCThreadState::self()->getCallingUid();
5218 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5219 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5220 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5221 return PERMISSION_DENIED;
5222 }
5223
Vishnu Nairefc42e22019-12-03 17:36:12 -08005224 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005225 if (sourceCrop.width() <= 0) {
5226 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005227 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005228 }
5229
5230 if (sourceCrop.height() <= 0) {
5231 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005232 crop.bottom = parentSourceBounds.getHeight();
5233 }
5234
5235 if (crop.isEmpty() || frameScale <= 0.0f) {
5236 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5237 // crop was not specified, or an invalid frame scale was provided.
5238 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005239 }
5240 reqWidth = crop.width() * frameScale;
5241 reqHeight = crop.height() * frameScale;
5242
5243 for (const auto& handle : excludeHandles) {
5244 sp<Layer> excludeLayer = fromHandle(handle);
5245 if (excludeLayer != nullptr) {
5246 excludeLayers.emplace(excludeLayer);
5247 } else {
5248 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5249 return NAME_NOT_FOUND;
5250 }
5251 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005252
5253 auto display = getDisplayByLayerStack(parent->getLayerStack());
5254 if (!display) {
5255 return BAD_VALUE;
5256 }
5257
5258 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005259 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005260
Chia-I Wu20261cb2018-08-23 12:55:44 -07005261 // really small crop or frameScale
5262 if (reqWidth <= 0) {
5263 reqWidth = 1;
5264 }
5265 if (reqHeight <= 0) {
5266 reqHeight = 1;
5267 }
5268
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005269 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5270 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005271 auto traverseLayers = [parent, childrenOnly,
5272 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005273 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5274 if (!layer->isVisible()) {
5275 return;
Robert Carr578038f2018-03-09 12:25:24 -08005276 } else if (childrenOnly && layer == parent.get()) {
5277 return;
chaviwa76b2712017-09-20 12:02:26 -07005278 }
Robert Carr866455f2019-04-02 16:28:26 -07005279
5280 sp<Layer> p = layer;
5281 while (p != nullptr) {
5282 if (excludeLayers.count(p) != 0) {
5283 return;
5284 }
5285 p = p->getParent();
5286 }
5287
chaviwa76b2712017-09-20 12:02:26 -07005288 visitor(layer);
5289 });
5290 };
Robert Carr108b2c72019-04-02 16:32:58 -07005291
5292 bool outCapturedSecureLayers = false;
5293 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5294 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005295}
5296
5297status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5298 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005299 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005300 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005301 bool useIdentityTransform,
5302 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005303 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005304
Peiyong Lin0e003c92018-09-17 11:09:51 -07005305 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005306 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5307 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005308 *outBuffer =
5309 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5310 static_cast<android_pixel_format>(reqPixelFormat), 1,
5311 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005312
Robert Carr108b2c72019-04-02 16:32:58 -07005313 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5314 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005315}
5316
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005317status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5318 TraverseLayersFunction traverseLayers,
5319 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005320 bool useIdentityTransform,
5321 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005322 // This mutex protects syncFd and captureResult for communication of the return values from the
5323 // main thread back to this Binder thread
5324 std::mutex captureMutex;
5325 std::condition_variable captureCondition;
5326 std::unique_lock<std::mutex> captureLock(captureMutex);
5327 int syncFd = -1;
5328 std::optional<status_t> captureResult;
5329
Robert Carr03480e22018-01-04 16:02:06 -08005330 const int uid = IPCThreadState::self()->getCallingUid();
5331 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5332
Dominik Laskowski8c001672018-05-30 16:52:06 -07005333 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005334 // If there is a refresh pending, bug out early and tell the binder thread to try again
5335 // after the refresh.
5336 if (mRefreshPending) {
5337 ATRACE_NAME("Skipping screenshot for now");
5338 std::unique_lock<std::mutex> captureLock(captureMutex);
5339 captureResult = std::make_optional<status_t>(EAGAIN);
5340 captureCondition.notify_one();
5341 return;
5342 }
5343
5344 status_t result = NO_ERROR;
5345 int fd = -1;
5346 {
5347 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005348 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005349 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005350 useIdentityTransform, forSystem, &fd,
5351 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005352 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005353 }
5354
5355 {
5356 std::unique_lock<std::mutex> captureLock(captureMutex);
5357 syncFd = fd;
5358 captureResult = std::make_optional<status_t>(result);
5359 captureCondition.notify_one();
5360 }
5361 });
5362
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005363 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005365 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005366 while (*captureResult == EAGAIN) {
5367 captureResult.reset();
5368 result = postMessageAsync(message);
5369 if (result != NO_ERROR) {
5370 return result;
5371 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005372 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005373 }
5374 result = *captureResult;
5375 }
5376
5377 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005378 sync_wait(syncFd, -1);
5379 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005380 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005381
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005382 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005383}
5384
chaviwa76b2712017-09-20 12:02:26 -07005385void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005386 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005387 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5388 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005389 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005390
chaviwa76b2712017-09-20 12:02:26 -07005391 const auto reqWidth = renderArea.getReqWidth();
5392 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005393 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005394 const auto transform = renderArea.getTransform();
5395 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005396 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005397
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005398 renderengine::DisplaySettings clientCompositionDisplay;
5399 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005400
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005401 // assume that bounds are never offset, and that they are the same as the
5402 // buffer bounds.
5403 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005404 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005405 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005406
5407 // Now take into account the rotation flag. We append a transform that
5408 // rotates the layer stack about the origin, then translate by buffer
5409 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005410 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005411 int displacementX = 0;
5412 int displacementY = 0;
5413 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5414 switch (rotation) {
5415 case ui::Transform::ROT_90:
5416 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005417 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005418 break;
5419 case ui::Transform::ROT_180:
5420 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005421 displacementY = renderArea.getBounds().getWidth();
5422 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005423 break;
5424 case ui::Transform::ROT_270:
5425 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005426 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005427 break;
5428 default:
5429 break;
5430 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005431
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005432 // We need to transform the clipping window into the right spot.
5433 // First, rotate the clipping rectangle by the rotation hint to get the
5434 // right orientation
5435 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5436 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5437 const vec4 rotClipTL = rotMatrix * clipTL;
5438 const vec4 rotClipBR = rotMatrix * clipBR;
5439 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5440 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5441 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5442 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5443
5444 // Now reposition the clipping rectangle with the displacement vector
5445 // computed above.
5446 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005447 clientCompositionDisplay.clip =
5448 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5449 newClipRight + displacementX, newClipBottom + displacementY);
5450
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005451 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005452 clientCompositionDisplay.globalTransform =
5453 clipTransform * clientCompositionDisplay.globalTransform;
5454
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005455 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5456 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005457
chaviw50da5042018-04-09 13:49:37 -07005458 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005459
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005460 renderengine::LayerSettings fillLayer;
5461 fillLayer.source.buffer.buffer = nullptr;
5462 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5463 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5464 fillLayer.alpha = half(alpha);
5465 clientCompositionLayers.push_back(fillLayer);
5466
5467 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005468 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005469 const bool supportProtectedContent = false;
5470 Region clip(renderArea.getBounds());
5471 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5472 clip,
5473 useIdentityTransform,
5474 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5475 renderArea.isSecure(),
5476 supportProtectedContent,
5477 clearRegion,
5478 };
5479 auto result = layer->prepareClientComposition(targetSettings);
5480 if (result) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005481 std::optional<renderengine::LayerSettings> shadowLayer =
5482 layer->prepareShadowClientComposition(*result, displayViewport,
5483 clientCompositionDisplay.outputDataspace);
5484 if (shadowLayer) {
5485 clientCompositionLayers.push_back(*shadowLayer);
5486 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005487 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005488 }
chaviwa76b2712017-09-20 12:02:26 -07005489 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005490
5491 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005492 // Use an empty fence for the buffer fence, since we just created the buffer so
5493 // there is no need for synchronization with the GPU.
5494 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005495 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005496 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005497 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005498 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005499
5500 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005501}
5502
chaviwa76b2712017-09-20 12:02:26 -07005503status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5504 TraverseLayersFunction traverseLayers,
5505 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005506 bool useIdentityTransform, bool forSystem,
5507 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005508 ATRACE_CALL();
5509
chaviwa76b2712017-09-20 12:02:26 -07005510 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005511 outCapturedSecureLayers =
5512 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005513 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005514
Robert Carr03480e22018-01-04 16:02:06 -08005515 // We allow the system server to take screenshots of secure layers for
5516 // use in situations like the Screen-rotation animation and place
5517 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005518 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005519 ALOGW("FB is protected: PERMISSION_DENIED");
5520 return PERMISSION_DENIED;
5521 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005522 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005523 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005524}
5525
chaviw95ef3c42019-02-14 10:55:09 -08005526void SurfaceFlinger::setInputWindowsFinished() {
5527 Mutex::Autolock _l(mStateLock);
5528
5529 mPendingSyncInputWindows = false;
5530 mTransactionCV.broadcast();
5531}
chaviw5f21a5e2019-02-14 10:00:34 -08005532
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005533// ---------------------------------------------------------------------------
5534
Dan Stoza412903f2017-04-27 13:42:17 -07005535void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5536 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005537}
5538
Dan Stoza412903f2017-04-27 13:42:17 -07005539void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5540 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005541}
5542
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005543void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005544 const LayerVector::Visitor& visitor) {
5545 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005546 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005547 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005548 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005549 continue;
5550 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005551 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005552 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005553 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005554 return;
5555 }
chaviwa76b2712017-09-20 12:02:26 -07005556 if (!layer->isVisible()) {
5557 return;
5558 }
5559 visitor(layer);
5560 });
5561 }
5562}
5563
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005564status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5565 HwcConfigIndexType defaultConfig,
5566 float minRefreshRate,
5567 float maxRefreshRate) {
5568 Mutex::Autolock lock(mStateLock);
5569
Dominik Laskowski22488f62019-03-28 09:53:04 -07005570 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005571 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5572 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5573 // it should go thru setDesiredActiveConfig, similar to primary display.
5574 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5575 const auto displayId = display->getId();
5576 LOG_ALWAYS_FATAL_IF(!displayId);
5577
5578 HWC2::VsyncPeriodChangeConstraints constraints;
5579 constraints.desiredTimeNanos = systemTime();
5580 constraints.seamlessRequired = false;
5581
5582 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005583 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5584 constraints, &timeline) < 0) {
5585 return BAD_VALUE;
5586 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005587 if (timeline.refreshRequired) {
5588 repaintEverythingForHWC();
5589 }
5590
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005591 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005592 display->setActiveConfig(configId);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005593 const nsecs_t vsyncPeriod =
5594 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).vsyncPeriod;
5595 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId,
5596 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005597 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005598 }
5599
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005600 if (mDebugDisplayConfigSetByBackdoor) {
5601 // ignore this request as config is overridden by backdoor
5602 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005603 }
5604
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005605 bool policyChanged;
5606 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5607 &policyChanged) < 0) {
5608 return BAD_VALUE;
5609 }
5610 if (!policyChanged) {
5611 return NO_ERROR;
5612 }
5613
5614 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5615 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005616
5617 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5618 // that listeners that care about a change in allowed configs can get the notification.
5619 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005620 const nsecs_t vsyncPeriod =
5621 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005622 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005623 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005624
Ady Abraham2139f732019-11-13 18:56:40 -08005625 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5626 auto configId = mScheduler->getPreferredConfigId();
5627 auto preferredRefreshRate = configId
5628 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5629 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5630 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5631 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5632 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5633 ALOGV("switching to Scheduler preferred config %d",
5634 preferredRefreshRate.configId.value());
5635 setDesiredActiveConfig(
5636 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5637 } else {
5638 // Set the highest allowed config
5639 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5640 Scheduler::ConfigEvent::Changed});
5641 }
5642 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005643 ALOGV("switching to config %d", defaultConfig.value());
5644 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005645 }
5646
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005647 return NO_ERROR;
5648}
5649
Ana Krulec0782b882019-10-15 17:34:54 -07005650status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005651 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005652 float maxRefreshRate) {
5653 ATRACE_CALL();
5654
5655 if (!displayToken) {
5656 return BAD_VALUE;
5657 }
5658
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005659 status_t result = NO_ERROR;
5660
Ana Krulec234bb162019-11-10 22:55:55 +01005661 postMessageSync(new LambdaMessage([&]() {
5662 const auto display = getDisplayDeviceLocked(displayToken);
5663 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005664 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005665 ALOGE("Attempt to set desired display configs for invalid display token %p",
5666 displayToken.get());
5667 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005668 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005669 ALOGW("Attempt to set desired display configs for virtual display");
5670 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005671 result =
5672 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5673 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005674 }
5675 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005676
5677 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005678}
5679
5680status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005681 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005682 float* outMinRefreshRate,
5683 float* outMaxRefreshRate) {
5684 ATRACE_CALL();
5685
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005686 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005687 return BAD_VALUE;
5688 }
5689
5690 Mutex::Autolock lock(mStateLock);
5691 const auto display = getDisplayDeviceLocked(displayToken);
5692 if (!display) {
5693 return NAME_NOT_FOUND;
5694 }
5695
5696 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005697 HwcConfigIndexType defaultConfig;
5698 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5699 *outDefaultConfig = defaultConfig.value();
5700 return NO_ERROR;
5701 } else if (display->isVirtual()) {
5702 return BAD_VALUE;
5703 } else {
5704 const auto displayId = display->getId();
5705 if (!displayId) {
5706 return BAD_VALUE;
5707 }
5708 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5709 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5710 *outMinRefreshRate = 1e9f / vsyncPeriod;
5711 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5712 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005713 }
Ana Krulec0782b882019-10-15 17:34:54 -07005714}
5715
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005716void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005717 mFlinger->setInputWindowsFinished();
5718}
5719
Robert Carrc0df3122019-04-11 13:18:21 -07005720sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005721 BBinder* b = nullptr;
5722 if (handle) {
5723 b = handle->localBinder();
5724 }
Robert Carrc0df3122019-04-11 13:18:21 -07005725 if (b == nullptr) {
5726 return nullptr;
5727 }
5728 auto it = mLayersByLocalBinderToken.find(b);
5729 if (it != mLayersByLocalBinderToken.end()) {
5730 return it->second.promote();
5731 }
5732 return nullptr;
5733}
5734
Dominik Laskowski75848362019-11-11 17:57:20 -08005735void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005736 mNumLayers++;
5737 mScheduler->registerLayer(layer);
5738}
5739
5740void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5741 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005742 removeFromOffscreenLayers(layer);
5743}
5744
5745// WARNING: ONLY CALL THIS FROM LAYER DTOR
5746// Here we add children in the current state to offscreen layers and remove the
5747// layer itself from the offscreen layer list. Since
5748// this is the dtor, it is safe to access the current state. This keeps us
5749// from dangling children layers such that they are not reachable from the
5750// Drawing state nor the offscreen layer list
5751// See b/141111965
5752void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5753 for (auto& child : layer->getCurrentChildren()) {
5754 mOffscreenLayers.emplace(child.get());
5755 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005756 mOffscreenLayers.erase(layer);
5757}
5758
Alec Mouri4545a8a2019-08-08 20:05:32 -07005759void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5760 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5761}
5762
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005763status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5764 float lightPosY, float lightPosZ,
5765 float lightRadius) {
5766 Mutex::Autolock _l(mStateLock);
5767 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5768 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5769 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5770 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5771 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5772
5773 // these values are overridden when calculating the shadow settings for a layer.
5774 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5775 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005776 return NO_ERROR;
5777}
5778
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005779} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005780
Mathias Agopian3f844832013-08-07 21:24:32 -07005781#if defined(__gl_h_)
5782#error "don't include gl/gl.h in this file"
5783#endif
5784
5785#if defined(__gl2_h_)
5786#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005787#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005788
5789// TODO(b/129481165): remove the #pragma below and fix conversion issues
5790#pragma clang diagnostic pop // ignored "-Wconversion"