blob: 3d71267bb33f1f9420e39dba66a253d8912b52db [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
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070098#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700100#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/EventControlThread.h"
102#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700103#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
David Sodman7e4ae112018-02-09 15:02:28 -0800111#include "android-base/stringprintf.h"
112
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900116#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
chaviw1d044282017-09-27 12:19:28 -0700118#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900119#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700122
Jaesoo Lee43518572017-01-23 19:03:16 +0900123using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900124using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900125using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800126
Yiwei Zhang5434a782018-12-05 18:06:32 -0800127using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700128using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700129using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800130using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700131using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700132using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900133
Steven Thomasb02664d2017-07-26 18:48:28 -0700134namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700135
136#pragma clang diagnostic push
137#pragma clang diagnostic error "-Wswitch-enum"
138
139bool isWideColorMode(const ColorMode colorMode) {
140 switch (colorMode) {
141 case ColorMode::DISPLAY_P3:
142 case ColorMode::ADOBE_RGB:
143 case ColorMode::DCI_P3:
144 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700145 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700146 case ColorMode::BT2100_PQ:
147 case ColorMode::BT2100_HLG:
148 return true;
149 case ColorMode::NATIVE:
150 case ColorMode::STANDARD_BT601_625:
151 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
152 case ColorMode::STANDARD_BT601_525:
153 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
154 case ColorMode::STANDARD_BT709:
155 case ColorMode::SRGB:
156 return false;
157 }
158 return false;
159}
160
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700161bool isHdrColorMode(const ColorMode colorMode) {
162 switch (colorMode) {
163 case ColorMode::BT2100_PQ:
164 case ColorMode::BT2100_HLG:
165 return true;
166 case ColorMode::DISPLAY_P3:
167 case ColorMode::ADOBE_RGB:
168 case ColorMode::DCI_P3:
169 case ColorMode::BT2020:
170 case ColorMode::DISPLAY_BT2020:
171 case ColorMode::NATIVE:
172 case ColorMode::STANDARD_BT601_625:
173 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
174 case ColorMode::STANDARD_BT601_525:
175 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
176 case ColorMode::STANDARD_BT709:
177 case ColorMode::SRGB:
178 return false;
179 }
180 return false;
181}
182
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700183ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
184 switch (rotation) {
185 case ISurfaceComposer::eRotateNone:
186 return ui::Transform::ROT_0;
187 case ISurfaceComposer::eRotate90:
188 return ui::Transform::ROT_90;
189 case ISurfaceComposer::eRotate180:
190 return ui::Transform::ROT_180;
191 case ISurfaceComposer::eRotate270:
192 return ui::Transform::ROT_270;
193 }
194 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
195 return ui::Transform::ROT_0;
196}
197
Peiyong Linfca547f2018-07-09 13:03:33 -0700198#pragma clang diagnostic pop
199
Steven Thomasb02664d2017-07-26 18:48:28 -0700200class ConditionalLock {
201public:
202 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
203 if (lock) {
204 mMutex.lock();
205 }
206 }
207 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
208private:
209 Mutex& mMutex;
210 bool mLocked;
211};
Peiyong Linfca547f2018-07-09 13:03:33 -0700212
Peiyong Lin9d846a52018-11-05 13:18:20 -0800213// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
214bool validateCompositionDataspace(Dataspace dataspace) {
215 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
216}
217
Steven Thomasb02664d2017-07-26 18:48:28 -0700218} // namespace anonymous
219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220// ---------------------------------------------------------------------------
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222const String16 sHardwareTest("android.permission.HARDWARE_TEST");
223const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
224const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
225const String16 sDump("android.permission.DUMP");
226
227// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700228int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700229bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800230uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800231bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800232bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800233int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600234bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700235int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700236bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700237bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700238Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
239ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
240Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700242
Kalle Raitaa099a242017-01-11 11:17:29 -0800243std::string getHwcServiceName() {
244 char value[PROPERTY_VALUE_MAX] = {};
245 property_get("debug.sf.hwc_service_name", value, "default");
246 ALOGI("Using HWComposer service: '%s'", value);
247 return std::string(value);
248}
249
250bool useTrebleTestingOverride() {
251 char value[PROPERTY_VALUE_MAX] = {};
252 property_get("debug.sf.treble_testing_override", value, "false");
253 ALOGI("Treble testing override: '%s'", value);
254 return std::string(value) == "true";
255}
256
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
258 switch(displayColorSetting) {
259 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700260 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Enhanced");
265 default:
266 return std::string("Unknown ") +
267 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800268 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800269}
270
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700271SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
274 : mFactory(factory),
275 mPhaseOffsets(mFactory.createPhaseOffsets()),
276 mInterceptor(mFactory.createSurfaceInterceptor(this)),
277 mTimeStats(mFactory.createTimeStats()),
278 mEventQueue(mFactory.createMessageQueue()),
279 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800280
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 mDefaultCompositionDataspace =
302 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
303 mWideColorGamutCompositionDataspace =
304 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
305 defaultCompositionDataspace = mDefaultCompositionDataspace;
306 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
307 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
308 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
309 wideColorGamutCompositionPixelFormat =
310 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
315 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
316 switch (tmpPrimaryDisplayOrientation) {
317 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700321 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800322 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700324 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800325 break;
326 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700327 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800328 break;
329 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700330 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800331
Sundong Ahn85131bd2019-02-18 15:51:53 +0900332 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700343 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000344
345 // DDMS debugging deprecated (b/120782499)
346 property_get("debug.sf.ddms", value, "0");
347 int debugDdms = atoi(value);
348 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700349
350 property_get("debug.sf.disable_backpressure", value, "0");
351 mPropagateBackpressure = !atoi(value);
352 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700353
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800354 property_get("debug.sf.enable_hwc_vds", value, "0");
355 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800356 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800357
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800358 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800359 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700361
Yiwei Zhang243b3782018-05-15 17:40:04 -0700362 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700363 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
364 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
365
Ana Krulece5a06e02019-03-06 17:09:03 -0800366 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800367 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800368
369 int int_value = atoi(value);
370 if (int_value) {
371 mUseSmart90ForVideo = true;
372 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800373
Dan Stozaec460082018-12-17 15:35:09 -0800374 property_get("debug.sf.luma_sampling", value, "1");
375 mLumaSampling = atoi(value);
376
Ana Krulec757f63a2019-01-25 10:46:18 -0800377 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
378 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700379
Romain Guy11d63f42017-07-20 12:47:14 -0700380 // We should be reading 'persist.sys.sf.color_saturation' here
381 // but since /data may be encrypted, we need to wait until after vold
382 // comes online to attempt to read the property. The property is
383 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800384
385 if (useTrebleTestingOverride()) {
386 // Without the override SurfaceFlinger cannot connect to HIDL
387 // services that are not listed in the manifests. Considered
388 // deriving the setting from the set service name, but it
389 // would be brittle if the name that's not 'default' is used
390 // for production purposes later on.
391 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393}
394
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395void SurfaceFlinger::onFirstRef()
396{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800397 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700400SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401
Dan Stozac7014012014-02-14 15:03:43 -0800402void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403{
404 // the window manager died on us. prepare its eulogy.
405
Andy McFadden13a082e2012-08-24 10:16:42 -0700406 // restore initial conditions (default device unblank, etc)
407 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408
409 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700410 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Robert Carr1db73f62016-12-21 12:58:51 -0800413static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700414 status_t err = client->initCheck();
415 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800416 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417 }
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return nullptr;
419}
420
421sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
422 return initClient(new Client(this));
423}
424
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700425sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
426 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427{
428 class DisplayToken : public BBinder {
429 sp<SurfaceFlinger> flinger;
430 virtual ~DisplayToken() {
431 // no more references, this display must be terminated
432 Mutex::Autolock _l(flinger->mStateLock);
433 flinger->mCurrentState.displays.removeItem(this);
434 flinger->setTransactionFlags(eDisplayTransactionNeeded);
435 }
436 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700437 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 : flinger(flinger) {
439 }
440 };
441
442 sp<BBinder> token = new DisplayToken(this);
443
444 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 // Display ID is assigned when virtual display is allocated by HWC.
446 DisplayDeviceState state;
447 state.isSecure = secure;
448 state.displayName = displayName;
449 mCurrentState.displays.add(token, state);
450 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 return token;
452}
453
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700454void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 Mutex::Autolock _l(mStateLock);
456
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
458 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 return;
461 }
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
464 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 ALOGE("destroyDisplay called for non-virtual display");
466 return;
467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 mInterceptor->saveDisplayDeletion(state.sequenceId);
469 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 setTransactionFlags(eDisplayTransactionNeeded);
471}
472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
474 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800476 const auto internalDisplayId = getInternalDisplayIdLocked();
477 if (!internalDisplayId) {
478 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700479 }
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 std::vector<PhysicalDisplayId> displayIds;
482 displayIds.reserve(mPhysicalDisplayTokens.size());
483 displayIds.push_back(internalDisplayId->value);
484
485 for (const auto& [id, token] : mPhysicalDisplayTokens) {
486 if (id != *internalDisplayId) {
487 displayIds.push_back(id.value);
488 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700489 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800491 return displayIds;
492}
493
494sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
495 Mutex::Autolock lock(mStateLock);
496 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497}
498
Ady Abraham37965d42018-11-01 13:43:32 -0700499status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
500 if (!outGetColorManagement) {
501 return BAD_VALUE;
502 }
503 *outGetColorManagement = useColorManagement;
504 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700505}
506
Lloyd Pique441d5042018-10-18 16:49:51 -0700507HWComposer& SurfaceFlinger::getHwComposer() const {
508 return mCompositionEngine->getHwComposer();
509}
510
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700511renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
512 return mCompositionEngine->getRenderEngine();
513}
514
Lloyd Pique70d91362018-10-18 16:02:55 -0700515compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
516 return *mCompositionEngine.get();
517}
518
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800519void SurfaceFlinger::bootFinished()
520{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700521 if (mStartPropertySetThread->join() != NO_ERROR) {
522 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524 const nsecs_t now = systemTime();
525 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000526 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527
528 // wait patiently for the window manager death
529 const String16 name("window");
530 sp<IBinder> window(defaultServiceManager()->getService(name));
531 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700532 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 }
Robert Carr720e5062018-07-30 17:45:14 -0700534 sp<IBinder> input(defaultServiceManager()->getService(
535 String16("inputflinger")));
536 if (input == nullptr) {
537 ALOGE("Failed to link to input service");
538 } else {
539 mInputFlinger = interface_cast<IInputFlinger>(input);
540 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
Steven Thomas050b2c82017-03-06 11:45:16 -0800542 if (mVrFlinger) {
543 mVrFlinger->OnBootFinished();
544 }
545
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700547 // formerly we would just kill the process, but we now ask it to exit so it
548 // can choose where to stop the animation.
549 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700550
551 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
552 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
553 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700554
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 readPersistentProperties();
557 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558
Ady Abraham97d04232019-03-05 19:48:12 -0800559 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700560 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700561 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800562
Dominik Laskowski22488f62019-03-28 09:53:04 -0700563 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800564 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800566 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569}
570
Dan Stoza436ccf32018-06-21 12:10:12 -0700571uint32_t SurfaceFlinger::getNewTexture() {
572 {
573 std::lock_guard lock(mTexturePoolMutex);
574 if (!mTexturePool.empty()) {
575 uint32_t name = mTexturePool.back();
576 mTexturePool.pop_back();
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
578 return name;
579 }
580
581 // The pool was too small, so increase it for the future
582 ++mTexturePoolSize;
583 }
584
585 // The pool was empty, so we need to get a new texture name directly using a
586 // blocking call to the main thread
587 uint32_t name = 0;
588 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
589 return name;
590}
591
Mathias Agopian3f844832013-08-07 21:24:32 -0700592void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700593 std::lock_guard lock(mTexturePoolMutex);
594 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
595 // to actually delete this or not based on mTexturePoolSize
596 mTexturePool.push_back(texture);
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Ana Krulec757f63a2019-01-25 10:46:18 -0800606 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700609 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800610 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700611 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
612 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800613 auto resyncCallback =
614 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800615
Ana Krulecc2870422019-01-29 19:00:58 -0800616 mAppConnectionHandle =
617 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
618 resyncCallback,
619 impl::EventThread::InterceptVSyncsCallback());
620 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
621 resyncCallback, [this](nsecs_t timestamp) {
622 mInterceptor->saveVSyncEvent(timestamp);
623 });
624
625 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
626 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
627 mSfConnectionHandle.get());
628
Kevin DuBois413287f2019-02-25 08:46:47 -0800629 mRegionSamplingThread =
630 new RegionSamplingThread(*this, *mScheduler,
631 RegionSamplingThread::EnvironmentTimingTunables());
632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700634 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700635 renderEngineFeature |= (useColorManagement ?
636 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700637 renderEngineFeature |= (useContextPriority ?
638 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700639 renderEngineFeature |=
640 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
641 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700642
643 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800644 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700645 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700646 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800647 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700648
649 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
650 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700651 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
652 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800653 // Process any initial hotplug and resulting display changes.
654 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700655 const auto display = getDefaultDisplayDeviceLocked();
656 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700657 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800659
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700662 // This callback is called from the vr flinger dispatch thread. We
663 // need to call signalTransaction(), which requires holding
664 // mStateLock when we're not on the main thread. Acquiring
665 // mStateLock from the vr flinger dispatch thread might trigger a
666 // deadlock in surface flinger (see b/66916578), so post a message
667 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700668 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700669 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
670 mVrFlingerRequestsDisplay = requestDisplay;
671 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
675 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 .value_or(0),
678 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (!mVrFlinger) {
680 ALOGE("Failed to start vrflinger");
681 }
682 }
683
Mathias Agopian92a979a2012-08-02 18:32:23 -0700684 // initialize our drawing state
685 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700686
Andy McFadden13a082e2012-08-24 10:16:42 -0700687 // set initial conditions (e.g. unblank default device)
688 initializeDisplays();
689
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700690 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700691
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700693
694 const bool presentFenceReliable =
695 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
696 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697
698 if (mStartPropertySetThread->Start() != NO_ERROR) {
699 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701
Alec Mouri93bc83d2019-04-17 14:47:43 -0700702 mScheduler->setChangeRefreshRateCallback(
703 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
704 Mutex::Autolock lock(mStateLock);
705 setRefreshRateTo(type, event);
706 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700707
Dominik Laskowski22488f62019-03-28 09:53:04 -0700708 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
709 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800710
Dan Stoza9e56aa02015-11-02 13:00:03 -0800711 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700712}
713
Romain Guy11d63f42017-07-20 12:47:14 -0700714void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700715 Mutex::Autolock _l(mStateLock);
716
Romain Guy11d63f42017-07-20 12:47:14 -0700717 char value[PROPERTY_VALUE_MAX];
718
719 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800720 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700721 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800722 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100723
724 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700725 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800726
727 property_get("persist.sys.sf.color_mode", value, "0");
728 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700729}
730
Mathias Agopiana67e4182012-06-19 17:26:12 -0700731void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800732 // Start boot animation service by setting a property mailbox
733 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800735 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700736 if (mStartPropertySetThread->join() != NO_ERROR) {
737 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800738 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700739}
740
Mathias Agopian875d8e12013-06-07 15:35:48 -0700741size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700742 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700743}
744
Mathias Agopian875d8e12013-06-07 15:35:48 -0700745size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700746 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700747}
748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800750
Jamie Gennis582270d2011-08-17 18:19:00 -0700751bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800752 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800753 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800754 return authenticateSurfaceTextureLocked(bufferProducer);
755}
756
757bool SurfaceFlinger::authenticateSurfaceTextureLocked(
758 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800759 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800760 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800761}
762
Brian Anderson6b376712017-04-04 10:51:39 -0700763status_t SurfaceFlinger::getSupportedFrameTimestamps(
764 std::vector<FrameEvent>* outSupported) const {
765 *outSupported = {
766 FrameEvent::REQUESTED_PRESENT,
767 FrameEvent::ACQUIRE,
768 FrameEvent::LATCH,
769 FrameEvent::FIRST_REFRESH_START,
770 FrameEvent::LAST_REFRESH_START,
771 FrameEvent::GPU_COMPOSITION_DONE,
772 FrameEvent::DEQUEUE_READY,
773 FrameEvent::RELEASE,
774 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700775 ConditionalLock _l(mStateLock,
776 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700777 if (!getHwComposer().hasCapability(
778 HWC2::Capability::PresentFenceIsNotReliable)) {
779 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
780 }
781 return NO_ERROR;
782}
783
Dominik Laskowski22488f62019-03-28 09:53:04 -0700784status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
785 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700786 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700787 return BAD_VALUE;
788 }
789
Dominik Laskowski22488f62019-03-28 09:53:04 -0700790 Mutex::Autolock lock(mStateLock);
791
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800792 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700793 if (!displayId) {
794 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700795 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700796
Mathias Agopian8b736f12012-08-13 17:54:26 -0700797 // TODO: Not sure if display density should handled by SF any longer
798 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700799 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700800 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700801 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800802 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700803 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804 }
805 return density;
806 }
807 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700808 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700809 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700810 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 return getDensityFromProperty("ro.sf.lcd_density"); }
812 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700813
Dan Stoza7f7da322014-05-02 15:26:25 -0700814 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700815
Dominik Laskowski075d3172018-05-24 15:50:06 -0700816 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 DisplayInfo info = DisplayInfo();
818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 float xdpi = hwConfig->getDpiX();
820 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700821
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700822 info.w = hwConfig->getWidth();
823 info.h = hwConfig->getHeight();
824 // Default display viewport to display width and height
825 info.viewportW = info.w;
826 info.viewportH = info.h;
827
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800828 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 // The density of the device is provided by a build property
830 float density = Density::getBuildDensity() / 160.0f;
831 if (density == 0) {
832 // the build doesn't provide a density -- this is wrong!
833 // use xdpi instead
834 ALOGE("ro.sf.lcd_density must be defined as a build property");
835 density = xdpi / 160.0f;
836 }
837 if (Density::getEmuDensity()) {
838 // if "qemu.sf.lcd_density" is specified, it overrides everything
839 xdpi = ydpi = density = Density::getEmuDensity();
840 density /= 160.0f;
841 }
842 info.density = density;
843
844 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700845 const auto display = getDefaultDisplayDeviceLocked();
846 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700847
848 // This is for screenrecord
849 const Rect viewport = display->getViewport();
850 if (viewport.isValid()) {
851 info.viewportW = uint32_t(viewport.getWidth());
852 info.viewportH = uint32_t(viewport.getHeight());
853 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 } else {
855 // TODO: where should this value come from?
856 static const int TV_DENSITY = 213;
857 info.density = TV_DENSITY / 160.0f;
858 info.orientation = 0;
859 }
860
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 info.xdpi = xdpi;
862 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800863 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700864 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
865 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
866 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867
Andy McFadden91b2ca82014-06-13 14:04:23 -0700868 // This is how far in advance a buffer must be queued for
869 // presentation at a given time. If you want a buffer to appear
870 // on the screen at time N, you must submit the buffer before
871 // (N - presentationDeadline).
872 //
873 // Normally it's one full refresh period (to give SF a chance to
874 // latch the buffer), but this can be reduced by configuring a
875 // DispSync offset. Any additional delays introduced by the hardware
876 // composer or panel must be accounted for here.
877 //
878 // We add an additional 1ms to allow for processing time and
879 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700880 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700881
882 // All non-virtual displays are currently considered secure.
883 info.secure = true;
884
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800885 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700886 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800887 std::swap(info.w, info.h);
888 }
889
Michael Wright28f24d02016-07-12 13:30:53 -0700890 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return NO_ERROR;
894}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
897 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700898 return BAD_VALUE;
899 }
900
Ana Krulecc2870422019-01-29 19:00:58 -0800901 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700902 return NO_ERROR;
903}
904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
906 const auto display = getDisplayDevice(displayToken);
907 if (!display) {
908 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800909 return BAD_VALUE;
910 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700913}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700914
Ady Abraham03b02dd2019-03-21 15:40:11 -0700915void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800917
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800918 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800919 // config twice. However event generation config might have changed so we need to update it
920 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800921 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700922 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
923 mDesiredActiveConfig = info;
924 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800925
926 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927 // This will trigger HWC refresh without resetting the idle timer.
928 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700929 // Start receiving vsync samples now, so that we can detect a period
930 // switch.
931 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
932 mPhaseOffsets->setRefreshRateType(info.type);
933 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
934 mVsyncModulator.onRefreshRateChangeInitiated();
935 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800937 mDesiredActiveConfigChanged = true;
938 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700939
940 if (mRefreshRateOverlay) {
941 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
942 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
946 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800947
948 std::vector<int32_t> allowedConfig;
949 allowedConfig.push_back(mode);
950
951 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952}
953
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954void SurfaceFlinger::setActiveConfigInternal() {
955 ATRACE_CALL();
956
Dominik Laskowski22488f62019-03-28 09:53:04 -0700957 const auto display = getDefaultDisplayDeviceLocked();
958 if (!display) {
959 return;
960 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961
Dominik Laskowski22488f62019-03-28 09:53:04 -0700962 std::lock_guard<std::mutex> lock(mActiveConfigLock);
963 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
964
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965 display->setActiveConfig(mUpcomingActiveConfig.configId);
966
Ana Krulecc2870422019-01-29 19:00:58 -0800967 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Alec Mouri754c98a2019-03-18 18:53:42 -0700968 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800969 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
970 mVsyncModulator.setPhaseOffsets(early, gl, late);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800971 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700972
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800973 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800974 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
975 mUpcomingActiveConfig.configId);
976 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977}
978
Dominik Laskowski22488f62019-03-28 09:53:04 -0700979bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800980 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800981 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700982 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 // fence has not signaled yet. wait for the next invalidate
Ady Abrahame1a5bcb2019-04-17 20:09:26 -0700984 mEventQueue->invalidateForHWC();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800985 return true;
986 }
987
988 // We received the present fence from the HWC, so we assume it successfully updated
989 // the config, hence we update SF.
990 mCheckPendingFence = false;
991 setActiveConfigInternal();
992 }
993
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994 // Store the local variable to release the lock.
995 ActiveConfigInfo desiredActiveConfig;
996 {
997 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800998 if (!mDesiredActiveConfigChanged) {
999 return false;
1000 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001001 desiredActiveConfig = mDesiredActiveConfig;
1002 }
1003
Dominik Laskowski22488f62019-03-28 09:53:04 -07001004 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001005 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1006 // display is not valid or we are already in the requested mode
1007 // on both cases there is nothing left to do
1008 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham6398a0a2019-04-18 19:30:44 -07001009 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 mDesiredActiveConfigChanged = false;
1011 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1012 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014
Ady Abraham838de062019-02-04 10:24:03 -08001015 // Desired active config was set, it is different than the config currently in use, however
1016 // allowed configs might have change by the time we process the refresh.
1017 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001018 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham838de062019-02-04 10:24:03 -08001019 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Alec Mouriecf2e0f2019-03-26 13:26:17 -07001020 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
Ady Abraham838de062019-02-04 10:24:03 -08001021 mDesiredActiveConfig.configId = display->getActiveConfig();
Ady Abraham6398a0a2019-04-18 19:30:44 -07001022 mDesiredActiveConfigChanged = false;
1023 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham838de062019-02-04 10:24:03 -08001024 return false;
1025 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 mUpcomingActiveConfig = desiredActiveConfig;
1027 const auto displayId = display->getId();
1028 LOG_ALWAYS_FATAL_IF(!displayId);
1029
1030 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1031 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1032
1033 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 mCheckPendingFence = true;
Ady Abrahame1a5bcb2019-04-17 20:09:26 -07001035 mEventQueue->invalidateForHWC();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001037}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1040 Vector<ColorMode>* outColorModes) {
1041 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001042 return BAD_VALUE;
1043 }
1044
Peiyong Lina52f0292018-03-14 17:26:31 -07001045 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001046 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001047 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1048
1049 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1050 if (!displayId) {
1051 return NAME_NOT_FOUND;
1052 }
1053
Dominik Laskowski075d3172018-05-24 15:50:06 -07001054 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001055 }
Michael Wright28f24d02016-07-12 13:30:53 -07001056 outColorModes->clear();
1057 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1058
1059 return NO_ERROR;
1060}
1061
Daniel Solomon42d04562019-01-20 21:03:19 -08001062status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1063 ui::DisplayPrimaries &primaries) {
1064 if (!displayToken) {
1065 return BAD_VALUE;
1066 }
1067
1068 // Currently we only support this API for a single internal display.
1069 if (getInternalDisplayToken() != displayToken) {
1070 return BAD_VALUE;
1071 }
1072
1073 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1074 return NO_ERROR;
1075}
1076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1078 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001079 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001080 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001081 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001082}
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001085 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 Vector<ColorMode> modes;
1087 getDisplayColorModes(displayToken, &modes);
1088 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1089 if (mode < ColorMode::NATIVE || !exists) {
1090 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1091 decodeColorMode(mode).c_str(), mode, displayToken.get());
1092 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001093 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 const auto display = getDisplayDevice(displayToken);
1095 if (!display) {
1096 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1097 decodeColorMode(mode).c_str(), mode, displayToken.get());
1098 } else if (display->isVirtual()) {
1099 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1100 decodeColorMode(mode).c_str(), mode);
1101 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001102 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1103 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 }
1105 }));
1106
Michael Wright28f24d02016-07-12 13:30:53 -07001107 return NO_ERROR;
1108}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001109
Svetoslavd85084b2014-03-20 10:28:31 -07001110status_t SurfaceFlinger::clearAnimationFrameStats() {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.clearStats();
1113 return NO_ERROR;
1114}
1115
1116status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1117 Mutex::Autolock _l(mStateLock);
1118 mAnimFrameTracker.getStats(outStats);
1119 return NO_ERROR;
1120}
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1123 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001124 Mutex::Autolock _l(mStateLock);
1125
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 const auto display = getDisplayDeviceLocked(displayToken);
1127 if (!display) {
1128 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001129 return BAD_VALUE;
1130 }
1131
Peiyong Linfb069302018-04-25 14:34:31 -07001132 // At this point the DisplayDeivce should already be set up,
1133 // meaning the luminance information is already queried from
1134 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001136 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1137 capabilities.getDesiredMaxLuminance(),
1138 capabilities.getDesiredMaxAverageLuminance(),
1139 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140
1141 return NO_ERROR;
1142}
1143
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001144status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1145 ui::PixelFormat* outFormat,
1146 ui::Dataspace* outDataspace,
1147 uint8_t* outComponentMask) const {
1148 if (!outFormat || !outDataspace || !outComponentMask) {
1149 return BAD_VALUE;
1150 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001151 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001152 if (!display || !display->getId()) {
1153 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1154 return BAD_VALUE;
1155 }
1156 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1157 outDataspace, outComponentMask);
1158}
1159
Kevin DuBois74e53772018-11-19 10:52:38 -08001160status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1161 bool enable, uint8_t componentMask,
1162 uint64_t maxFrames) const {
1163 const auto display = getDisplayDevice(displayToken);
1164 if (!display || !display->getId()) {
1165 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1166 return BAD_VALUE;
1167 }
1168
1169 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1170 componentMask, maxFrames);
1171}
1172
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001173status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1174 uint64_t maxFrames, uint64_t timestamp,
1175 DisplayedFrameStats* outStats) const {
1176 const auto display = getDisplayDevice(displayToken);
1177 if (!display || !display->getId()) {
1178 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1179 return BAD_VALUE;
1180 }
1181
1182 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1183 outStats);
1184}
1185
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001186status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1187 if (!outSupported) {
1188 return BAD_VALUE;
1189 }
1190 *outSupported = getRenderEngine().supportsProtectedContent();
1191 return NO_ERROR;
1192}
1193
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001194status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1195 bool* outIsWideColorDisplay) const {
1196 if (!displayToken || !outIsWideColorDisplay) {
1197 return BAD_VALUE;
1198 }
1199 Mutex::Autolock _l(mStateLock);
1200 const auto display = getDisplayDeviceLocked(displayToken);
1201 if (!display) {
1202 return BAD_VALUE;
1203 }
1204 *outIsWideColorDisplay = display->hasWideColorGamut();
1205 return NO_ERROR;
1206}
1207
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001208status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001209 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001210 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212 if (mInjectVSyncs == enable) {
1213 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001214 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215
Ana Krulecc2870422019-01-29 19:00:58 -08001216 auto resyncCallback =
1217 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001218
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001219 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001220 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 if (enable) {
1222 ALOGV("VSync Injections enabled");
1223 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001224 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001225 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001226 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001227 impl::EventThread::InterceptVSyncsCallback(),
1228 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001229 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001230 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 } else {
1232 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001233 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1234 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001235 }
1236
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001237 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001238 }));
1239
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001240 return NO_ERROR;
1241}
1242
1243status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001244 Mutex::Autolock _l(mStateLock);
1245
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001246 if (!mInjectVSyncs) {
1247 ALOGE("VSync Injections not enabled");
1248 return BAD_VALUE;
1249 }
1250 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1251 ALOGV("Injecting VSync inside SurfaceFlinger");
1252 mVSyncInjector->onInjectSyncEvent(when);
1253 }
1254 return NO_ERROR;
1255}
1256
Lloyd Pique755e3192018-01-31 16:46:15 -08001257status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1258 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001259 // Try to acquire a lock for 1s, fail gracefully
1260 const status_t err = mStateLock.timedLock(s2ns(1));
1261 const bool locked = (err == NO_ERROR);
1262 if (!locked) {
1263 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1264 return TIMED_OUT;
1265 }
1266
1267 outLayers->clear();
1268 mCurrentState.traverseInZOrder([&](Layer* layer) {
1269 outLayers->push_back(layer->getLayerDebugInfo());
1270 });
1271
1272 mStateLock.unlock();
1273 return NO_ERROR;
1274}
1275
Peiyong Linc6780972018-10-28 15:24:08 -07001276status_t SurfaceFlinger::getCompositionPreference(
1277 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1278 Dataspace* outWideColorGamutDataspace,
1279 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001280 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001281 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001282 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001283 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001284 return NO_ERROR;
1285}
1286
Dan Stozaec460082018-12-17 15:35:09 -08001287status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1288 const sp<IBinder>& stopLayerHandle,
1289 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001290 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001291 return BAD_VALUE;
1292 }
1293 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001294 return NO_ERROR;
1295}
1296
Dan Stozaec460082018-12-17 15:35:09 -08001297status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001298 if (!listener) {
1299 return BAD_VALUE;
1300 }
Dan Stozaec460082018-12-17 15:35:09 -08001301 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001302 return NO_ERROR;
1303}
Dan Gittik57e63c52019-01-18 16:37:54 +00001304
1305status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1306 bool* outSupport) const {
1307 if (!displayToken || !outSupport) {
1308 return BAD_VALUE;
1309 }
1310 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1311 if (!displayId) {
1312 return NAME_NOT_FOUND;
1313 }
1314 *outSupport =
1315 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1316 return NO_ERROR;
1317}
1318
1319status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1320 float brightness) const {
1321 if (!displayToken) {
1322 return BAD_VALUE;
1323 }
1324 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1325 if (!displayId) {
1326 return NAME_NOT_FOUND;
1327 }
1328 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1329}
1330
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001331// ----------------------------------------------------------------------------
1332
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001333sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1334 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001335 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001336 Mutex::Autolock lock(mStateLock);
1337 return getVsyncPeriod();
1338 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001339
Ana Krulecc2870422019-01-29 19:00:58 -08001340 const auto& handle =
1341 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001342
Ana Krulecc2870422019-01-29 19:00:58 -08001343 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001344}
1345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001346// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347
1348void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001349 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001350}
1351
1352void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001357 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358}
1359
1360void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001361 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001362 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001363}
1364
1365status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001366 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001367 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001368}
1369
1370status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001371 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001372 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001373 if (res == NO_ERROR) {
1374 msg->wait();
1375 }
1376 return res;
1377}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001378
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001379void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001380 do {
1381 waitForEvent();
1382 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001383}
1384
Dominik Laskowski83b88212018-12-11 13:34:06 -08001385nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001386 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001387 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1388 return 0;
1389 }
1390
1391 const auto config = getHwComposer().getActiveConfig(*displayId);
1392 return config ? config->getVsyncPeriod() : 0;
1393}
1394
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001395void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1396 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001397 ATRACE_NAME("SF onVsync");
1398
Steven Thomas3cfac282017-02-06 12:29:30 -08001399 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001401 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 return;
1403 }
1404
Dominik Laskowski075d3172018-05-24 15:50:06 -07001405 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001406 return;
1407 }
1408
Dominik Laskowski075d3172018-05-24 15:50:06 -07001409 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001410 // For now, we don't do anything with external display vsyncs.
1411 return;
1412 }
1413
Alec Mouri754c98a2019-03-18 18:53:42 -07001414 bool periodChanged = false;
1415 mScheduler->addResyncSample(timestamp, &periodChanged);
1416 if (periodChanged) {
1417 mVsyncModulator.onRefreshRateChangeDetected();
1418 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001419}
1420
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001421void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001422 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1423 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001424}
1425
Dominik Laskowski22488f62019-03-28 09:53:04 -07001426bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1427 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001428}
1429
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001430void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001431 const auto display = getDefaultDisplayDeviceLocked();
1432 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001433 return;
1434 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001435 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001436
Ana Krulec7d1d6832018-12-27 11:10:09 -08001437 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001438 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001439 if (!refreshRateConfig) {
1440 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001441 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001442 }
Ady Abraham1902d072019-03-01 17:18:59 -08001443
Alec Mouri0a1cc962019-03-14 12:33:02 -07001444 const int desiredConfigId = refreshRateConfig->configId;
1445
Dominik Laskowski22488f62019-03-28 09:53:04 -07001446 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001447 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1448 return;
1449 }
1450
Dominik Laskowski22488f62019-03-28 09:53:04 -07001451 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001452}
1453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001455 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001456 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001457 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001458
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 // Ignore events that do not have the right sequenceId.
1460 if (sequenceId != getBE().mComposerSequenceId) {
1461 return;
1462 }
1463
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 // Only lock if we're not on the main thread. This function is normally
1465 // called on a hwbinder thread, but for the primary display it's called on
1466 // the main thread with the state lock already held, so don't attempt to
1467 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001468 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001471
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001472 if (std::this_thread::get_id() == mMainThreadId) {
1473 // Process all pending hot plug events immediately if we are on the main thread.
1474 processDisplayHotplugEventsLocked();
1475 }
1476
Lloyd Piqueba04e622017-12-14 17:11:26 -08001477 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001478}
1479
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001480void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001482 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001485 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001486}
1487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001488void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001489 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001491 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001492 getHwComposer().setVsyncEnabled(*displayId,
1493 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1494 }
Mathias Agopian86303202012-07-24 22:46:10 -07001495}
1496
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001498void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001499 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001500 // Clear the drawing state so that the logic inside of
1501 // handleTransactionLocked will fire. It will determine the delta between
1502 // mCurrentState and mDrawingState and re-apply all changes when we make the
1503 // transition.
1504 mDrawingState.displays.clear();
1505 mDisplays.clear();
1506}
1507
Steven Thomas050b2c82017-03-06 11:45:16 -08001508void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001509 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001510 if (!mVrFlinger)
1511 return;
1512 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001513 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001514 return;
1515 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001516
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 ALOGE("Vr flinger is only supported for remote hardware composer"
1519 " service connections. Ignoring request to transition to vr"
1520 " flinger.");
1521 mVrFlingerRequestsDisplay = false;
1522 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001523 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001524
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001525 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526
Steven Thomas0123ac62018-07-12 11:32:34 -07001527 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001528 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001529
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001530 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001531
1532 // Clear out all the output layers from the composition engine for all
1533 // displays before destroying the hardware composer interface. This ensures
1534 // any HWC layers are destroyed through that interface before it becomes
1535 // invalid.
1536 for (const auto& [token, displayDevice] : mDisplays) {
1537 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1538 compositionengine::Output::OutputLayers());
1539 }
1540
Steven Thomas0123ac62018-07-12 11:32:34 -07001541 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1542 // called below. Clear the reference now so we don't accidentally use it
1543 // later.
1544 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001547 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001551 // Delete the current instance before creating the new one
1552 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1553 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1554 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1555 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
Lloyd Pique441d5042018-10-18 16:49:51 -07001557 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001558 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001559
1560 if (vrFlingerRequestsDisplay) {
1561 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563
1564 mVisibleRegionsDirty = true;
1565 invalidateHwcGeometry();
1566
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001567 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001568 display = getDefaultDisplayDeviceLocked();
1569 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001570 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001571
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001573 const nsecs_t vsyncPeriod = getVsyncPeriod();
1574 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001575
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001576 // The present fences returned from vr_hwc are not an accurate
1577 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001578 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579
Steven Thomasb02664d2017-07-26 18:48:28 -07001580 // Use phase of 0 since phase is not known.
1581 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001582 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001583 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001584
Ana Krulecc2870422019-01-29 19:00:58 -08001585 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001586
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001587 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001589}
1590
Ady Abrahambe0f9482019-04-24 15:41:53 -07001591bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1592 // We are storing the last 2 present fences. If sf's phase offset is to be
1593 // woken up before the actual vsync but targeting the next vsync, we need to check
1594 // fence N-2
1595 const sp<Fence>& fence =
1596 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1597 ? mPreviousPresentFences[0]
1598 : mPreviousPresentFences[1];
1599
1600 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1601}
1602
Dominik Laskowski22488f62019-03-28 09:53:04 -07001603void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001604 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001605 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001606 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001607 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001608 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1609 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1610 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1611 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1612 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1613 if (frameMissed) {
1614 mFrameMissedCount++;
1615 mTimeStats->incrementMissedFrames();
1616 }
1617
Alec Mouri40189b02019-03-05 15:07:54 -08001618 if (hwcFrameMissed) {
1619 mHwcFrameMissedCount++;
1620 }
1621
1622 if (gpuFrameMissed) {
1623 mGpuFrameMissedCount++;
1624 }
1625
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001626 if (mUseSmart90ForVideo) {
1627 // This call is made each time SF wakes up and creates a new frame. It is part
1628 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001629 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001630 }
1631
Ady Abrahamb838aed2019-02-12 15:30:16 -08001632 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001633 break;
1634 }
1635
Alec Mourife3dc942019-02-12 14:19:18 -08001636 // For now, only propagate backpressure when missing a hwc frame.
Alec Mourib0f45822019-05-06 11:01:35 -07001637 if (hwcFrameMissed && !gpuFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001638 if (mPropagateBackpressure) {
1639 signalLayerUpdate();
1640 break;
1641 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001642 }
Dan Stoza50182882016-07-08 12:02:20 -07001643
Steven Thomas050b2c82017-03-06 11:45:16 -08001644 // Now that we're going to make it to the handleMessageTransaction()
1645 // call below it's safe to call updateVrFlinger(), which will
1646 // potentially trigger a display handoff.
1647 updateVrFlinger();
1648
Dan Stoza6b9454d2014-11-07 16:00:59 -08001649 bool refreshNeeded = handleMessageTransaction();
1650 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001651
1652 updateCursorAsync();
1653 updateInputFlinger();
1654
Dan Stoza58784442014-12-02 16:58:17 -08001655 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001656 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001657 // Signal a refresh if a transaction modified the window state,
1658 // a new buffer was latched, or if HWC has requested a full
1659 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001660 signalRefresh();
1661 }
1662 break;
1663 }
1664 case MessageQueue::REFRESH: {
1665 handleMessageRefresh();
1666 break;
1667 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001668 }
1669}
1670
Dan Stoza6b9454d2014-11-07 16:00:59 -08001671bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001672 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001673 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001674
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001675 bool flushedATransaction = flushTransactionQueues();
1676
1677 bool runHandleTransaction = transactionFlags &&
1678 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1679
1680 if (runHandleTransaction) {
1681 handleTransaction(eTransactionMask);
1682 } else {
1683 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001684 }
1685
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001686 if (transactionFlushNeeded()) {
1687 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001688 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001689
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001690 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001691}
1692
Mathias Agopian4fec8732012-06-29 14:12:52 -07001693void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001695
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001696 mRefreshPending = false;
1697
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001698 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001699 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001700 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001701 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001702 for (const auto& [token, display] : mDisplays) {
1703 beginFrame(display);
1704 prepareFrame(display);
1705 doDebugFlashRegions(display, repaintEverything);
1706 doComposition(display, repaintEverything);
1707 }
1708
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001709 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710
1711 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001712 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001713
Dan Stozabfbffeb2016-07-21 14:49:33 -07001714 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001715 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001716 for (const auto& [token, displayDevice] : mDisplays) {
1717 auto display = displayDevice->getCompositionDisplay();
1718 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001719 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001720 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001721 mHadDeviceComposition =
1722 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001723 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001724
Jorim Jaggi90535212018-05-23 23:44:06 +02001725 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001726
David Sodman7e4ae112018-02-09 15:02:28 -08001727 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001728}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001729
David Sodmanfa9b2af2017-12-24 13:28:59 -08001730
1731bool SurfaceFlinger::handleMessageInvalidate() {
1732 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001733 bool refreshNeeded = handlePageFlip();
1734
Vishnu Nair4351ad52019-02-11 14:13:02 -08001735 if (mVisibleRegionsDirty) {
1736 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001737 if (mTracingEnabled) {
1738 mTracing.notify("visibleRegionsDirty");
1739 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001740 }
1741
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001742 for (auto& layer : mLayersPendingRefresh) {
1743 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001744 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001745 invalidateLayerStack(layer, visibleReg);
1746 }
1747 mLayersPendingRefresh.clear();
1748 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001749}
1750
David Sodman79bba0e2018-08-05 18:07:49 -07001751void SurfaceFlinger::calculateWorkingSet() {
1752 ATRACE_CALL();
1753 ALOGV(__FUNCTION__);
1754
David Sodman79bba0e2018-08-05 18:07:49 -07001755 // build the h/w work list
1756 if (CC_UNLIKELY(mGeometryInvalid)) {
1757 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001758 for (const auto& [token, displayDevice] : mDisplays) {
1759 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001760
Lloyd Piquea83776c2019-01-29 18:42:32 -08001761 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001762
Lloyd Piquea83776c2019-01-29 18:42:32 -08001763 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1764 auto& compositionState = layer->editState();
1765 compositionState.forceClientComposition = false;
1766 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1767 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001768 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001769
Lloyd Piquea83776c2019-01-29 18:42:32 -08001770 // The output Z order is set here based on a simple counter.
1771 compositionState.z = zOrder++;
1772
1773 // Update the display independent composition state. This goes
1774 // to the general composition layer state structure.
1775 // TODO: Do this once per compositionengine::CompositionLayer.
1776 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1777 true);
1778
1779 // Recalculate the geometry state of the output layer.
1780 layer->updateCompositionState(true);
1781
1782 // Write the updated geometry state to the HWC
1783 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001784 }
1785 }
1786 }
1787
1788 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001789 for (const auto& [token, displayDevice] : mDisplays) {
1790 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001791 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001792 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001793 continue;
1794 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001795 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001796
1797 if (mDrawingState.colorMatrixChanged) {
1798 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001799 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001800 Dataspace targetDataspace = Dataspace::UNKNOWN;
1801 if (useColorManagement) {
1802 ColorMode colorMode;
1803 RenderIntent renderIntent;
1804 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1805 display->setColorMode(colorMode, targetDataspace, renderIntent);
1806 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001807 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001808 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001809 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001810 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1811 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001812 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001813 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001814 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1815 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001816 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001817 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001818 }
1819
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001820 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001821 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001822 }
1823
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001824 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001825 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001826 layer->setCompositionType(displayDevice,
1827 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001828 continue;
1829 }
1830
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001832 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001833 displayDevice->getSupportedPerFrameMetadata(),
1834 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1835 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001836 }
1837 }
1838
1839 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001840
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001841 for (const auto& [token, displayDevice] : mDisplays) {
1842 auto display = displayDevice->getCompositionDisplay();
1843 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001844 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1845 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1846 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001847 }
1848 }
David Sodman79bba0e2018-08-05 18:07:49 -07001849}
1850
Lloyd Pique32cbe282018-10-19 13:09:22 -07001851void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1852 bool repaintEverything) {
1853 auto display = displayDevice->getCompositionDisplay();
1854 const auto& displayState = display->getState();
1855
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856 // is debugging enabled
1857 if (CC_LIKELY(!mDebugRegion))
1858 return;
1859
Lloyd Pique32cbe282018-10-19 13:09:22 -07001860 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001861 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001862 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001863 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001864 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001865 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001866 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001868 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869 }
1870 }
1871
Lloyd Pique32cbe282018-10-19 13:09:22 -07001872 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873
1874 if (mDebugRegion > 1) {
1875 usleep(mDebugRegion * 1000);
1876 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001877
Lloyd Pique32cbe282018-10-19 13:09:22 -07001878 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879}
1880
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001881void SurfaceFlinger::logLayerStats() {
1882 ATRACE_CALL();
1883 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001884 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001885 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001886 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001887 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001888 }
1889 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001890
1891 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001892 }
1893}
1894
David Sodman2b406362017-12-15 13:33:47 -08001895void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 ATRACE_CALL();
1898 ALOGV("preComposition");
1899
David Sodman2b406362017-12-15 13:33:47 -08001900 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1901
Mathias Agopiancd60f992012-08-16 16:28:27 -07001902 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001903 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001904 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001905 needExtraInvalidate = true;
1906 }
Robert Carr2047fae2016-11-28 14:09:09 -08001907 });
1908
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909 if (needExtraInvalidate) {
1910 signalLayerUpdate();
1911 }
1912}
1913
Ana Krulece588e312018-09-18 12:32:24 -07001914void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1915 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916 // Update queue of past composite+present times and determine the
1917 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001918 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001920 while (!getBE().mCompositePresentTimes.empty()) {
1921 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001922 // Cached values should have been updated before calling this method,
1923 // which helps avoid duplicate syscalls.
1924 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1925 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1926 break;
1927 }
1928 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001929 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930 }
1931
1932 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001933 while (getBE().mCompositePresentTimes.size() > 16) {
1934 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001935 }
1936
Ana Krulece588e312018-09-18 12:32:24 -07001937 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001938}
1939
Ana Krulece588e312018-09-18 12:32:24 -07001940void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1941 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 // Integer division and modulo round toward 0 not -inf, so we need to
1943 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001944 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1945 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1946 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947
Ana Krulec757f63a2019-01-25 10:46:18 -08001948 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001949 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001950 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001951 }
1952
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 // Snap the latency to a value that removes scheduling jitter from the
1954 // composition and present times, which often have >1ms of jitter.
1955 // Reducing jitter is important if an app attempts to extrapolate
1956 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001957 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001959 nsecs_t bias = stats.vsyncPeriod / 2;
1960 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1961 nsecs_t snappedCompositeToPresentLatency =
1962 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963
David Sodman99974d22017-11-28 12:04:33 -08001964 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001965 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1966 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001967 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001968}
1969
David Sodman2b406362017-12-15 13:33:47 -08001970void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001971{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 ATRACE_CALL();
1973 ALOGV("postComposition");
1974
Brian Anderson3546a3f2016-07-14 11:51:14 -07001975 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001976 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001977 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001978 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001979 }
1980
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001981 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001982 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001983
David Sodman73beded2017-11-15 11:56:06 -08001984 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001985 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001986 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001987 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001988 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1989 ->getRenderSurface()
1990 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001991 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001992 } else {
1993 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1994 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001995
David Sodman73beded2017-11-15 11:56:06 -08001996 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001997 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1998 mPreviousPresentFences[0] = displayDevice
1999 ? getHwComposer().getPresentFence(*displayDevice->getId())
2000 : Fence::NO_FENCE;
2001 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002002 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002003
Ana Krulece588e312018-09-18 12:32:24 -07002004 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002005 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002006
David Sodman2b406362017-12-15 13:33:47 -08002007 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002008 // when we started doing work for this frame, but that should be okay
2009 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002010 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002011 CompositorTiming compositorTiming;
2012 {
David Sodman99974d22017-11-28 12:04:33 -08002013 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2014 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002015 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002016
Robert Carr2047fae2016-11-28 14:09:09 -08002017 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002018 bool frameLatched =
2019 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2020 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002021 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002022 recordBufferingStats(layer->getName().string(),
2023 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002024 }
Robert Carr2047fae2016-11-28 14:09:09 -08002025 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002026
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002027 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002028 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002029 }
2030
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002031 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002032 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2033 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002034 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002035 }
2036 }
2037
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002038 if (mAnimCompositionPending) {
2039 mAnimCompositionPending = false;
2040
Brian Anderson4e606e32017-03-16 15:34:57 -07002041 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002042 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002043 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002045 // The HWC doesn't support present fences, so use the refresh
2046 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002047 const nsecs_t presentTime =
2048 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002049 mAnimFrameTracker.setActualPresentTime(presentTime);
2050 }
2051 mAnimFrameTracker.advanceFrame();
2052 }
Dan Stozab90cf072015-03-05 11:05:59 -08002053
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002054 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002055 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002056 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002057 }
2058
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002059 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002060
Lloyd Pique32cbe282018-10-19 13:09:22 -07002061 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2062 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002063 return;
2064 }
2065
2066 nsecs_t currentTime = systemTime();
2067 if (mHasPoweredOff) {
2068 mHasPoweredOff = false;
2069 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002070 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002071 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002072 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2073 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002074 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002075 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002076 }
David Sodman4a36e932017-11-07 14:29:47 -08002077 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002078 }
David Sodman4a36e932017-11-07 14:29:47 -08002079 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002080
2081 {
2082 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002083 if (mTexturePool.size() < mTexturePoolSize) {
2084 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002085 const size_t offset = mTexturePool.size();
2086 mTexturePool.resize(mTexturePoolSize);
2087 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2088 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002089 } else if (mTexturePool.size() > mTexturePoolSize) {
2090 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2091 const size_t offset = mTexturePoolSize;
2092 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2093 mTexturePool.resize(mTexturePoolSize);
2094 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002095 }
2096 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002097
Ady Abrahambe0f9482019-04-24 15:41:53 -07002098 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Walle2ffb422018-10-12 11:33:52 -07002099 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002100
Kevin DuBois413287f2019-02-25 08:46:47 -08002101 if (mLumaSampling && mRegionSamplingThread) {
2102 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002103 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002104
2105 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2106 // side-effect of getTotalSize(), so we check that again here
2107 if (ATRACE_ENABLED()) {
2108 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2109 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002110}
2111
Vishnu Nair4351ad52019-02-11 14:13:02 -08002112void SurfaceFlinger::computeLayerBounds() {
2113 for (const auto& pair : mDisplays) {
2114 const auto& displayDevice = pair.second;
2115 const auto display = displayDevice->getCompositionDisplay();
2116 for (const auto& layer : mDrawingState.layersSortedByZ) {
2117 // only consider the layers on the given layer stack
2118 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002119 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002120 }
2121
2122 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2123 }
2124 }
2125}
2126
Mathias Agopiancd60f992012-08-16 16:28:27 -07002127void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 ATRACE_CALL();
2129 ALOGV("rebuildLayerStacks");
2130
Mathias Agopiancd60f992012-08-16 16:28:27 -07002131 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002132 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002133 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002134 mVisibleRegionsDirty = false;
2135 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002136
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002137 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 const auto& displayDevice = pair.second;
2139 auto display = displayDevice->getCompositionDisplay();
2140 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002141 Region opaqueRegion;
2142 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002143 compositionengine::Output::OutputLayers layersSortedByZ;
2144 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002145 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002146 const ui::Transform& tr = displayState.transform;
2147 const Rect bounds = displayState.bounds;
2148 if (displayState.isEnabled) {
2149 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002150
Jeff Sharkey76488112017-02-27 14:15:18 -07002151 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002152 auto compositionLayer = layer->getCompositionLayer();
2153 if (compositionLayer == nullptr) {
2154 return;
2155 }
2156
Lloyd Pique32cbe282018-10-19 13:09:22 -07002157 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002158 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2159 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2160
Lloyd Pique07e33212018-12-18 16:33:37 -08002161 bool needsOutputLayer = false;
2162
Lloyd Piqueef36b002019-01-23 17:52:04 -08002163 if (display->belongsInOutput(layer->getLayerStack(),
2164 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002165 Region drawRegion(tr.transform(
2166 layer->visibleNonTransparentRegion));
2167 drawRegion.andSelf(bounds);
2168 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002169 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002170 }
Chia-I Wu83806892017-11-16 10:50:20 -08002171 }
2172
Lloyd Pique07e33212018-12-18 16:33:37 -08002173 if (needsOutputLayer) {
2174 layersSortedByZ.emplace_back(
2175 display->getOrCreateOutputLayer(displayId, compositionLayer,
2176 layerFE));
2177 deprecated_layersSortedByZ.add(layer);
2178
2179 auto& outputLayerState = layersSortedByZ.back()->editState();
2180 outputLayerState.visibleRegion =
2181 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2182 } else if (displayId) {
2183 // For layers that are being removed from a HWC display,
2184 // and that have queued frames, add them to a a list of
2185 // released layers so we can properly set a fence.
2186 bool hasExistingOutputLayer =
2187 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2188 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2189 mLayersWithQueuedFrames.cend(),
2190 layer) != mLayersWithQueuedFrames.cend();
2191
2192 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002193 layersNeedingFences.add(layer);
2194 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002195 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002196 });
2197 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002198
2199 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2200
2201 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002202 displayDevice->setLayersNeedingFences(layersNeedingFences);
2203
2204 Region undefinedRegion{bounds};
2205 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2206
2207 display->editState().undefinedRegion = undefinedRegion;
2208 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002209 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002211}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002212
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002213// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002214// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002215// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002216// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002217// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002218// The returned HDR data space is one of
2219// - Dataspace::UNKNOWN
2220// - Dataspace::BT2020_HLG
2221// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002222Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2223 Dataspace* outHdrDataSpace,
2224 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002225 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002226 *outHdrDataSpace = Dataspace::UNKNOWN;
2227
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002228 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002229 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002230 case Dataspace::V0_SCRGB:
2231 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002232 case Dataspace::BT2020:
2233 case Dataspace::BT2020_ITU:
2234 case Dataspace::BT2020_LINEAR:
2235 case Dataspace::DISPLAY_BT2020:
2236 bestDataSpace = Dataspace::DISPLAY_BT2020;
2237 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002238 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002239 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002240 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002241 case Dataspace::BT2020_PQ:
2242 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002243 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002244 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002245 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002246 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002247 case Dataspace::BT2020_HLG:
2248 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002249 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002250 // When there's mixed PQ content and HLG content, we set the HDR
2251 // data space to be BT2020_PQ and convert HLG to PQ.
2252 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2253 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002254 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255 break;
2256 default:
2257 break;
2258 }
Romain Guy54f154a2017-10-24 21:40:32 +01002259 }
2260
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002261 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002262}
2263
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002264// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002265void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2266 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2268 *outMode = ColorMode::NATIVE;
2269 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002272 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002273
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002275 bool isHdrClientComposition = false;
2276 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002277
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002278 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2279
Peiyong Lina3ea5592019-02-10 14:45:00 -08002280 switch (mForceColorMode) {
2281 case ColorMode::SRGB:
2282 bestDataSpace = Dataspace::V0_SRGB;
2283 break;
2284 case ColorMode::DISPLAY_P3:
2285 bestDataSpace = Dataspace::DISPLAY_P3;
2286 break;
2287 default:
2288 break;
2289 }
2290
Peiyong Lindfde5112018-06-05 10:58:41 -07002291 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002292 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2293 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002294 if (isHdr) {
2295 bestDataSpace = hdrDataSpace;
2296 }
2297
Chia-I Wu0d711262018-05-21 15:19:35 -07002298 RenderIntent intent;
2299 switch (mDisplayColorSetting) {
2300 case DisplayColorSetting::MANAGED:
2301 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002302 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002303 break;
2304 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002305 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002306 break;
2307 default: // vendor display color setting
2308 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2309 break;
2310 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002311
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002312 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002313}
2314
Lloyd Pique32cbe282018-10-19 13:09:22 -07002315void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2316 auto display = displayDevice->getCompositionDisplay();
2317 const auto& displayState = display->getState();
2318
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002319 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002320 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2321 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002322
David Sodmanfa9b2af2017-12-24 13:28:59 -08002323 // If nothing has changed (!dirty), don't recompose.
2324 // If something changed, but we don't currently have any visible layers,
2325 // and didn't when we last did a composition, then skip it this time.
2326 // The second rule does two things:
2327 // - When all layers are removed from a display, we'll emit one black
2328 // frame, then nothing more until we get new layers.
2329 // - When a display is created with a private layer stack, we won't
2330 // emit any black frames until a layer is added to the layer stack.
2331 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002332
Dominik Laskowski075d3172018-05-24 15:50:06 -07002333 const char flagPrefix[] = {'-', '+'};
2334 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002335 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2336 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2337 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2338 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002339
Lloyd Pique31cb2942018-10-19 17:23:03 -07002340 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002341
David Sodmanfa9b2af2017-12-24 13:28:59 -08002342 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002343 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002344 }
2345}
2346
Lloyd Pique32cbe282018-10-19 13:09:22 -07002347void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2348 auto display = displayDevice->getCompositionDisplay();
2349 const auto& displayState = display->getState();
2350
2351 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002352 return;
David Sodman2b406362017-12-15 13:33:47 -08002353 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002354
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002355 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002356 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002357 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002358}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002359
Lloyd Pique32cbe282018-10-19 13:09:22 -07002360void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002361 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002362 ALOGV("doComposition");
2363
Lloyd Pique32cbe282018-10-19 13:09:22 -07002364 auto display = displayDevice->getCompositionDisplay();
2365 const auto& displayState = display->getState();
2366
2367 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002368 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002369 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002370
David Sodmanfa9b2af2017-12-24 13:28:59 -08002371 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002373
Lloyd Pique32cbe282018-10-19 13:09:22 -07002374 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002375 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002376 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002377 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002378}
2379
David Sodmanfa9b2af2017-12-24 13:28:59 -08002380void SurfaceFlinger::postFrame()
2381{
2382 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002383 const auto display = getDefaultDisplayDeviceLocked();
2384 if (display && getHwComposer().isConnected(*display->getId())) {
2385 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002386 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2387 logFrameStats();
2388 }
2389 }
2390}
2391
Lloyd Pique32cbe282018-10-19 13:09:22 -07002392void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002393 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002394 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002395
Lloyd Pique32cbe282018-10-19 13:09:22 -07002396 auto display = displayDevice->getCompositionDisplay();
2397 const auto& displayState = display->getState();
2398 const auto displayId = display->getId();
2399
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 if (displayId) {
2402 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002403 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002404 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002405 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002406 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002407 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002408
Chia-I Wu7b549592017-11-15 09:14:57 -08002409 // The layer buffer from the previous frame (if any) is released
2410 // by HWC only when the release fence from this frame (if any) is
2411 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002412 if (layer->getState().hwc) {
2413 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002414 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002415 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2416 usedClientComposition =
2417 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002418 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002419
2420 // If the layer was client composited in the previous frame, we
2421 // need to merge with the previous client target acquire fence.
2422 // Since we do not track that, always merge with the current
2423 // client target acquire fence when it is available, even though
2424 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002425 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002426 releaseFence =
2427 Fence::merge("LayerRelease", releaseFence,
2428 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002429 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002430
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002431 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 }
Chia-I Wu83806892017-11-16 10:50:20 -08002433
2434 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002435 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002436 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002439 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002441 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002442 }
2443 }
2444
Dominik Laskowski075d3172018-05-24 15:50:06 -07002445 if (displayId) {
2446 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002447 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002448 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449}
2450
Mathias Agopian87baae12012-07-31 12:38:26 -07002451void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452{
Mathias Agopian841cde52012-03-01 15:44:37 -08002453 ATRACE_CALL();
2454
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002455 // here we keep a copy of the drawing state (that is the state that's
2456 // going to be overwritten by handleTransactionLocked()) outside of
2457 // mStateLock so that the side-effects of the State assignment
2458 // don't happen with mStateLock held (which can cause deadlocks).
2459 State drawingState(mDrawingState);
2460
Mathias Agopianca4d3602011-05-19 15:38:14 -07002461 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002462 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463
Mathias Agopianca4d3602011-05-19 15:38:14 -07002464 // Here we're guaranteed that some transaction flags are set
2465 // so we can call handleTransactionLocked() unconditionally.
2466 // We call getTransactionFlags(), which will also clear the flags,
2467 // with mStateLock held to guarantee that mCurrentState won't change
2468 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002469
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002470 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002471 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002472 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002473
Mathias Agopianca4d3602011-05-19 15:38:14 -07002474 mDebugInTransaction = 0;
2475 invalidateHwcGeometry();
2476 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002477}
2478
Lloyd Piqueba04e622017-12-14 17:11:26 -08002479void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2480 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 const std::optional<DisplayIdentificationInfo> info =
2482 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002483
Dominik Laskowski075d3172018-05-24 15:50:06 -07002484 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002485 continue;
2486 }
2487
Lloyd Piqueba04e622017-12-14 17:11:26 -08002488 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002490 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 mPhysicalDisplayTokens[info->id] = new BBinder();
2492 DisplayDeviceState state;
2493 state.displayId = info->id;
2494 state.isSecure = true; // All physical displays are currently considered secure.
2495 state.displayName = info->name;
2496 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2497 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002498 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002499 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002500 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002501
Dominik Laskowski075d3172018-05-24 15:50:06 -07002502 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2503 if (index >= 0) {
2504 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2505 mInterceptor->saveDisplayDeletion(state.sequenceId);
2506 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002507 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002509 }
2510
2511 processDisplayChangesLocked();
2512 }
2513
2514 mPendingHotplugEvents.clear();
2515}
2516
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002517void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002518 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2519 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002520}
2521
Lloyd Pique99d3da52018-01-22 17:48:03 -08002522sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002524 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002525 const sp<IGraphicBufferProducer>& producer) {
2526 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002527 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002528 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002529 creationArgs.isSecure = state.isSecure;
2530 creationArgs.displaySurface = dispSurface;
2531 creationArgs.hasWideColorGamut = false;
2532 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002533
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002534 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 creationArgs.isPrimary = isInternalDisplay;
2536
2537 if (useColorManagement && displayId) {
2538 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002540 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002541 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002542 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002543
Dominik Laskowski7e045462018-05-30 13:02:02 -07002544 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002546 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547 }
tangrobin6753a022018-08-10 10:58:54 +08002548 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002549
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 if (displayId) {
2551 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002552 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002554 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002555
Lloyd Pique90c115d2018-09-18 21:39:42 -07002556 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002557 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002558 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002559
Lloyd Pique99d3da52018-01-22 17:48:03 -08002560 // Make sure that composition can never be stalled by a virtual display
2561 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002562 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002563 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002564 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2565 }
2566
Dominik Laskowski075d3172018-05-24 15:50:06 -07002567 creationArgs.displayInstallOrientation =
2568 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002569
Lloyd Pique99d3da52018-01-22 17:48:03 -08002570 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002571 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002572
Lloyd Pique90c115d2018-09-18 21:39:42 -07002573 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574
2575 if (maxFrameBufferAcquiredBuffers >= 3) {
2576 nativeWindowSurface->preallocateBuffers();
2577 }
2578
2579 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002580 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002583 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002584 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002585 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2586 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 if (!state.isVirtual()) {
2588 LOG_ALWAYS_FATAL_IF(!displayId);
2589 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002590 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002592 display->setLayerStack(state.layerStack);
2593 display->setProjection(state.orientation, state.viewport, state.frame);
2594 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002597}
2598
Lloyd Pique347200f2017-12-14 17:00:15 -08002599void SurfaceFlinger::processDisplayChangesLocked() {
2600 // here we take advantage of Vector's copy-on-write semantics to
2601 // improve performance by skipping the transaction entirely when
2602 // know that the lists are identical
2603 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2604 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2605 if (!curr.isIdenticalTo(draw)) {
2606 mVisibleRegionsDirty = true;
2607 const size_t cc = curr.size();
2608 size_t dc = draw.size();
2609
2610 // find the displays that were removed
2611 // (ie: in drawing state but not in current state)
2612 // also handle displays that changed
2613 // (ie: displays that are in both lists)
2614 for (size_t i = 0; i < dc;) {
2615 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2616 if (j < 0) {
2617 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002618 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002619 // Save display ID before disconnecting.
2620 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002621 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002622
2623 if (!display->isVirtual()) {
2624 LOG_ALWAYS_FATAL_IF(!displayId);
2625 dispatchDisplayHotplugEvent(displayId->value, false);
2626 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002627 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002628
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002629 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002630 } else {
2631 // this display is in both lists. see if something changed.
2632 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002633 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2635 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2636 if (state_binder != draw_binder) {
2637 // changing the surface is like destroying and
2638 // recreating the DisplayDevice, so we just remove it
2639 // from the drawing state, so that it get re-added
2640 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002641 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002642 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002644 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002645 mDrawingState.displays.removeItemsAt(i);
2646 dc--;
2647 // at this point we must loop to the next item
2648 continue;
2649 }
2650
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002651 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002652 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002653 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002654 }
2655 if ((state.orientation != draw[i].orientation) ||
2656 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002657 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002658 }
2659 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002660 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002661 }
2662 }
2663 }
2664 ++i;
2665 }
2666
2667 // find displays that were added
2668 // (ie: in current state but not in drawing state)
2669 for (size_t i = 0; i < cc; i++) {
2670 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2671 const DisplayDeviceState& state(curr[i]);
2672
Lloyd Pique542307f2018-10-19 13:24:08 -07002673 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002674 sp<IGraphicBufferProducer> producer;
2675 sp<IGraphicBufferProducer> bqProducer;
2676 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002677 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002678
Dominik Laskowski075d3172018-05-24 15:50:06 -07002679 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002680 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002681 // Virtual displays without a surface are dormant:
2682 // they have external state (layer stack, projection,
2683 // etc.) but no internal state (i.e. a DisplayDevice).
2684 if (state.surface != nullptr) {
2685 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002686 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 int width = 0;
2688 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2689 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2690 int height = 0;
2691 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2692 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2693 int intFormat = 0;
2694 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2695 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002696 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002697
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698 displayId =
2699 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 }
2701
2702 // TODO: Plumb requested format back up to consumer
2703
2704 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 bqProducer, bqConsumer,
2707 state.displayName);
2708
2709 dispSurface = vds;
2710 producer = vds;
2711 }
2712 } else {
2713 ALOGE_IF(state.surface != nullptr,
2714 "adding a supported display, but rendering "
2715 "surface is provided (%p), ignoring it",
2716 state.surface.get());
2717
Dominik Laskowski075d3172018-05-24 15:50:06 -07002718 displayId = state.displayId;
2719 LOG_ALWAYS_FATAL_IF(!displayId);
2720 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 producer = bqProducer;
2722 }
2723
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002726 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002727 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002729 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002731 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 }
2733 }
2734 }
2735 }
2736 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002737
2738 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002739}
2740
Mathias Agopian87baae12012-07-31 12:38:26 -07002741void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002742{
Dan Stoza7dde5992015-05-22 09:51:44 -07002743 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002744 mCurrentState.traverseInZOrder([](Layer* layer) {
2745 layer->notifyAvailableFrames();
2746 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002747
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 /*
2749 * Traversal of the children
2750 * (perform the transaction for each of them if needed)
2751 */
2752
Marissa Wall06255332019-03-27 13:48:27 -07002753 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002754 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002756 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757
2758 const uint32_t flags = layer->doTransaction(0);
2759 if (flags & Layer::eVisibleRegion)
2760 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002761
2762 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002763 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002764 }
Robert Carr2047fae2016-11-28 14:09:09 -08002765 });
Marissa Wall06255332019-03-27 13:48:27 -07002766 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767 }
2768
2769 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002770 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 */
2772
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002775 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002776 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002778 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002779 // The transform hint might have changed for some layers
2780 // (either because a display has changed, or because a layer
2781 // as changed).
2782 //
2783 // Walk through all the layers in currentLayers,
2784 // and update their transform hint.
2785 //
2786 // If a layer is visible only on a single display, then that
2787 // display is used to calculate the hint, otherwise we use the
2788 // default display.
2789 //
2790 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2791 // the hint is set before we acquire a buffer from the surface texture.
2792 //
2793 // NOTE: layer transactions have taken place already, so we use their
2794 // drawing state. However, SurfaceFlinger's own transaction has not
2795 // happened yet, so we must use the current state layer list
2796 // (soon to become the drawing state list).
2797 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002798 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002799 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002800 bool first = true;
2801 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002802 // NOTE: we rely on the fact that layers are sorted by
2803 // layerStack first (so we don't have to traverse the list
2804 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002805 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002806 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002807 currentlayerStack = layerStack;
2808 // figure out if this layerstack is mirrored
2809 // (more than one display) if so, pick the default display,
2810 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002811 hintDisplay = nullptr;
2812 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002813 if (display->getCompositionDisplay()
2814 ->belongsInOutput(layer->getLayerStack(),
2815 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002816 if (hintDisplay) {
2817 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002818 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002819 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002820 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002821 }
2822 }
2823 }
2824 }
Chet Haase91d25932013-04-11 15:24:55 -07002825
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002826 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002827 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2828 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002829
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002830 // could be null when this layer is using a layerStack
2831 // that is not visible on any display. Also can occur at
2832 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002833 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002834 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002835
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002836 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002837 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 if (hintDisplay) {
2839 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002840 }
Robert Carr2047fae2016-11-28 14:09:09 -08002841
2842 first = false;
2843 });
Mathias Agopian84300952012-11-21 16:02:13 -08002844 }
2845
2846
Mathias Agopian3559b072012-08-15 13:46:03 -07002847 /*
2848 * Perform our own transaction if needed
2849 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002850
2851 if (mLayersAdded) {
2852 mLayersAdded = false;
2853 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002854 mVisibleRegionsDirty = true;
2855 }
2856
2857 // some layers might have been removed, so
2858 // we need to update the regions they're exposing.
2859 if (mLayersRemoved) {
2860 mLayersRemoved = false;
2861 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002862 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002863 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002864 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002866 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002867 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002868 }
Robert Carr2047fae2016-11-28 14:09:09 -08002869 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 }
2871
Vishnu Nairec0ab382019-02-13 15:32:56 -08002872 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002874}
2875
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002876void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002877 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002878 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002879 return;
2880 }
2881
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002882 if (mVisibleRegionsDirty || mInputInfoChanged) {
2883 mInputInfoChanged = false;
2884 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002885 } else if (mInputWindowCommands.syncInputWindows) {
2886 // If the caller requested to sync input windows, but there are no
2887 // changes to input windows, notify immediately.
2888 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002889 }
2890
2891 executeInputWindowCommands();
2892}
2893
2894void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002895 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002896
2897 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2898 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002899 // When calculating the screen bounds we ignore the transparent region since it may
2900 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002901 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002902 }
2903 });
chaviw291d88a2019-02-14 10:33:58 -08002904
2905 mInputFlinger->setInputWindows(inputHandles,
2906 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2907 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002908}
2909
Vishnu Nairec0ab382019-02-13 15:32:56 -08002910void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002911 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002912 mPendingInputWindowCommands.clear();
2913}
2914
chaviwfbe5d9c2018-12-26 12:23:37 -08002915void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002916 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2917 if (transferTouchFocusCommand.fromToken != nullptr &&
2918 transferTouchFocusCommand.toToken != nullptr &&
2919 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2920 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2921 transferTouchFocusCommand.toToken);
2922 }
2923 }
2924
2925 mInputWindowCommands.clear();
2926}
2927
Riley Andrews03414a12014-07-01 14:22:59 -07002928void SurfaceFlinger::updateCursorAsync()
2929{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002930 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002931 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002932 continue;
2933 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002935 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2936 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002937 }
2938 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002939}
2940
chaviw61626f22018-11-15 16:26:27 -08002941void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2942 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002943 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002944 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002945 }
2946 layer->releasePendingBuffer(systemTime());
2947}
2948
Mathias Agopian4fec8732012-06-29 14:12:52 -07002949void SurfaceFlinger::commitTransaction()
2950{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002951 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002952 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002953 for (const auto& l : mLayersPendingRemoval) {
2954 recordBufferingStats(l->getName().string(),
2955 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002956
Lloyd Pique07e33212018-12-18 16:33:37 -08002957 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002958 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002959 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002960 }
chaviw74d90ad2019-04-26 14:45:26 -07002961
2962 // If the layer has been removed and has no parent, then it will not be reachable
2963 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2964 // ensure we can copy its current to drawing state.
2965 if (!l->getParent()) {
2966 mOffscreenLayers.emplace(l.get());
2967 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002968 }
2969 mLayersPendingRemoval.clear();
2970 }
2971
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002972 // If this transaction is part of a window animation then the next frame
2973 // we composite should be considered an animation as well.
2974 mAnimCompositionPending = mAnimTransactionPending;
2975
Nataniel Borges2b796da2019-02-15 13:32:18 -08002976 withTracingLock([&]() {
2977 mDrawingState = mCurrentState;
2978 // clear the "changed" flags in current state
2979 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002980
chaviw74d90ad2019-04-26 14:45:26 -07002981 mDrawingState.traverseInZOrder([&](Layer* layer) {
2982 layer->commitChildList();
2983
2984 // If the layer can be reached when traversing mDrawingState, then the layer is no
2985 // longer offscreen. Remove the layer from the offscreenLayer set.
2986 if (mOffscreenLayers.count(layer)) {
2987 mOffscreenLayers.erase(layer);
2988 }
2989 });
2990
2991 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002992 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002993
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002994 mTransactionPending = false;
2995 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Nataniel Borges2b796da2019-02-15 13:32:18 -08002999void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3000 if (mTracingEnabledChanged) {
3001 mTracingEnabled = mTracing.isEnabled();
3002 mTracingEnabledChanged = false;
3003 }
3004
3005 // Synchronize with Tracing thread
3006 std::unique_lock<std::mutex> lock;
3007 if (mTracingEnabled) {
3008 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3009 }
3010
3011 lockedOperation();
3012
3013 // Synchronize with Tracing thread
3014 if (mTracingEnabled) {
3015 lock.unlock();
3016 }
3017}
3018
chaviw74d90ad2019-04-26 14:45:26 -07003019void SurfaceFlinger::commitOffscreenLayers() {
3020 for (Layer* offscreenLayer : mOffscreenLayers) {
3021 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3022 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3023 if (!trFlags) return;
3024
3025 layer->doTransaction(0);
3026 layer->commitChildList();
3027 });
3028 }
3029}
3030
Lloyd Pique32cbe282018-10-19 13:09:22 -07003031void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003032 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003033 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003035
Lloyd Pique32cbe282018-10-19 13:09:22 -07003036 auto display = displayDevice->getCompositionDisplay();
3037
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038 Region aboveOpaqueLayers;
3039 Region aboveCoveredLayers;
3040 Region dirty;
3041
Mathias Agopian87baae12012-07-31 12:38:26 -07003042 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043
Robert Carr2047fae2016-11-28 14:09:09 -08003044 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003045 // start with the whole surface at its current location
3046 const Layer::State& s(layer->getDrawingState());
3047
Jesse Hall01e29052013-02-19 16:13:35 -08003048 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003049 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003050 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003051 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003052
Mathias Agopianab028732010-03-16 16:41:46 -07003053 /*
3054 * opaqueRegion: area of a surface that is fully opaque.
3055 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003057
3058 /*
3059 * visibleRegion: area of a surface that is visible on screen
3060 * and not fully transparent. This is essentially the layer's
3061 * footprint minus the opaque regions above it.
3062 * Areas covered by a translucent surface are considered visible.
3063 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003065
3066 /*
3067 * coveredRegion: area of a surface that is covered by all
3068 * visible regions above it (which includes the translucent areas).
3069 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003071
Jesse Halla8026d22012-09-25 13:25:04 -07003072 /*
3073 * transparentRegion: area of a surface that is hinted to be completely
3074 * transparent. This is only used to tell when the layer has no visible
3075 * non-transparent regions and can be removed from the layer list. It
3076 * does not affect the visibleRegion of this layer or any layers
3077 * beneath it. The hint may not be correct if apps don't respect the
3078 * SurfaceView restrictions (which, sadly, some don't).
3079 */
3080 Region transparentRegion;
3081
Mathias Agopianab028732010-03-16 16:41:46 -07003082
3083 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003084 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003085 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003086 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003087
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003089 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003090 if (!visibleRegion.isEmpty()) {
3091 // Remove the transparent area from the visible region
3092 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003093 if (tr.preserveRects()) {
3094 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003095 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003096 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003097 // transformation too complex, can't do the
3098 // transparent region optimization.
3099 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003100 }
Mathias Agopianab028732010-03-16 16:41:46 -07003101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102
Mathias Agopianab028732010-03-16 16:41:46 -07003103 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003104 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003105 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003106 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003107 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003108 // the opaque region is the layer's footprint
3109 opaqueRegion = visibleRegion;
3110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 }
3112 }
3113
Robert Carre5f4f692018-01-12 13:12:28 -08003114 if (visibleRegion.isEmpty()) {
3115 layer->clearVisibilityRegions();
3116 return;
3117 }
3118
Mathias Agopianab028732010-03-16 16:41:46 -07003119 // Clip the covered region to the visible region
3120 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3121
3122 // Update aboveCoveredLayers for next (lower) layer
3123 aboveCoveredLayers.orSelf(visibleRegion);
3124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125 // subtract the opaque region covered by the layers above us
3126 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127
3128 // compute this layer's dirty region
3129 if (layer->contentDirty) {
3130 // we need to invalidate the whole region
3131 dirty = visibleRegion;
3132 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003133 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 layer->contentDirty = false;
3135 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003136 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003137 * the exposed region consists of two components:
3138 * 1) what's VISIBLE now and was COVERED before
3139 * 2) what's EXPOSED now less what was EXPOSED before
3140 *
3141 * note that (1) is conservative, we start with the whole
3142 * visible region but only keep what used to be covered by
3143 * something -- which mean it may have been exposed.
3144 *
3145 * (2) handles areas that were not covered by anything but got
3146 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003147 */
Mathias Agopianab028732010-03-16 16:41:46 -07003148 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003149 const Region oldVisibleRegion = layer->visibleRegion;
3150 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003151 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3152 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153 }
3154 dirty.subtractSelf(aboveOpaqueLayers);
3155
3156 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003157 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158
Mathias Agopianab028732010-03-16 16:41:46 -07003159 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003161
Jesse Halla8026d22012-09-25 13:25:04 -07003162 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 layer->setVisibleRegion(visibleRegion);
3164 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003165 layer->setVisibleNonTransparentRegion(
3166 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003167 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168
Mathias Agopian87baae12012-07-31 12:38:26 -07003169 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170}
3171
Chia-I Wuab0c3192017-08-01 11:29:00 -07003172void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003173 for (const auto& [token, displayDevice] : mDisplays) {
3174 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003175 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003176 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003177 }
3178 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003179}
3180
Dan Stoza6b9454d2014-11-07 16:00:59 -08003181bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182{
Ady Abraham09bd3922019-04-08 10:44:56 -07003183 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003184 ALOGV("handlePageFlip");
3185
Brian Andersond6927fb2016-07-23 23:37:30 -07003186 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187
Mathias Agopian4fec8732012-06-29 14:12:52 -07003188 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003189 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003190 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003191
3192 // Store the set of layers that need updates. This set must not change as
3193 // buffers are being latched, as this could result in a deadlock.
3194 // Example: Two producers share the same command stream and:
3195 // 1.) Layer 0 is latched
3196 // 2.) Layer 0 gets a new frame
3197 // 2.) Layer 1 gets a new frame
3198 // 3.) Layer 1 is latched.
3199 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3200 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003201 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003202 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003203 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003204 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003205 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003206 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003207 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003208 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003209 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003210 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003211 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003212 } else {
3213 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003214 }
Robert Carr2047fae2016-11-28 14:09:09 -08003215 });
3216
Lloyd Piquef2c79392018-12-20 16:23:33 -08003217 if (!mLayersWithQueuedFrames.empty()) {
3218 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3219 // writes to Layer current state. See also b/119481871
3220 Mutex::Autolock lock(mStateLock);
3221
3222 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003223 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003224 mLayersPendingRefresh.push_back(layer);
3225 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003226 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003227 if (layer->isBufferLatched()) {
3228 newDataLatched = true;
3229 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003230 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003231 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003232
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003233 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003234
3235 // If we will need to wake up at some time in the future to deal with a
3236 // queued frame that shouldn't be displayed during this vsync period, wake
3237 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003238 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003239 signalLayerUpdate();
3240 }
3241
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003242 // enter boot animation on first buffer latch
3243 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3244 ALOGI("Enter boot animation");
3245 mBootStage = BootStage::BOOTANIMATION;
3246 }
3247
Dan Stoza6b9454d2014-11-07 16:00:59 -08003248 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003249 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250}
3251
Mathias Agopianad456f92011-01-13 17:53:01 -08003252void SurfaceFlinger::invalidateHwcGeometry()
3253{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003254 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003255}
3256
Lloyd Pique32cbe282018-10-19 13:09:22 -07003257void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003258 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003259 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003260 // We only need to actually compose the display if:
3261 // 1) It is being handled by hardware composer, which may need this to
3262 // keep its virtual display state machine in sync, or
3263 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003264 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003265 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003266 return;
3267 }
3268
Dan Stoza9e56aa02015-11-02 13:00:03 -08003269 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003270 base::unique_fd readyFence;
3271 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003272
3273 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003274 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275}
3276
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003277bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3278 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003279 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003280 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003281
Lloyd Pique32cbe282018-10-19 13:09:22 -07003282 auto display = displayDevice->getCompositionDisplay();
3283 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003284 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003285 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003286 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003287
3288 const Region bounds(displayState.bounds);
3289 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003290 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003291 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003292
Chia-I Wu8e50e692018-05-04 10:12:37 -07003293 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003294
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003295 renderengine::DisplaySettings clientCompositionDisplay;
3296 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3297 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003298 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003299
Dan Stoza9e56aa02015-11-02 13:00:03 -08003300 if (hasClientComposition) {
3301 ALOGV("hasClientComposition");
3302
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003303 if (displayDevice->isPrimary() && supportProtectedContent) {
3304 bool needsProtected = false;
3305 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3306 // If the layer is a protected layer, mark protected context is needed.
3307 if (layer->isProtected()) {
3308 needsProtected = true;
3309 break;
3310 }
3311 }
Peiyong Lin52010312019-05-02 14:22:16 -07003312 if (needsProtected != renderEngine.isProtected()) {
3313 renderEngine.useProtectedContext(needsProtected);
3314 }
3315 if (needsProtected != display->getRenderSurface()->isProtected() &&
3316 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003317 display->getRenderSurface()->setProtected(needsProtected);
3318 }
3319 }
3320
Alec Mouri6338c9d2019-02-07 16:57:51 -08003321 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003322
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003323 if (buf == nullptr) {
3324 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3325 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003326 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003327 return false;
3328 }
3329
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003330 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3331 clientCompositionDisplay.clip = displayState.scissor;
3332 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003333 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003334 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003335
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003336 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003337 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003338 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003340 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003341 clientCompositionDisplay.outputDataspace = outputDataspace;
3342 clientCompositionDisplay.maxLuminance =
3343 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003344
Lloyd Pique441d5042018-10-18 16:49:51 -07003345 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003346 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003347 getHwComposer()
3348 .hasDisplayCapability(displayId,
3349 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003350
Peiyong Lind3788632018-09-18 16:01:31 -07003351 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003352 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3353 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003354 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003355 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003356 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003357
Mathias Agopian85d751c2012-08-29 16:59:24 -07003358 /*
3359 * and then, render the layers targeted at the framebuffer
3360 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003361
Dan Stoza9e56aa02015-11-02 13:00:03 -08003362 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003363 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003364 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003365 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003366 const Region viewportRegion(displayState.viewport);
3367 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003368 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003369 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003370 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003371 switch (layer->getCompositionType(displayDevice)) {
3372 case Hwc2::IComposerClient::Composition::CURSOR:
3373 case Hwc2::IComposerClient::Composition::DEVICE:
3374 case Hwc2::IComposerClient::Composition::SIDEBAND:
3375 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003376 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003377 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003378 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003379 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003380 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003381 // never clear the very first layer since we're
3382 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 renderengine::LayerSettings layerSettings;
3384 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003385 bool prepared =
3386 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3387 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003388
3389 if (prepared) {
3390 layerSettings.source.buffer.buffer = nullptr;
3391 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3392 layerSettings.alpha = half(0.0);
3393 layerSettings.disableBlending = true;
3394 clientCompositionLayers.push_back(layerSettings);
3395 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003396 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003397 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003398 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003399 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003400 renderengine::LayerSettings layerSettings;
3401 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003402 layer->prepareClientLayer(renderArea, clip, clearRegion,
3403 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 if (prepared) {
3405 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003406 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003407 break;
3408 }
3409 default:
3410 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003411 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003412 } else {
3413 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003414 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003416 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003417
Alec Mouri820c7402019-01-23 13:02:39 -08003418 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003419 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003420 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003421
3422 // We boost GPU frequency here because there will be color spaces conversion
3423 // and it's expensive. We boost the GPU frequency so that GPU composition can
3424 // finish in time. We must reset GPU frequency afterwards, because high frequency
3425 // consumes extra battery.
3426 const bool expensiveRenderingExpected =
3427 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3428 if (expensiveRenderingExpected && displayId) {
3429 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3430 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003431 if (!debugRegion.isEmpty()) {
3432 Region::const_iterator it = debugRegion.begin();
3433 Region::const_iterator end = debugRegion.end();
3434 while (it != end) {
3435 const Rect& rect = *it++;
3436 renderengine::LayerSettings layerSettings;
3437 layerSettings.source.buffer.buffer = nullptr;
3438 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3439 layerSettings.geometry.boundaries = rect.toFloatRect();
3440 layerSettings.alpha = half(1.0);
3441 clientCompositionLayers.push_back(layerSettings);
3442 }
3443 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003444 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003445 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3446 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003447 } else if (displayId) {
3448 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003449 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003450 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003451}
3452
Chia-I Wu28e3a252018-09-07 12:05:02 -07003453void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003454 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003455 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456}
3457
Robert Carrc0df3122019-04-11 13:18:21 -07003458status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3459 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3460 const sp<IBinder>& parentHandle,
3461 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003462 // add this layer to the current state list
3463 {
3464 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003465 sp<Layer> parent;
3466 if (parentHandle != nullptr) {
3467 parent = fromHandle(parentHandle);
3468 if (parent == nullptr) {
3469 return NAME_NOT_FOUND;
3470 }
3471 } else {
3472 parent = parentLayer;
3473 }
3474
Robert Carr1f0a16a2016-10-24 16:27:39 -07003475 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003476 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3477 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003478 return NO_MEMORY;
3479 }
Robert Carrc0df3122019-04-11 13:18:21 -07003480
3481 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3482
Robert Carrb89ea9d2018-12-10 13:01:14 -08003483 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003484 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003485 } else if (parent == nullptr) {
3486 lbc->onRemovedFromCurrentState();
3487 } else if (parent->isRemovedFromCurrentState()) {
3488 parent->addChild(lbc);
3489 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003490 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003491 parent->addChild(lbc);
3492 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003493
Yiwei Zhang243b3782018-05-15 17:40:04 -07003494 if (gbc != nullptr) {
3495 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3496 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3497 mMaxGraphicBufferProducerListSize,
3498 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3499 mGraphicBufferProducerList.size(),
3500 mMaxGraphicBufferProducerListSize, mNumLayers);
3501 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003502 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003503 }
3504
Mathias Agopian96f08192010-06-02 23:28:45 -07003505 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003506 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003507
Dan Stoza7d89d062015-04-30 13:29:25 -07003508 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003509}
3510
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003511uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003512 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003513}
3514
Mathias Agopian3f844832013-08-07 21:24:32 -07003515uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003516 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517}
3518
Mathias Agopian3f844832013-08-07 21:24:32 -07003519uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003520 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003521}
3522
3523uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003524 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003525 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003526 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003528 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003529 }
3530 return old;
3531}
3532
Marissa Wall713b63f2018-10-17 15:42:43 -07003533bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003534 // to prevent onHandleDestroyed from being called while the lock is held,
3535 // we must keep a copy of the transactions (specifically the composer
3536 // states) around outside the scope of the lock
3537 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003538 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003539 {
3540 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003541
Valerie Haufce31b82019-04-30 16:41:14 -07003542 auto it = mTransactionQueues.begin();
3543 while (it != mTransactionQueues.end()) {
3544 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003545
Valerie Haufce31b82019-04-30 16:41:14 -07003546 while (!transactionQueue.empty()) {
3547 const auto& transaction = transactionQueue.front();
3548 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3549 transaction.states)) {
3550 setTransactionFlags(eTransactionFlushNeeded);
3551 break;
3552 }
3553 transactions.push_back(transaction);
3554 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3555 mPendingInputWindowCommands, transaction.desiredPresentTime,
3556 transaction.buffer, transaction.callback,
3557 transaction.postTime, transaction.privileged,
3558 /*isMainThread*/ true);
3559 transactionQueue.pop();
3560 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003561 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003562
Valerie Haufce31b82019-04-30 16:41:14 -07003563 if (transactionQueue.empty()) {
3564 it = mTransactionQueues.erase(it);
3565 mTransactionCV.broadcast();
3566 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003567 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003568 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003569 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003570 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003571 return flushedATransaction;
3572}
3573
3574bool SurfaceFlinger::transactionFlushNeeded() {
3575 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003576}
3577
chaviwca27f252018-02-06 16:46:39 -08003578bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3579 for (const ComposerState& state : states) {
3580 // Here we need to check that the interface we're given is indeed
3581 // one of our own. A malicious client could give us a nullptr
3582 // IInterface, or one of its own or even one of our own but a
3583 // different type. All these situations would cause us to crash.
3584 if (state.client == nullptr) {
3585 return true;
3586 }
3587
3588 sp<IBinder> binder = IInterface::asBinder(state.client);
3589 if (binder == nullptr) {
3590 return true;
3591 }
3592
3593 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3594 return true;
3595 }
3596 }
3597 return false;
3598}
3599
Marissa Wall17b4e452018-12-26 16:32:34 -08003600bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3601 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003602 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003603 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3604 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3605 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3606 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3607 return false;
3608 }
3609
Marissa Wall713b63f2018-10-17 15:42:43 -07003610 for (const ComposerState& state : states) {
3611 const layer_state_t& s = state.state;
3612 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3613 continue;
3614 }
3615 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003616 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003617 }
3618 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003619 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003620}
3621
3622void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3623 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003624 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003625 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003626 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003627 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003628 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003629 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003630
Valerie Haubc6ddb12019-03-08 11:10:15 -08003631 const int64_t postTime = systemTime();
3632
Robert Carr14167e02019-02-13 13:50:55 -08003633 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3634
Mathias Agopian698c0872011-06-28 19:09:31 -07003635 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003636
chaviwca27f252018-02-06 16:46:39 -08003637 if (containsAnyInvalidClientState(states)) {
3638 return;
3639 }
3640
Marissa Wall713b63f2018-10-17 15:42:43 -07003641 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003642 auto itr = mTransactionQueues.find(applyToken);
3643 // if this is an animation frame, wait until prior animation frame has
3644 // been applied by SF
3645 if (flags & eAnimation) {
3646 while (itr != mTransactionQueues.end()) {
3647 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3648 if (CC_UNLIKELY(err != NO_ERROR)) {
3649 ALOGW_IF(err == TIMED_OUT,
3650 "setTransactionState timed out "
3651 "waiting for animation frame to apply");
3652 break;
3653 }
3654 itr = mTransactionQueues.find(applyToken);
3655 }
3656 }
3657 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003658 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003659 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003660 uncacheBuffer, listenerCallbacks, postTime,
3661 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003662 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003663 return;
3664 }
3665
Valerie Haubc6ddb12019-03-08 11:10:15 -08003666 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003667 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003668}
3669
3670void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003671 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003672 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003673 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003674 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003675 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003676 const int64_t postTime, bool privileged,
3677 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003678 uint32_t transactionFlags = 0;
3679
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003680 if (flags & eAnimation) {
3681 // For window updates that are part of an animation we must wait for
3682 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003683 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003684 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003685 if (CC_UNLIKELY(err != NO_ERROR)) {
3686 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003687 // caller after a few seconds.
3688 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3689 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003690 mAnimTransactionPending = false;
3691 break;
3692 }
3693 }
3694 }
3695
chaviwca27f252018-02-06 16:46:39 -08003696 for (const DisplayState& display : displays) {
3697 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003698 }
3699
Marissa Walld600d572019-03-26 15:38:50 -07003700 // In case the client has sent a Transaction that should receive callbacks but without any
3701 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3702 // to the callback thread so it can send an empty callback
3703 if (!listenerCallbacks.empty()) {
3704 mTransactionCompletedThread.run();
3705 }
3706 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3707 mTransactionCompletedThread.addCallback(listener, callbackIds);
3708 }
3709
Marissa Walle2ffb422018-10-12 11:33:52 -07003710 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003711 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003712 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3713 postTime, privileged);
3714 }
3715
Marissa Walle2ffb422018-10-12 11:33:52 -07003716 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003717 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003718 mTransactionCompletedThread.sendCallbacks();
3719 }
3720 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003721
chaviw273171b2018-12-26 11:46:30 -08003722 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3723
Marissa Wall947d34e2019-03-29 14:03:53 -07003724 if (uncacheBuffer.isValid()) {
3725 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003726 }
3727
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003728 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3729 // anyway. This can be used as a flush mechanism for previous async transactions.
3730 // Empty animation transaction can be used to simulate back-pressure, so also force a
3731 // transaction for empty animation transactions.
3732 if (transactionFlags == 0 &&
3733 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003734 transactionFlags = eTransactionNeeded;
3735 }
3736
Marissa Wall06255332019-03-27 13:48:27 -07003737 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3738 // so we don't have to wake up again next frame to preform an uneeded traversal.
3739 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3740 transactionFlags = transactionFlags & (~eTraversalNeeded);
3741 mTraversalNeededMainThread = true;
3742 }
3743
Mathias Agopian386aa982011-11-07 21:58:03 -08003744 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003745 if (mInterceptor->isEnabled()) {
3746 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003747 }
Irvel468051e2016-06-13 16:44:44 -07003748
Mathias Agopian386aa982011-11-07 21:58:03 -08003749 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003750 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3751 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003752 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003753
3754 // if this is a synchronous transaction, wait for it to take effect
3755 // before returning.
3756 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003757 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003758 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003759 if (flags & eAnimation) {
3760 mAnimTransactionPending = true;
3761 }
chaviw4fe36852019-04-15 16:25:49 -07003762 if (mPendingInputWindowCommands.syncInputWindows) {
3763 mPendingSyncInputWindows = true;
3764 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003765
3766 // applyTransactionState can be called by either the main SF thread or by
3767 // another process through setTransactionState. While a given process may wish
3768 // to wait on synchronous transactions, the main SF thread should never
3769 // be blocked. Therefore, we only wait if isMainThread is false.
3770 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003771 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3772 if (CC_UNLIKELY(err != NO_ERROR)) {
3773 // just in case something goes wrong in SF, return to the
3774 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003775 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3776 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003777 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003778 break;
3779 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003780 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781 }
3782}
3783
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003784uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3785 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3786 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003787
Mathias Agopiane57f2922012-08-09 16:29:12 -07003788 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003789 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3790
3791 const uint32_t what = s.what;
3792 if (what & DisplayState::eSurfaceChanged) {
3793 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3794 state.surface = s.surface;
3795 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003796 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003797 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003798 if (what & DisplayState::eLayerStackChanged) {
3799 if (state.layerStack != s.layerStack) {
3800 state.layerStack = s.layerStack;
3801 flags |= eDisplayTransactionNeeded;
3802 }
3803 }
3804 if (what & DisplayState::eDisplayProjectionChanged) {
3805 if (state.orientation != s.orientation) {
3806 state.orientation = s.orientation;
3807 flags |= eDisplayTransactionNeeded;
3808 }
3809 if (state.frame != s.frame) {
3810 state.frame = s.frame;
3811 flags |= eDisplayTransactionNeeded;
3812 }
3813 if (state.viewport != s.viewport) {
3814 state.viewport = s.viewport;
3815 flags |= eDisplayTransactionNeeded;
3816 }
3817 }
3818 if (what & DisplayState::eDisplaySizeChanged) {
3819 if (state.width != s.width) {
3820 state.width = s.width;
3821 flags |= eDisplayTransactionNeeded;
3822 }
3823 if (state.height != s.height) {
3824 state.height = s.height;
3825 flags |= eDisplayTransactionNeeded;
3826 }
3827 }
3828
Mathias Agopiane57f2922012-08-09 16:29:12 -07003829 return flags;
3830}
3831
Robert Carr14167e02019-02-13 13:50:55 -08003832bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003833 IPCThreadState* ipc = IPCThreadState::self();
3834 const int pid = ipc->getCallingPid();
3835 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003836 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003837 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003838 return false;
3839 }
3840 return true;
3841}
3842
Marissa Wall3dad52d2019-03-22 14:03:19 -07003843uint32_t SurfaceFlinger::setClientStateLocked(
3844 const ComposerState& composerState, int64_t desiredPresentTime,
3845 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3846 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003847 const layer_state_t& s = composerState.state;
3848 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3849
Mathias Agopian13127d82013-03-05 17:47:11 -08003850 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003851 if (layer == nullptr) {
3852 return 0;
3853 }
3854
chaviw8b3871a2017-11-01 17:41:01 -07003855 uint32_t flags = 0;
3856
Garfield Tan8a3083e2018-12-03 13:21:07 -08003857 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003858 bool geometryAppliesWithResize =
3859 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003860
3861 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3862 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003863 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003864 layer->pushPendingState();
3865 }
3866
chaviw8b3871a2017-11-01 17:41:01 -07003867 if (what & layer_state_t::ePositionChanged) {
3868 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3869 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003870 }
chaviw8b3871a2017-11-01 17:41:01 -07003871 }
3872 if (what & layer_state_t::eLayerChanged) {
3873 // NOTE: index needs to be calculated before we update the state
3874 const auto& p = layer->getParent();
3875 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003876 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003877 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003878 mCurrentState.layersSortedByZ.removeAt(idx);
3879 mCurrentState.layersSortedByZ.add(layer);
3880 // we need traversal (state changed)
3881 // AND transaction (list changed)
3882 flags |= eTransactionNeeded|eTraversalNeeded;
3883 }
chaviw8b3871a2017-11-01 17:41:01 -07003884 } else {
3885 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003886 flags |= eTransactionNeeded|eTraversalNeeded;
3887 }
3888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 }
3890 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003891 // NOTE: index needs to be calculated before we update the state
3892 const auto& p = layer->getParent();
3893 if (p == nullptr) {
3894 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3895 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3896 mCurrentState.layersSortedByZ.removeAt(idx);
3897 mCurrentState.layersSortedByZ.add(layer);
3898 // we need traversal (state changed)
3899 // AND transaction (list changed)
3900 flags |= eTransactionNeeded|eTraversalNeeded;
3901 }
3902 } else {
3903 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3904 flags |= eTransactionNeeded|eTraversalNeeded;
3905 }
chaviw8b3871a2017-11-01 17:41:01 -07003906 }
3907 }
3908 if (what & layer_state_t::eSizeChanged) {
3909 if (layer->setSize(s.w, s.h)) {
3910 flags |= eTraversalNeeded;
3911 }
3912 }
3913 if (what & layer_state_t::eAlphaChanged) {
3914 if (layer->setAlpha(s.alpha))
3915 flags |= eTraversalNeeded;
3916 }
3917 if (what & layer_state_t::eColorChanged) {
3918 if (layer->setColor(s.color))
3919 flags |= eTraversalNeeded;
3920 }
Peiyong Lind3788632018-09-18 16:01:31 -07003921 if (what & layer_state_t::eColorTransformChanged) {
3922 if (layer->setColorTransform(s.colorTransform)) {
3923 flags |= eTraversalNeeded;
3924 }
3925 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003926 if (what & layer_state_t::eBackgroundColorChanged) {
3927 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3928 flags |= eTraversalNeeded;
3929 }
3930 }
chaviw8b3871a2017-11-01 17:41:01 -07003931 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003932 // TODO: b/109894387
3933 //
3934 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3935 // rotation. To see the problem observe that if we have a square parent, and a child
3936 // of the same size, then we rotate the child 45 degrees around it's center, the child
3937 // must now be cropped to a non rectangular 8 sided region.
3938 //
3939 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3940 // private API, and the WindowManager only uses rotation in one case, which is on a top
3941 // level layer in which cropping is not an issue.
3942 //
3943 // However given that abuse of rotation matrices could lead to surfaces extending outside
3944 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3945 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3946 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003947 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003948 flags |= eTraversalNeeded;
3949 }
3950 if (what & layer_state_t::eTransparentRegionChanged) {
3951 if (layer->setTransparentRegionHint(s.transparentRegion))
3952 flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eFlagsChanged) {
3955 if (layer->setFlags(s.flags, s.mask))
3956 flags |= eTraversalNeeded;
3957 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003958 if (what & layer_state_t::eCropChanged_legacy) {
3959 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003960 flags |= eTraversalNeeded;
3961 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003962 if (what & layer_state_t::eCornerRadiusChanged) {
3963 if (layer->setCornerRadius(s.cornerRadius))
3964 flags |= eTraversalNeeded;
3965 }
chaviw8b3871a2017-11-01 17:41:01 -07003966 if (what & layer_state_t::eLayerStackChanged) {
3967 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3968 // We only allow setting layer stacks for top level layers,
3969 // everything else inherits layer stack from its parent.
3970 if (layer->hasParent()) {
3971 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3972 layer->getName().string());
3973 } else if (idx < 0) {
3974 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3975 "that also does not appear in the top level layer list. Something"
3976 " has gone wrong.", layer->getName().string());
3977 } else if (layer->setLayerStack(s.layerStack)) {
3978 mCurrentState.layersSortedByZ.removeAt(idx);
3979 mCurrentState.layersSortedByZ.add(layer);
3980 // we need traversal (state changed)
3981 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003982 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003983 }
3984 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003985 if (what & layer_state_t::eDeferTransaction_legacy) {
3986 if (s.barrierHandle_legacy != nullptr) {
3987 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3988 } else if (s.barrierGbp_legacy != nullptr) {
3989 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003990 if (authenticateSurfaceTextureLocked(gbp)) {
3991 const auto& otherLayer =
3992 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003993 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003994 } else {
3995 ALOGE("Attempt to defer transaction to to an"
3996 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003997 }
3998 }
chaviw8b3871a2017-11-01 17:41:01 -07003999 // We don't trigger a traversal here because if no other state is
4000 // changed, we don't want this to cause any more work
4001 }
4002 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004003 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004004 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004005 if (!hadParent) {
4006 mCurrentState.layersSortedByZ.remove(layer);
4007 }
chaviw8b3871a2017-11-01 17:41:01 -07004008 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004009 }
chaviw8b3871a2017-11-01 17:41:01 -07004010 }
4011 if (what & layer_state_t::eReparentChildren) {
4012 if (layer->reparentChildren(s.reparentHandle)) {
4013 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004014 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004015 }
chaviw8b3871a2017-11-01 17:41:01 -07004016 if (what & layer_state_t::eDetachChildren) {
4017 layer->detachChildren();
4018 }
4019 if (what & layer_state_t::eOverrideScalingModeChanged) {
4020 layer->setOverrideScalingMode(s.overrideScalingMode);
4021 // We don't trigger a traversal here because if no other state is
4022 // changed, we don't want this to cause any more work
4023 }
Marissa Wall61c58622018-07-18 10:12:20 -07004024 if (what & layer_state_t::eTransformChanged) {
4025 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4026 }
4027 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4028 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4029 flags |= eTraversalNeeded;
4030 }
4031 if (what & layer_state_t::eCropChanged) {
4032 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4033 }
Marissa Wall861616d2018-10-22 12:52:23 -07004034 if (what & layer_state_t::eFrameChanged) {
4035 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4036 }
Marissa Wall61c58622018-07-18 10:12:20 -07004037 if (what & layer_state_t::eAcquireFenceChanged) {
4038 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4039 }
4040 if (what & layer_state_t::eDataspaceChanged) {
4041 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4042 }
4043 if (what & layer_state_t::eHdrMetadataChanged) {
4044 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4045 }
4046 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4047 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4048 }
4049 if (what & layer_state_t::eApiChanged) {
4050 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4051 }
4052 if (what & layer_state_t::eSidebandStreamChanged) {
4053 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4054 }
Robert Carr720e5062018-07-30 17:45:14 -07004055 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004056 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004057 layer->setInputInfo(s.inputInfo);
4058 flags |= eTraversalNeeded;
4059 } else {
4060 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4061 }
Robert Carr720e5062018-07-30 17:45:14 -07004062 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004063 if (what & layer_state_t::eMetadataChanged) {
4064 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4065 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004066 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4067 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4068 flags |= eTraversalNeeded;
4069 }
4070 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004071 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004072 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004073 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004074 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4075 }
4076 }
Marissa Wall78b72202019-03-15 14:58:34 -07004077 bool bufferChanged = what & layer_state_t::eBufferChanged;
4078 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4079 sp<GraphicBuffer> buffer;
4080 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004081 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004082 buffer = s.buffer;
4083 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004084 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004085 } else if (bufferChanged) {
4086 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004087 }
Marissa Wall78b72202019-03-15 14:58:34 -07004088 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004089 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004090 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004091 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004092 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004093 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4094 // Do not put anything that updates layer state or modifies flags after
4095 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004096 return flags;
4097}
4098
chaviw273171b2018-12-26 11:46:30 -08004099uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4100 uint32_t flags = 0;
4101 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4102 flags |= eTraversalNeeded;
4103 }
4104
chaviwa911b102019-02-14 10:18:33 -08004105 if (inputWindowCommands.syncInputWindows) {
4106 flags |= eTraversalNeeded;
4107 }
4108
Vishnu Nairec0ab382019-02-13 15:32:56 -08004109 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004110 return flags;
4111}
4112
Marissa Wall2d814fb2019-04-09 18:52:57 +00004113status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4114 uint32_t h, PixelFormat format, uint32_t flags,
4115 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004116 sp<IGraphicBufferProducer>* gbp,
4117 const sp<IBinder>& parentHandle,
4118 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004119 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004120 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004121 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004122 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004123 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004124
Robert Carrc0df3122019-04-11 13:18:21 -07004125 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4126 "Expected only one of parentLayer or parentHandle to be non-null. "
4127 "Programmer error?");
4128
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129 status_t result = NO_ERROR;
4130
4131 sp<Layer> layer;
4132
Cody Northropbc755282017-03-31 12:00:08 -06004133 String8 uniqueName = getUniqueLayerName(name);
4134
Evan Roskya1f1e152019-01-24 16:17:46 -08004135 bool primaryDisplayOnly = false;
4136
4137 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4138 // TODO b/64227542
4139 if (metadata.has(METADATA_WINDOW_TYPE)) {
4140 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4141 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004142 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004143 primaryDisplayOnly = true;
4144 }
4145 }
4146
Mathias Agopian3165cc22012-08-08 19:42:09 -07004147 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004148 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004149 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4150 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004151
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004153 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004154 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4155 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004156 break;
chaviw13fdc492017-06-27 12:40:18 -07004157 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004158 // check if buffer size is set for color layer.
4159 if (w > 0 || h > 0) {
4160 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4161 int(w), int(h));
4162 return BAD_VALUE;
4163 }
4164
Evan Roskya1f1e152019-01-24 16:17:46 -08004165 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4166 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004167 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004168 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004169 // check if buffer size is set for container layer.
4170 if (w > 0 || h > 0) {
4171 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4172 int(w), int(h));
4173 return BAD_VALUE;
4174 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004175 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4176 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004177 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004178 default:
4179 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004180 break;
4181 }
4182
Dan Stoza7d89d062015-04-30 13:29:25 -07004183 if (result != NO_ERROR) {
4184 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004185 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004186
Evan Roskya1f1e152019-01-24 16:17:46 -08004187 if (primaryDisplayOnly) {
4188 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004189 }
4190
Robert Carrb89ea9d2018-12-10 13:01:14 -08004191 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004192 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4193 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004194 if (result != NO_ERROR) {
4195 return result;
4196 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004197 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004198
4199 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004200 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004201}
4202
Cody Northropbc755282017-03-31 12:00:08 -06004203String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4204{
4205 bool matchFound = true;
4206 uint32_t dupeCounter = 0;
4207
4208 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4209 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4210
Dan Stoza436ccf32018-06-21 12:10:12 -07004211 // Grab the state lock since we're accessing mCurrentState
4212 Mutex::Autolock lock(mStateLock);
4213
Cody Northropbc755282017-03-31 12:00:08 -06004214 // Loop over layers until we're sure there is no matching name
4215 while (matchFound) {
4216 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004217 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004218 if (layer->getName() == uniqueName) {
4219 matchFound = true;
4220 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4221 }
4222 });
4223 }
4224
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004225 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4226 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004227
4228 return uniqueName;
4229}
4230
Marissa Wallfd668622018-05-10 10:21:13 -07004231status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4232 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004233 LayerMetadata metadata, PixelFormat& format,
4234 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004235 sp<IGraphicBufferProducer>* gbp,
4236 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004237 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004238 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004239 case PIXEL_FORMAT_TRANSPARENT:
4240 case PIXEL_FORMAT_TRANSLUCENT:
4241 format = PIXEL_FORMAT_RGBA_8888;
4242 break;
4243 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004244 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004245 break;
4246 }
4247
Evan Roskya1f1e152019-01-24 16:17:46 -08004248 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4249 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004250 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004251 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004252 *handle = layer->getHandle();
4253 *gbp = layer->getProducer();
4254 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004255 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004256
Marissa Wallfd668622018-05-10 10:21:13 -07004257 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004258 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004259}
4260
Marissa Wall61c58622018-07-18 10:12:20 -07004261status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4262 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004263 LayerMetadata metadata, sp<IBinder>* handle,
4264 sp<Layer>* outLayer) {
4265 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4266 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004267 *handle = layer->getHandle();
4268 *outLayer = layer;
4269
4270 return NO_ERROR;
4271}
4272
Evan Roskya1f1e152019-01-24 16:17:46 -08004273status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4274 uint32_t h, uint32_t flags, LayerMetadata metadata,
4275 sp<IBinder>* handle, sp<Layer>* outLayer) {
4276 *outLayer = getFactory().createColorLayer(
4277 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004278 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004279 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004280}
4281
Evan Roskya1f1e152019-01-24 16:17:46 -08004282status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4283 uint32_t w, uint32_t h, uint32_t flags,
4284 LayerMetadata metadata, sp<IBinder>* handle,
4285 sp<Layer>* outLayer) {
4286 *outLayer = getFactory().createContainerLayer(
4287 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004288 *handle = (*outLayer)->getHandle();
4289 return NO_ERROR;
4290}
4291
4292
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004293void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004294 mLayersPendingRemoval.add(layer);
4295 mLayersRemoved = true;
4296 setTransactionFlags(eTransactionNeeded);
4297}
4298
Robert Carr695d5282018-12-18 15:27:58 -08004299void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004300{
Robert Carr2e102c92018-10-23 12:11:15 -07004301 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004302 // If a layer has a parent, we allow it to out-live it's handle
4303 // with the idea that the parent holds a reference and will eventually
4304 // be cleaned up. However no one cleans up the top-level so we do so
4305 // here.
4306 if (layer->getParent() == nullptr) {
4307 mCurrentState.layersSortedByZ.remove(layer);
4308 }
4309 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004310
4311 auto it = mLayersByLocalBinderToken.begin();
4312 while (it != mLayersByLocalBinderToken.end()) {
4313 if (it->second == layer) {
4314 it = mLayersByLocalBinderToken.erase(it);
4315 } else {
4316 it++;
4317 }
4318 }
4319
Robert Carr695d5282018-12-18 15:27:58 -08004320 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004321}
4322
Mathias Agopianb60314a2012-04-10 22:09:54 -07004323// ---------------------------------------------------------------------------
4324
Andy McFadden13a082e2012-08-24 10:16:42 -07004325void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004326 const auto display = getDefaultDisplayDeviceLocked();
4327 if (!display) return;
4328
4329 const sp<IBinder> token = display->getDisplayToken().promote();
4330 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004331
Jesse Hall01e29052013-02-19 16:13:35 -08004332 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004333 Vector<ComposerState> state;
4334 Vector<DisplayState> displays;
4335 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004336 d.what = DisplayState::eDisplayProjectionChanged |
4337 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004338 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004339 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004340 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004341 d.frame.makeInvalid();
4342 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004343 d.width = 0;
4344 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004345 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004346 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004347
Dominik Laskowskie9774092018-12-11 10:04:24 -08004348 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004349
Dominik Laskowski83b88212018-12-11 13:34:06 -08004350 const nsecs_t vsyncPeriod = getVsyncPeriod();
4351 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004352
Brian Andersond0010582017-03-07 13:20:31 -08004353 // Use phase of 0 since phase is not known.
4354 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004355 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004356 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004357}
4358
4359void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004360 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004361 postMessageAsync(
4362 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004363}
4364
Dominik Laskowskie9774092018-12-11 10:04:24 -08004365void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004366 if (display->isVirtual()) {
4367 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004368 return;
4369 }
4370
Dominik Laskowski075d3172018-05-24 15:50:06 -07004371 const auto displayId = display->getId();
4372 LOG_ALWAYS_FATAL_IF(!displayId);
4373
Dominik Laskowski34157762018-10-31 13:07:19 -07004374 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004375
4376 int currentMode = display->getPowerMode();
4377 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004378 return;
4379 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004380
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004381 display->setPowerMode(mode);
4382
Lloyd Pique4dccc412018-01-22 17:21:36 -08004383 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004384 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004385 }
4386
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004387 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004388 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004389 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004390 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004391 mScheduler->onScreenAcquired(mAppConnectionHandle);
4392 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004393 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004394
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004395 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004396 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004397 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004398
4399 struct sched_param param = {0};
4400 param.sched_priority = 1;
4401 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4402 ALOGW("Couldn't set SCHED_FIFO on display on");
4403 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004404 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004405 // Turn off the display
4406 struct sched_param param = {0};
4407 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4408 ALOGW("Couldn't set SCHED_OTHER on display off");
4409 }
4410
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004411 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004412 mScheduler->disableHardwareVsync(true);
4413 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004414 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004415
Dominik Laskowski075d3172018-05-24 15:50:06 -07004416 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004417 mVisibleRegionsDirty = true;
4418 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004419 } else if (mode == HWC_POWER_MODE_DOZE ||
4420 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004421 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004422 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004423 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004424 mScheduler->onScreenAcquired(mAppConnectionHandle);
4425 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004426 }
4427 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4428 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004429 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004430 mScheduler->disableHardwareVsync(true);
4431 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004432 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004433 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004434 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004435 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004436 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004437 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004438
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004439 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004440 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004441 mRefreshRateStats.setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004442 }
4443
Dominik Laskowski34157762018-10-31 13:07:19 -07004444 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004445}
4446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004447void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004448 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004449 const auto display = getDisplayDevice(displayToken);
4450 if (!display) {
4451 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4452 displayToken.get());
4453 } else if (display->isVirtual()) {
4454 ALOGW("Attempt to set power mode %d for virtual display", mode);
4455 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004456 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004457 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004458 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004459}
4460
4461// ---------------------------------------------------------------------------
4462
Dominik Laskowskic2867142019-01-21 11:33:38 -08004463status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4464 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004466
Mathias Agopianbd115332013-04-18 16:41:04 -07004467 IPCThreadState* ipc = IPCThreadState::self();
4468 const int pid = ipc->getCallingPid();
4469 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004470
Mathias Agopianbd115332013-04-18 16:41:04 -07004471 if ((uid != AID_SHELL) &&
4472 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4474 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004475 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004476 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004477 // (this would indicate SF is stuck, but we want to be able to
4478 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004479 status_t err = mStateLock.timedLock(s2ns(1));
4480 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004481 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result,
4483 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4484 "(no locks held)\n",
4485 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004486 }
4487
Dominik Laskowskic2867142019-01-21 11:33:38 -08004488 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004489
Dominik Laskowskic2867142019-01-21 11:33:38 -08004490 static const std::unordered_map<std::string, Dumper> dumpers = {
4491 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4492 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4493 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004494 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004495 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004496 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004497 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4498 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004499 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4500 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4501 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4502 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4503 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4504 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004505 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004506 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4507 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004508
Dominik Laskowskic2867142019-01-21 11:33:38 -08004509 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004510
Dominik Laskowskic2867142019-01-21 11:33:38 -08004511 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4512 (it->second)(args, asProto, result);
4513 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004514 if (asProto) {
4515 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4516 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4517 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004518 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004519 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004520 }
4521
Mathias Agopian9795c422009-08-26 16:36:26 -07004522 if (locked) {
4523 mStateLock.unlock();
4524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 return NO_ERROR;
4528}
4529
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004530status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4531 if (asProto && mTracing.isEnabled()) {
4532 mTracing.writeToFileAsync();
4533 }
4534
4535 return doDump(fd, DumpArgs(), asProto);
4536}
4537
Dominik Laskowskic2867142019-01-21 11:33:38 -08004538void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 mCurrentState.traverseInZOrder(
4540 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004541}
4542
Dominik Laskowskic2867142019-01-21 11:33:38 -08004543void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004544 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004545
Dominik Laskowskic2867142019-01-21 11:33:38 -08004546 if (args.size() > 1) {
4547 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004548 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004549 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004550 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004551 }
Robert Carr2047fae2016-11-28 14:09:09 -08004552 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004553 } else {
4554 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004555 }
4556}
4557
Dominik Laskowskic2867142019-01-21 11:33:38 -08004558void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004559 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004560 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004561 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004562 }
Robert Carr2047fae2016-11-28 14:09:09 -08004563 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004564
Svetoslavd85084b2014-03-20 10:28:31 -07004565 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004566}
4567
Dominik Laskowskic2867142019-01-21 11:33:38 -08004568void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4569 mTimeStats->parseArgs(asProto, args, result);
4570}
4571
Jamie Gennis6547ff42013-07-16 20:12:42 -07004572// This should only be called from the main thread. Otherwise it would need
4573// the lock and should use mCurrentState rather than mDrawingState.
4574void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004575 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004576 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004577 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004578
4579 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4580}
4581
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004583 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004584
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004585 if (isLayerTripleBufferingDisabled())
4586 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004587
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4589 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4590 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4591 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4592 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4593 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004594 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004595}
4596
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004597void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004598 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004599 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004600 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004601 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004602
Ady Abraham97d04232019-03-05 19:48:12 -08004603 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004604 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4605 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004606 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004607}
4608
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4610 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004611 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4612 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004613 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004614 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004616 }
David Sodman4a36e932017-11-07 14:29:47 -08004617 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004618 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004619 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4621 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004622}
4623
Dan Stozae77c7662016-05-13 11:37:28 -07004624void SurfaceFlinger::recordBufferingStats(const char* layerName,
4625 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004626 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4627 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004628 for (const auto& segment : history) {
4629 if (!segment.usedThirdBuffer) {
4630 stats.twoBufferTime += segment.totalTime;
4631 }
4632 if (segment.occupancyAverage < 1.0f) {
4633 stats.doubleBufferedTime += segment.totalTime;
4634 } else if (segment.occupancyAverage < 2.0f) {
4635 stats.tripleBufferedTime += segment.totalTime;
4636 }
4637 ++stats.numSegments;
4638 stats.totalTime += segment.totalTime;
4639 }
4640}
4641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4643 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004644
4645 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4646 const size_t count = currentLayers.size();
4647 for (size_t i=0 ; i<count ; i++) {
4648 currentLayers[i]->dumpFrameEvents(result);
4649 }
4650}
4651
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004653 result.append("Buffering stats:\n");
4654 result.append(" [Layer name] <Active time> <Two buffer> "
4655 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004656 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004657 typedef std::tuple<std::string, float, float, float> BufferTuple;
4658 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004659 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004660 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004661 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004662 if (stats.numSegments == 0) {
4663 continue;
4664 }
4665 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4666 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4667 stats.totalTime;
4668 float doubleBufferRatio = static_cast<float>(
4669 stats.doubleBufferedTime) / stats.totalTime;
4670 float tripleBufferRatio = static_cast<float>(
4671 stats.tripleBufferedTime) / stats.totalTime;
4672 sorted.insert({activeTime, {name, twoBufferRatio,
4673 doubleBufferRatio, tripleBufferRatio}});
4674 }
4675 for (const auto& sortedPair : sorted) {
4676 float activeTime = sortedPair.first;
4677 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4679 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004680 }
4681 result.append("\n");
4682}
4683
Yiwei Zhang5434a782018-12-05 18:06:32 -08004684void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004685 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004686 const auto displayId = display->getId();
4687 if (!displayId) {
4688 continue;
4689 }
4690 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004691 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004692 continue;
4693 }
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695 StringAppendF(&result,
4696 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4697 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004698 uint8_t port;
4699 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004700 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004701 result.append("no identification data\n");
4702 continue;
4703 }
4704
4705 if (!isEdid(data)) {
4706 result.append("unknown identification data: ");
4707 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004708 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004709 }
4710 result.append("\n");
4711 continue;
4712 }
4713
4714 const auto edid = parseEdid(data);
4715 if (!edid) {
4716 result.append("invalid EDID: ");
4717 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004719 }
4720 result.append("\n");
4721 continue;
4722 }
4723
Yiwei Zhang5434a782018-12-05 18:06:32 -08004724 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004725 result.append(edid->displayName.data(), edid->displayName.length());
4726 result.append("\"\n");
4727 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004728}
4729
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4731 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4732 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4733 StringAppendF(&result, "DisplayColorSetting: %s\n",
4734 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004735
4736 // TODO: print out if wide-color mode is active or not
4737
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004738 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004739 const auto displayId = display->getId();
4740 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004741 continue;
4742 }
4743
Yiwei Zhang5434a782018-12-05 18:06:32 -08004744 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004745 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004746 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004747 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004748 }
4749
Lloyd Pique32cbe282018-10-19 13:09:22 -07004750 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, " Current color mode: %s (%d)\n",
4752 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004753 }
4754 result.append("\n");
4755}
4756
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004757LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4758 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004759 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004760 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4761 const State& state = useDrawing ? mDrawingState : mCurrentState;
4762 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004763 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004764 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004765 });
4766
4767 return layersProto;
4768}
4769
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004770LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4771 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004772 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004773
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004774 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004775 resolution->set_w(displayDevice->getWidth());
4776 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004777
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004778 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004779 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004780
Lloyd Pique32cbe282018-10-19 13:09:22 -07004781 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4782 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4783 layersProto.set_global_transform(displayState.orientation);
4784
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004785 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004786 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004787 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004788 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004789 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004790 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004791 }
4792 });
4793
4794 return layersProto;
4795}
4796
Dominik Laskowskic2867142019-01-21 11:33:38 -08004797void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4798 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004799 Colorizer colorizer(colorize);
4800
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004801 // figure out if we're stuck somewhere
4802 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004804 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4805
4806 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004807 * Dump library configuration.
4808 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809
4810 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004811 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004812 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004813 appendSfConfigString(result);
4814 appendUiConfigString(result);
4815 appendGuiConfigString(result);
4816 result.append("\n");
4817
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004818 result.append("\nDisplay identification data:\n");
4819 dumpDisplayIdentificationData(result);
4820
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004821 result.append("\nWide-Color information:\n");
4822 dumpWideColorInfo(result);
4823
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004824 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004825 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004826 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004827 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004828 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004829
Andy McFadden41d67d72014-04-25 16:58:34 -07004830 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004831 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004832 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004833 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004834 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004835
Dan Stozab90cf072015-03-05 11:05:59 -08004836 dumpStaticScreenStats(result);
4837 result.append("\n");
4838
Alec Mouri40189b02019-03-05 15:07:54 -08004839 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4840 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4841 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004842
Dan Stozae77c7662016-05-13 11:37:28 -07004843 dumpBufferingStats(result);
4844
Andy McFadden4803b742012-09-24 19:07:20 -07004845 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004846 * Dump the visible layer list
4847 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004848 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4850 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4851 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004852 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004853
Chia-I Wu2f884132018-09-13 15:17:58 -07004854 {
4855 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4856 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004857 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004858 result.append("\n");
4859 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004860
Lloyd Pique207def92019-02-28 16:09:52 -08004861 {
4862 StringAppendF(&result, "Composition layers\n");
4863 mDrawingState.traverseInZOrder([&](Layer* layer) {
4864 auto compositionLayer = layer->getCompositionLayer();
4865 if (compositionLayer) compositionLayer->dump(result);
4866 });
4867 }
4868
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004869 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004870 * Dump Display state
4871 */
4872
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004873 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004874 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004875 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004876 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004877 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004878 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004879 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004880
4881 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004882 * Dump SurfaceFlinger global state
4883 */
4884
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004885 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004886 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004887 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004888
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004889 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004890
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004892 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4893 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4895 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004896 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004897 StringAppendF(&result,
4898 " transaction-flags : %08x\n"
4899 " gpu_to_cpu_unsupported : %d\n",
4900 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004901
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004902 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004903 displayId && getHwComposer().isConnected(*displayId)) {
4904 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004905 StringAppendF(&result,
4906 " refresh-rate : %f fps\n"
4907 " x-dpi : %f\n"
4908 " y-dpi : %f\n",
4909 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4910 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004911 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004912
Yiwei Zhang5434a782018-12-05 18:06:32 -08004913 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004914
Dan Stozae22aec72016-08-01 13:20:59 -07004915 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004916 * Tracing state
4917 */
4918 mTracing.dump(result);
4919 result.append("\n");
4920
4921 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004922 * HWC layer minidump
4923 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004924 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004925 const auto displayId = display->getId();
4926 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004927 continue;
4928 }
4929
Yiwei Zhang5434a782018-12-05 18:06:32 -08004930 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004931 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004932 const sp<DisplayDevice> displayDevice = display;
4933 mCurrentState.traverseInZOrder(
4934 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004935 result.append("\n");
4936 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004937
4938 /*
4939 * Dump HWComposer state
4940 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004941 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004942 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004943 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004944 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004945 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004946 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004947
4948 /*
4949 * Dump gralloc state
4950 */
4951 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4952 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004953
4954 /*
4955 * Dump VrFlinger state if in use.
4956 */
4957 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4958 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004959 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004960 result.append("\n");
4961 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004962
4963 /**
4964 * Scheduler dump state.
4965 */
Ana Krulecc2870422019-01-29 19:00:58 -08004966 result.append("\nScheduler state:\n");
4967 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08004968 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07004969 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004970
4971 result.append(mTimeStats->miniDump());
4972 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004973}
4974
Dominik Laskowski075d3172018-05-24 15:50:06 -07004975const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004976 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004977 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004978 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004979 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004980 }
4981 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004982
Dominik Laskowski34157762018-10-31 13:07:19 -07004983 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004984 static const Vector<sp<Layer>> empty;
4985 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004986}
4987
Chia-I Wu28f320b2018-05-03 11:02:56 -07004988void SurfaceFlinger::updateColorMatrixLocked() {
4989 mat4 colorMatrix;
4990 if (mGlobalSaturationFactor != 1.0f) {
4991 // Rec.709 luma coefficients
4992 float3 luminance{0.213f, 0.715f, 0.072f};
4993 luminance *= 1.0f - mGlobalSaturationFactor;
4994 mat4 saturationMatrix = mat4(
4995 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4996 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4997 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4998 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4999 );
5000 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5001 } else {
5002 colorMatrix = mClientColorMatrix * mDaltonizer();
5003 }
5004
5005 if (mCurrentState.colorMatrix != colorMatrix) {
5006 mCurrentState.colorMatrix = colorMatrix;
5007 mCurrentState.colorMatrixChanged = true;
5008 setTransactionFlags(eTransactionNeeded);
5009 }
5010}
5011
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005012status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005013#pragma clang diagnostic push
5014#pragma clang diagnostic error "-Wswitch-enum"
5015 switch (static_cast<ISurfaceComposerTag>(code)) {
5016 // These methods should at minimum make sure that the client requested
5017 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005018 case BOOT_FINISHED:
5019 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005020 case CREATE_DISPLAY:
5021 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005022 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005023 case GET_ANIMATION_FRAME_STATS:
5024 case GET_HDR_CAPABILITIES:
5025 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005026 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005027 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005028 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005029 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005030 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005031 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005032 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5033 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005034 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5035 IPCThreadState* ipc = IPCThreadState::self();
5036 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5037 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005038 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005039 }
Robert Carr1db73f62016-12-21 12:58:51 -08005040 return OK;
5041 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005042 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005043 IPCThreadState* ipc = IPCThreadState::self();
5044 const int pid = ipc->getCallingPid();
5045 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005046 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5047 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005048 return PERMISSION_DENIED;
5049 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005050 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005052 // Used by apps to hook Choreographer to SurfaceFlinger.
5053 case CREATE_DISPLAY_EVENT_CONNECTION:
5054 // The following calls are currently used by clients that do not
5055 // request necessary permissions. However, they do not expose any secret
5056 // information, so it is OK to pass them.
5057 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005058 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005059 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005060 case GET_PHYSICAL_DISPLAY_IDS:
5061 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005062 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005063 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005064 case GET_DISPLAY_CONFIGS:
5065 case GET_DISPLAY_STATS:
5066 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5067 // Calling setTransactionState is safe, because you need to have been
5068 // granted a reference to Client* and Handle* to do anything with it.
5069 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005070 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005071 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005072 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005073 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005074 case IS_WIDE_COLOR_DISPLAY:
5075 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5076 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005077 return OK;
5078 }
5079 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005080 case CAPTURE_SCREEN:
5081 case ADD_REGION_SAMPLING_LISTENER:
5082 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005083 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005084 IPCThreadState* ipc = IPCThreadState::self();
5085 const int pid = ipc->getCallingPid();
5086 const int uid = ipc->getCallingUid();
5087 if ((uid != AID_GRAPHICS) &&
5088 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5089 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5090 return PERMISSION_DENIED;
5091 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005092 return OK;
5093 }
5094 // The following codes are deprecated and should never be allowed to access SF.
5095 case CONNECT_DISPLAY_UNUSED:
5096 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5097 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5098 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005099 }
chaviw93df2ea2019-04-30 16:45:12 -07005100 case CAPTURE_SCREEN_BY_ID: {
5101 IPCThreadState* ipc = IPCThreadState::self();
5102 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005103 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005104 return OK;
5105 }
5106 return PERMISSION_DENIED;
5107 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005108 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005109
5110 // These codes are used for the IBinder protocol to either interrogate the recipient
5111 // side of the transaction for its canonical interface descriptor or to dump its state.
5112 // We let them pass by default.
5113 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5114 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5115 code == IBinder::SYSPROPS_TRANSACTION) {
5116 return OK;
5117 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005118 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005119 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005120 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005121 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5122 return OK;
5123 }
5124 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5125 return PERMISSION_DENIED;
5126#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005127}
5128
Ana Krulec13be8ad2018-08-21 02:43:56 +00005129status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5130 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005131 status_t credentialCheck = CheckTransactCodeCredentials(code);
5132 if (credentialCheck != OK) {
5133 return credentialCheck;
5134 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005136 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5137 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005138 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005139 IPCThreadState* ipc = IPCThreadState::self();
5140 const int uid = ipc->getCallingUid();
5141 if (CC_UNLIKELY(uid != AID_SYSTEM
5142 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005143 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005144 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005145 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005146 return PERMISSION_DENIED;
5147 }
5148 int n;
5149 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005150 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005151 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005152 return NO_ERROR;
5153 case 1002: // SHOW_UPDATES
5154 n = data.readInt32();
5155 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005156 invalidateHwcGeometry();
5157 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005158 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005159 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005160 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005161 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005162 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005163 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005164 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005165 setTransactionFlags(
5166 eTransactionNeeded|
5167 eDisplayTransactionNeeded|
5168 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005169 return NO_ERROR;
5170 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005171 case 1006:{ // send empty update
5172 signalRefresh();
5173 return NO_ERROR;
5174 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005175 case 1008: // toggle use of hw composer
5176 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005177 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005178 invalidateHwcGeometry();
5179 repaintEverything();
5180 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005181 case 1009: // toggle use of transform hint
5182 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005183 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005184 invalidateHwcGeometry();
5185 repaintEverything();
5186 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005187 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005188 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005189 reply->writeInt32(0);
5190 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005191 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005192 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005193 return NO_ERROR;
5194 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005195 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005196 if (!display) {
5197 return NAME_NOT_FOUND;
5198 }
5199
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005200 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005201 return NO_ERROR;
5202 }
5203 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005204 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005205 // daltonize
5206 n = data.readInt32();
5207 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005208 case 1:
5209 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5210 break;
5211 case 2:
5212 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5213 break;
5214 case 3:
5215 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5216 break;
5217 default:
5218 mDaltonizer.setType(ColorBlindnessType::None);
5219 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005220 }
5221 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005222 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005223 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005224 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005225 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005226
5227 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005228 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005229 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005230 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005231 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005232 // apply a color matrix
5233 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005234 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005235 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005236 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005237 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005238 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005239 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005240 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005241 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005242 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005243 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005244
5245 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5246 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005247 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005248 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5249 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5250 }
5251
Chia-I Wu28f320b2018-05-03 11:02:56 -07005252 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005253 return NO_ERROR;
5254 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005255 // This is an experimental interface
5256 // Needs to be shifted to proper binder interface when we productize
5257 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005258 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005259 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005260 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005261 return NO_ERROR;
5262 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005263 case 1017: {
5264 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005265 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005266 return NO_ERROR;
5267 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005268 case 1018: { // Modify Choreographer's phase offset
5269 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005270 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005271 return NO_ERROR;
5272 }
5273 case 1019: { // Modify SurfaceFlinger's phase offset
5274 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005275 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005276 return NO_ERROR;
5277 }
Irvel468051e2016-06-13 16:44:44 -07005278 case 1020: { // Layer updates interceptor
5279 n = data.readInt32();
5280 if (n) {
5281 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005282 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005283 }
5284 else{
5285 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005286 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005287 }
5288 return NO_ERROR;
5289 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005290 case 1021: { // Disable HWC virtual displays
5291 n = data.readInt32();
5292 mUseHwcVirtualDisplays = !n;
5293 return NO_ERROR;
5294 }
Romain Guy0147a172017-06-01 13:53:56 -07005295 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005296 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005297 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005298
Chia-I Wu28f320b2018-05-03 11:02:56 -07005299 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005300 return NO_ERROR;
5301 }
Romain Guy54f154a2017-10-24 21:40:32 +01005302 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005303 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005304 invalidateHwcGeometry();
5305 repaintEverything();
5306 return NO_ERROR;
5307 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005308 // Deprecate, use 1030 to check whether the device is color managed.
5309 case 1024: {
5310 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005311 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005312 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005313 n = data.readInt32();
5314 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005315 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005316 Mutex::Autolock lock(mStateLock);
5317 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005318 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005319 reply->writeInt32(NO_ERROR);
5320 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005321 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005322 bool writeFile = false;
5323 {
5324 Mutex::Autolock lock(mStateLock);
5325 mTracingEnabledChanged = true;
5326 writeFile = mTracing.disable();
5327 }
5328
5329 if (writeFile) {
5330 reply->writeInt32(mTracing.writeToFile());
5331 } else {
5332 reply->writeInt32(NO_ERROR);
5333 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005334 }
5335 return NO_ERROR;
5336 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005337 case 1026: { // Get layer tracing status
5338 reply->writeBool(mTracing.isEnabled());
5339 return NO_ERROR;
5340 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005341 // Is a DisplayColorSetting supported?
5342 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005343 const auto display = getDefaultDisplayDevice();
5344 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005345 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005346 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005347
5348 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5349 switch (setting) {
5350 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005351 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005352 break;
5353 case DisplayColorSetting::UNMANAGED:
5354 reply->writeBool(true);
5355 break;
5356 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005357 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005358 break;
5359 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005360 reply->writeBool(
5361 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005362 break;
5363 }
5364 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005365 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005366 // Is VrFlinger active?
5367 case 1028: {
5368 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005369 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005370 return NO_ERROR;
5371 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005372 // Set buffer size for SF tracing (value in KB)
5373 case 1029: {
5374 n = data.readInt32();
5375 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5376 ALOGW("Invalid buffer size: %d KB", n);
5377 reply->writeInt32(BAD_VALUE);
5378 return BAD_VALUE;
5379 }
5380
5381 ALOGD("Updating trace buffer to %d KB", n);
5382 mTracing.setBufferSize(n * 1024);
5383 reply->writeInt32(NO_ERROR);
5384 return NO_ERROR;
5385 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005386 // Is device color managed?
5387 case 1030: {
5388 reply->writeBool(useColorManagement);
5389 return NO_ERROR;
5390 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005391 // Override default composition data space
5392 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5393 // && adb shell stop zygote && adb shell start zygote
5394 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5395 // adb shell stop zygote && adb shell start zygote
5396 case 1031: {
5397 Mutex::Autolock _l(mStateLock);
5398 n = data.readInt32();
5399 if (n) {
5400 n = data.readInt32();
5401 if (n) {
5402 Dataspace dataspace = static_cast<Dataspace>(n);
5403 if (!validateCompositionDataspace(dataspace)) {
5404 return BAD_VALUE;
5405 }
5406 mDefaultCompositionDataspace = dataspace;
5407 }
5408 n = data.readInt32();
5409 if (n) {
5410 Dataspace dataspace = static_cast<Dataspace>(n);
5411 if (!validateCompositionDataspace(dataspace)) {
5412 return BAD_VALUE;
5413 }
5414 mWideColorGamutCompositionDataspace = dataspace;
5415 }
5416 } else {
5417 // restore composition data space.
5418 mDefaultCompositionDataspace = defaultCompositionDataspace;
5419 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5420 }
5421 return NO_ERROR;
5422 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005423 // Set trace flags
5424 case 1033: {
5425 n = data.readUint32();
5426 ALOGD("Updating trace flags to 0x%x", n);
5427 mTracing.setTraceFlags(n);
5428 reply->writeInt32(NO_ERROR);
5429 return NO_ERROR;
5430 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005431 case 1034: {
5432 // TODO(b/129297325): expose this via developer menu option
5433 n = data.readInt32();
5434 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005435 RefreshRateType type;
5436 {
5437 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5438 type = mDesiredActiveConfig.type;
5439 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005440 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005441 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005442 } else if (!n) {
5443 mRefreshRateOverlay.reset();
5444 }
5445 return NO_ERROR;
5446 }
Ady Abraham34392f72019-04-10 11:29:27 -07005447 case 1035: {
5448 n = data.readInt32();
5449 mDebugDisplayConfigSetByBackdoor = false;
5450 if (n >= 0) {
5451 const auto displayToken = getInternalDisplayToken();
5452 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5453 if (result != NO_ERROR) {
5454 return result;
5455 }
5456 mDebugDisplayConfigSetByBackdoor = true;
5457 }
5458 return NO_ERROR;
5459 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005460 }
5461 }
5462 return err;
5463}
5464
Steven Thomas6d8110b2017-08-31 18:24:21 -07005465void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005466 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005467 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005468}
5469
Ana Krulec7d1d6832018-12-27 11:10:09 -08005470void SurfaceFlinger::repaintEverythingForHWC() {
5471 mRepaintEverything = true;
5472 mEventQueue->invalidateForHWC();
5473}
5474
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005475// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5476class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005477public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005478 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5479 ~WindowDisconnector() {
5480 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005481 }
5482
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005483private:
5484 ANativeWindow* mWindow;
5485 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005486};
5487
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005488status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005489 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5490 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005491 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005492 uint32_t reqWidth, uint32_t reqHeight,
5493 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005494 ISurfaceComposer::Rotation rotation,
5495 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005498 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005499
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005500 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5501
Chia-I Wu20261cb2018-08-23 12:55:44 -07005502 sp<DisplayDevice> display;
5503 {
5504 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005505
Chia-I Wu20261cb2018-08-23 12:55:44 -07005506 display = getDisplayDeviceLocked(displayToken);
5507 if (!display) return BAD_VALUE;
5508
Chia-I Wucb023152018-08-28 12:57:23 -07005509 // set the requested width/height to the logical display viewport size
5510 // by default
5511 if (reqWidth == 0 || reqHeight == 0) {
5512 reqWidth = uint32_t(display->getViewport().width());
5513 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005514 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005515 }
5516
Peiyong Lin0e003c92018-09-17 11:09:51 -07005517 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005518 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005519
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005520 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5521 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005522 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005523 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005524}
5525
chaviw93df2ea2019-04-30 16:45:12 -07005526static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5527 switch (colorMode) {
5528 case ColorMode::DISPLAY_P3:
5529 case ColorMode::BT2100_PQ:
5530 case ColorMode::BT2100_HLG:
5531 case ColorMode::DISPLAY_BT2020:
5532 return Dataspace::DISPLAY_P3;
5533 default:
5534 return Dataspace::V0_SRGB;
5535 }
5536}
5537
5538const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5539 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5540 if (displayToken) {
5541 return getDisplayDeviceLocked(displayToken);
5542 }
5543 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5544 // may not have a displayId.
5545 for (const auto& [token, display] : mDisplays) {
5546 if (display->getLayerStack() == displayOrLayerStack) {
5547 return display;
5548 }
5549 }
5550 return nullptr;
5551}
5552
5553status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5554 sp<GraphicBuffer>* outBuffer) {
5555 sp<DisplayDevice> display;
5556 uint32_t width;
5557 uint32_t height;
5558 ui::Transform::orientation_flags captureOrientation;
5559 {
5560 Mutex::Autolock _l(mStateLock);
5561 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5562 if (!display) {
5563 return BAD_VALUE;
5564 }
5565
5566 width = uint32_t(display->getViewport().width());
5567 height = uint32_t(display->getViewport().height());
5568
5569 captureOrientation = fromSurfaceComposerRotation(
5570 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
5571 *outDataspace =
5572 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5573 }
5574
5575 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5576 false /* captureSecureLayers */);
5577
5578 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5579 std::placeholders::_1);
5580 bool ignored = false;
5581 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5582 false /* useIdentityTransform */,
5583 ignored /* outCapturedSecureLayers */);
5584}
5585
Robert Carr866455f2019-04-02 16:28:26 -07005586status_t SurfaceFlinger::captureLayers(
5587 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5588 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5589 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5590 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005591 ATRACE_CALL();
5592
5593 class LayerRenderArea : public RenderArea {
5594 public:
Robert Carr578038f2018-03-09 12:25:24 -08005595 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005596 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5597 bool childrenOnly)
5598 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005599 mLayer(layer),
5600 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005601 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005602 mFlinger(flinger),
5603 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005604 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005605 Rect getBounds() const override {
5606 const Layer::State& layerState(mLayer->getDrawingState());
5607 return mLayer->getBufferSize(layerState);
5608 }
Marissa Wall61c58622018-07-18 10:12:20 -07005609 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005610 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005611 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005612 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005613 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005614 }
chaviwa76b2712017-09-20 12:02:26 -07005615 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005616 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005617 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005618 Rect getSourceCrop() const override {
5619 if (mCrop.isEmpty()) {
5620 return getBounds();
5621 } else {
5622 return mCrop;
5623 }
5624 }
Robert Carr578038f2018-03-09 12:25:24 -08005625 class ReparentForDrawing {
5626 public:
5627 const sp<Layer>& oldParent;
5628 const sp<Layer>& newParent;
5629
Vishnu Nair4351ad52019-02-11 14:13:02 -08005630 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5631 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005632 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005633 // Compute and cache the bounds for the new parent layer.
5634 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005635 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005636 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005637 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005638 };
5639
5640 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005641 const Rect sourceCrop = getSourceCrop();
5642 // no need to check rotation because there is none
5643 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5644 sourceCrop.height() != getReqHeight();
5645
Robert Carr578038f2018-03-09 12:25:24 -08005646 if (!mChildrenOnly) {
5647 mTransform = mLayer->getTransform().inverse();
5648 drawLayers();
5649 } else {
5650 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005651 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005652 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005653 bounds.getWidth(), bounds.getHeight(), 0,
5654 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005655
Vishnu Nair4351ad52019-02-11 14:13:02 -08005656 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005657 drawLayers();
5658 }
5659 }
chaviwa76b2712017-09-20 12:02:26 -07005660
chaviwa76b2712017-09-20 12:02:26 -07005661 private:
chaviw7206d492017-11-10 16:16:12 -08005662 const sp<Layer> mLayer;
5663 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005664
5665 // In the "childrenOnly" case we reparent the children to a screenshot
5666 // layer which has no properties set and which does not draw.
5667 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005668 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005669 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005670
5671 SurfaceFlinger* mFlinger;
5672 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005673 };
5674
Robert Carrc0df3122019-04-11 13:18:21 -07005675 int reqWidth = 0;
5676 int reqHeight = 0;
5677 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005678 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005679 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005680
Robert Carrc0df3122019-04-11 13:18:21 -07005681 {
5682 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005683
Robert Carrc0df3122019-04-11 13:18:21 -07005684 parent = fromHandle(layerHandleBinder);
5685 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5686 ALOGE("captureLayers called with an invalid or removed parent");
5687 return NAME_NOT_FOUND;
5688 }
5689
5690 const int uid = IPCThreadState::self()->getCallingUid();
5691 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5692 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5693 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5694 return PERMISSION_DENIED;
5695 }
5696
5697 if (sourceCrop.width() <= 0) {
5698 crop.left = 0;
5699 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5700 }
5701
5702 if (sourceCrop.height() <= 0) {
5703 crop.top = 0;
5704 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5705 }
5706 reqWidth = crop.width() * frameScale;
5707 reqHeight = crop.height() * frameScale;
5708
5709 for (const auto& handle : excludeHandles) {
5710 sp<Layer> excludeLayer = fromHandle(handle);
5711 if (excludeLayer != nullptr) {
5712 excludeLayers.emplace(excludeLayer);
5713 } else {
5714 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5715 return NAME_NOT_FOUND;
5716 }
5717 }
5718 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005719
Chia-I Wu20261cb2018-08-23 12:55:44 -07005720 // really small crop or frameScale
5721 if (reqWidth <= 0) {
5722 reqWidth = 1;
5723 }
5724 if (reqHeight <= 0) {
5725 reqHeight = 1;
5726 }
5727
Robert Carr866455f2019-04-02 16:28:26 -07005728 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5729 auto traverseLayers = [parent, childrenOnly,
5730 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005731 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5732 if (!layer->isVisible()) {
5733 return;
Robert Carr578038f2018-03-09 12:25:24 -08005734 } else if (childrenOnly && layer == parent.get()) {
5735 return;
chaviwa76b2712017-09-20 12:02:26 -07005736 }
Robert Carr866455f2019-04-02 16:28:26 -07005737
5738 sp<Layer> p = layer;
5739 while (p != nullptr) {
5740 if (excludeLayers.count(p) != 0) {
5741 return;
5742 }
5743 p = p->getParent();
5744 }
5745
chaviwa76b2712017-09-20 12:02:26 -07005746 visitor(layer);
5747 });
5748 };
Robert Carr108b2c72019-04-02 16:32:58 -07005749
5750 bool outCapturedSecureLayers = false;
5751 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5752 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005753}
5754
5755status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5756 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005757 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005758 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005759 bool useIdentityTransform,
5760 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005761 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005762
Peiyong Lin0e003c92018-09-17 11:09:51 -07005763 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005764 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5765 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005766 *outBuffer =
5767 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5768 static_cast<android_pixel_format>(reqPixelFormat), 1,
5769 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005770
Robert Carr108b2c72019-04-02 16:32:58 -07005771 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5772 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005773}
5774
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005775status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5776 TraverseLayersFunction traverseLayers,
5777 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005778 bool useIdentityTransform,
5779 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005780 // This mutex protects syncFd and captureResult for communication of the return values from the
5781 // main thread back to this Binder thread
5782 std::mutex captureMutex;
5783 std::condition_variable captureCondition;
5784 std::unique_lock<std::mutex> captureLock(captureMutex);
5785 int syncFd = -1;
5786 std::optional<status_t> captureResult;
5787
Robert Carr03480e22018-01-04 16:02:06 -08005788 const int uid = IPCThreadState::self()->getCallingUid();
5789 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5790
Dominik Laskowski8c001672018-05-30 16:52:06 -07005791 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005792 // If there is a refresh pending, bug out early and tell the binder thread to try again
5793 // after the refresh.
5794 if (mRefreshPending) {
5795 ATRACE_NAME("Skipping screenshot for now");
5796 std::unique_lock<std::mutex> captureLock(captureMutex);
5797 captureResult = std::make_optional<status_t>(EAGAIN);
5798 captureCondition.notify_one();
5799 return;
5800 }
5801
5802 status_t result = NO_ERROR;
5803 int fd = -1;
5804 {
5805 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005806 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005807 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005808 useIdentityTransform, forSystem, &fd,
5809 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005810 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005811 }
5812
5813 {
5814 std::unique_lock<std::mutex> captureLock(captureMutex);
5815 syncFd = fd;
5816 captureResult = std::make_optional<status_t>(result);
5817 captureCondition.notify_one();
5818 }
5819 });
5820
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005821 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005822 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005823 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005824 while (*captureResult == EAGAIN) {
5825 captureResult.reset();
5826 result = postMessageAsync(message);
5827 if (result != NO_ERROR) {
5828 return result;
5829 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005830 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005831 }
5832 result = *captureResult;
5833 }
5834
5835 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005836 sync_wait(syncFd, -1);
5837 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005838 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005839
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005840 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005841}
5842
chaviwa76b2712017-09-20 12:02:26 -07005843void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005844 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005845 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5846 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005847 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005848
chaviwa76b2712017-09-20 12:02:26 -07005849 const auto reqWidth = renderArea.getReqWidth();
5850 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005851 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005852 const auto transform = renderArea.getTransform();
5853 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005854
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005855 renderengine::DisplaySettings clientCompositionDisplay;
5856 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005857
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005858 // assume that bounds are never offset, and that they are the same as the
5859 // buffer bounds.
5860 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005861 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005862 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005863
5864 // Now take into account the rotation flag. We append a transform that
5865 // rotates the layer stack about the origin, then translate by buffer
5866 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005867 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005868 int displacementX = 0;
5869 int displacementY = 0;
5870 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5871 switch (rotation) {
5872 case ui::Transform::ROT_90:
5873 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005874 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005875 break;
5876 case ui::Transform::ROT_180:
5877 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005878 displacementY = renderArea.getBounds().getWidth();
5879 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005880 break;
5881 case ui::Transform::ROT_270:
5882 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005883 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005884 break;
5885 default:
5886 break;
5887 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005888
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005889 // We need to transform the clipping window into the right spot.
5890 // First, rotate the clipping rectangle by the rotation hint to get the
5891 // right orientation
5892 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5893 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5894 const vec4 rotClipTL = rotMatrix * clipTL;
5895 const vec4 rotClipBR = rotMatrix * clipBR;
5896 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5897 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5898 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5899 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5900
5901 // Now reposition the clipping rectangle with the displacement vector
5902 // computed above.
5903 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005904 clientCompositionDisplay.clip =
5905 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5906 newClipRight + displacementX, newClipBottom + displacementY);
5907
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005908 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005909 clientCompositionDisplay.globalTransform =
5910 clipTransform * clientCompositionDisplay.globalTransform;
5911
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005912 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5913 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005914
chaviw50da5042018-04-09 13:49:37 -07005915 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005916
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005917 renderengine::LayerSettings fillLayer;
5918 fillLayer.source.buffer.buffer = nullptr;
5919 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5920 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5921 fillLayer.alpha = half(alpha);
5922 clientCompositionLayers.push_back(fillLayer);
5923
5924 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005925 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005926 renderengine::LayerSettings layerSettings;
5927 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005928 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005929 if (prepared) {
5930 clientCompositionLayers.push_back(layerSettings);
5931 }
chaviwa76b2712017-09-20 12:02:26 -07005932 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005933
5934 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005935 // Use an empty fence for the buffer fence, since we just created the buffer so
5936 // there is no need for synchronization with the GPU.
5937 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005938 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005939 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005940 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005941 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005942
5943 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005944}
5945
chaviwa76b2712017-09-20 12:02:26 -07005946status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5947 TraverseLayersFunction traverseLayers,
5948 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005949 bool useIdentityTransform, bool forSystem,
5950 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005951 ATRACE_CALL();
5952
chaviwa76b2712017-09-20 12:02:26 -07005953 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005954 outCapturedSecureLayers =
5955 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005956 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005957
Robert Carr03480e22018-01-04 16:02:06 -08005958 // We allow the system server to take screenshots of secure layers for
5959 // use in situations like the Screen-rotation animation and place
5960 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005961 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005962 ALOGW("FB is protected: PERMISSION_DENIED");
5963 return PERMISSION_DENIED;
5964 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005965 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005966 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005967}
5968
chaviw95ef3c42019-02-14 10:55:09 -08005969void SurfaceFlinger::setInputWindowsFinished() {
5970 Mutex::Autolock _l(mStateLock);
5971
5972 mPendingSyncInputWindows = false;
5973 mTransactionCV.broadcast();
5974}
chaviw5f21a5e2019-02-14 10:00:34 -08005975
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005976// ---------------------------------------------------------------------------
5977
Dan Stoza412903f2017-04-27 13:42:17 -07005978void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5979 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005980}
5981
Dan Stoza412903f2017-04-27 13:42:17 -07005982void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5983 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005984}
5985
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005986void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005987 const LayerVector::Visitor& visitor) {
5988 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005989 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005990 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005991 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005992 continue;
5993 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005994 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005995 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005996 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005997 return;
5998 }
chaviwa76b2712017-09-20 12:02:26 -07005999 if (!layer->isVisible()) {
6000 return;
6001 }
6002 visitor(layer);
6003 });
6004 }
6005}
6006
Dominik Laskowski22488f62019-03-28 09:53:04 -07006007void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6008 const std::vector<int32_t>& allowedConfigs) {
6009 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006010 return;
6011 }
6012
6013 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006014 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006015
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006016 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006017 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006018 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006019 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006020 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006021 setDesiredActiveConfig(
6022 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006023 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006024 }
6025 }
Ady Abraham838de062019-02-04 10:24:03 -08006026}
6027
Dominik Laskowski22488f62019-03-28 09:53:04 -07006028status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006029 const std::vector<int32_t>& allowedConfigs) {
6030 ATRACE_CALL();
6031
Dominik Laskowski22488f62019-03-28 09:53:04 -07006032 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006033 return BAD_VALUE;
6034 }
6035
Ady Abraham34392f72019-04-10 11:29:27 -07006036 if (mDebugDisplayConfigSetByBackdoor) {
6037 // ignore this request as config is overridden by backdoor
6038 return NO_ERROR;
6039 }
6040
Ady Abraham838de062019-02-04 10:24:03 -08006041 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006042 const auto display = getDisplayDeviceLocked(displayToken);
6043 if (!display) {
6044 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6045 displayToken.get());
6046 } else if (display->isVirtual()) {
6047 ALOGW("Attempt to set allowed display configs for virtual display");
6048 } else {
6049 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6050 }
Ady Abraham838de062019-02-04 10:24:03 -08006051 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006052
Ady Abraham838de062019-02-04 10:24:03 -08006053 return NO_ERROR;
6054}
6055
Dominik Laskowski22488f62019-03-28 09:53:04 -07006056status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006057 std::vector<int32_t>* outAllowedConfigs) {
6058 ATRACE_CALL();
6059
Dominik Laskowski22488f62019-03-28 09:53:04 -07006060 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006061 return BAD_VALUE;
6062 }
6063
Dominik Laskowski22488f62019-03-28 09:53:04 -07006064 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006065
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006066 const auto display = getDisplayDeviceLocked(displayToken);
6067 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006068 return NAME_NOT_FOUND;
6069 }
6070
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006071 if (display->isPrimary()) {
6072 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6073 }
6074
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006075 return NO_ERROR;
6076}
6077
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006078void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006079 mFlinger->setInputWindowsFinished();
6080}
6081
Robert Carrc0df3122019-04-11 13:18:21 -07006082sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6083 BBinder *b = handle->localBinder();
6084 if (b == nullptr) {
6085 return nullptr;
6086 }
6087 auto it = mLayersByLocalBinderToken.find(b);
6088 if (it != mLayersByLocalBinderToken.end()) {
6089 return it->second.promote();
6090 }
6091 return nullptr;
6092}
6093
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006094} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006095
Mathias Agopian3f844832013-08-07 21:24:32 -07006096#if defined(__gl_h_)
6097#error "don't include gl/gl.h in this file"
6098#endif
6099
6100#if defined(__gl2_h_)
6101#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006102#endif