blob: e1e3dfb4d2b8a2e88d3d20cec9f5eb6f38fcb766 [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>
Ady Abraham8164d482019-01-11 14:47:59 -080065#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.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"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700113#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900115#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
chaviw1d044282017-09-27 12:19:28 -0700117#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900118#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700121
Jaesoo Lee43518572017-01-23 19:03:16 +0900122using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800125
Yiwei Zhang5434a782018-12-05 18:06:32 -0800126using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700127using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700128using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800129using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700130using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700131using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
134
Steven Thomasb02664d2017-07-26 18:48:28 -0700135namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700136
137#pragma clang diagnostic push
138#pragma clang diagnostic error "-Wswitch-enum"
139
140bool isWideColorMode(const ColorMode colorMode) {
141 switch (colorMode) {
142 case ColorMode::DISPLAY_P3:
143 case ColorMode::ADOBE_RGB:
144 case ColorMode::DCI_P3:
145 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700146 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700147 case ColorMode::BT2100_PQ:
148 case ColorMode::BT2100_HLG:
149 return true;
150 case ColorMode::NATIVE:
151 case ColorMode::STANDARD_BT601_625:
152 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
153 case ColorMode::STANDARD_BT601_525:
154 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
155 case ColorMode::STANDARD_BT709:
156 case ColorMode::SRGB:
157 return false;
158 }
159 return false;
160}
161
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700162ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
163 switch (rotation) {
164 case ISurfaceComposer::eRotateNone:
165 return ui::Transform::ROT_0;
166 case ISurfaceComposer::eRotate90:
167 return ui::Transform::ROT_90;
168 case ISurfaceComposer::eRotate180:
169 return ui::Transform::ROT_180;
170 case ISurfaceComposer::eRotate270:
171 return ui::Transform::ROT_270;
172 }
173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
174 return ui::Transform::ROT_0;
175}
176
Peiyong Linfca547f2018-07-09 13:03:33 -0700177#pragma clang diagnostic pop
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179class ConditionalLock {
180public:
181 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
182 if (lock) {
183 mMutex.lock();
184 }
185 }
186 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
187private:
188 Mutex& mMutex;
189 bool mLocked;
190};
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
Peiyong Lin9d846a52018-11-05 13:18:20 -0800192// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
193bool validateCompositionDataspace(Dataspace dataspace) {
194 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
195}
196
Steven Thomasb02664d2017-07-26 18:48:28 -0700197} // namespace anonymous
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Mathias Agopian99b49842011-06-27 16:05:52 -0700201const String16 sHardwareTest("android.permission.HARDWARE_TEST");
202const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
203const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
204const String16 sDump("android.permission.DUMP");
205
Daniel Solomon42d04562019-01-20 21:03:19 -0800206constexpr float kSrgbRedX = 0.4123f;
207constexpr float kSrgbRedY = 0.2126f;
208constexpr float kSrgbRedZ = 0.0193f;
209constexpr float kSrgbGreenX = 0.3576f;
210constexpr float kSrgbGreenY = 0.7152f;
211constexpr float kSrgbGreenZ = 0.1192f;
212constexpr float kSrgbBlueX = 0.1805f;
213constexpr float kSrgbBlueY = 0.0722f;
214constexpr float kSrgbBlueZ = 0.9506f;
215constexpr float kSrgbWhiteX = 0.9505f;
216constexpr float kSrgbWhiteY = 1.0000f;
217constexpr float kSrgbWhiteZ = 1.0891f;
218
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800219constexpr float kDefaultRefreshRate = 60.f;
220constexpr float kPerformanceRefreshRate = 90.f;
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700230int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700231bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700232bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700233Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
235Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
254 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
David Sodmanbc815282017-11-05 18:57:52 -0800266SurfaceFlingerBE::SurfaceFlingerBE()
267 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800268 mFrameBuckets(),
269 mTotalTime(0),
270 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800271 mComposerSequenceId(0) {
272}
273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
275 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800276 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700278 mTransactionPending(false),
279 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700280 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700281 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800283 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800285 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800286 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800287 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700289 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700290 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700291 mDebugInTransaction(0),
292 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700293 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800294 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulecc2870422019-01-29 19:00:58 -0800396 property_get("debug.sf.use_90Hz", value, "0");
397 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800398
Ana Krulec757f63a2019-01-25 10:46:18 -0800399 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
400 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700401
Romain Guy11d63f42017-07-20 12:47:14 -0700402 // We should be reading 'persist.sys.sf.color_saturation' here
403 // but since /data may be encrypted, we need to wait until after vold
404 // comes online to attempt to read the property. The property is
405 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800406
407 if (useTrebleTestingOverride()) {
408 // Without the override SurfaceFlinger cannot connect to HIDL
409 // services that are not listed in the manifests. Considered
410 // deriving the setting from the set service name, but it
411 // would be brittle if the name that's not 'default' is used
412 // for production purposes later on.
413 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422SurfaceFlinger::~SurfaceFlinger()
423{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Dan Stozac7014012014-02-14 15:03:43 -0800426void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427{
428 // the window manager died on us. prepare its eulogy.
429
Andy McFadden13a082e2012-08-24 10:16:42 -0700430 // restore initial conditions (default device unblank, etc)
431 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432
433 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700434 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435}
436
Robert Carr1db73f62016-12-21 12:58:51 -0800437static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700438 status_t err = client->initCheck();
439 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441 }
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return nullptr;
443}
444
445sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
446 return initClient(new Client(this));
447}
448
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700449sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
450 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451{
452 class DisplayToken : public BBinder {
453 sp<SurfaceFlinger> flinger;
454 virtual ~DisplayToken() {
455 // no more references, this display must be terminated
456 Mutex::Autolock _l(flinger->mStateLock);
457 flinger->mCurrentState.displays.removeItem(this);
458 flinger->setTransactionFlags(eDisplayTransactionNeeded);
459 }
460 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700461 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462 : flinger(flinger) {
463 }
464 };
465
466 sp<BBinder> token = new DisplayToken(this);
467
468 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 // Display ID is assigned when virtual display is allocated by HWC.
470 DisplayDeviceState state;
471 state.isSecure = secure;
472 state.displayName = displayName;
473 mCurrentState.displays.add(token, state);
474 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 return token;
476}
477
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700478void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 Mutex::Autolock _l(mStateLock);
480
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
482 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 return;
485 }
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
488 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 ALOGE("destroyDisplay called for non-virtual display");
490 return;
491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 mInterceptor->saveDisplayDeletion(state.sequenceId);
493 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 setTransactionFlags(eDisplayTransactionNeeded);
495}
496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
498 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 const auto internalDisplayId = getInternalDisplayIdLocked();
501 if (!internalDisplayId) {
502 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503 }
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 std::vector<PhysicalDisplayId> displayIds;
506 displayIds.reserve(mPhysicalDisplayTokens.size());
507 displayIds.push_back(internalDisplayId->value);
508
509 for (const auto& [id, token] : mPhysicalDisplayTokens) {
510 if (id != *internalDisplayId) {
511 displayIds.push_back(id.value);
512 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800515 return displayIds;
516}
517
518sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
519 Mutex::Autolock lock(mStateLock);
520 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521}
522
Ady Abraham37965d42018-11-01 13:43:32 -0700523status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
524 if (!outGetColorManagement) {
525 return BAD_VALUE;
526 }
527 *outGetColorManagement = useColorManagement;
528 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700529}
530
Lloyd Pique441d5042018-10-18 16:49:51 -0700531HWComposer& SurfaceFlinger::getHwComposer() const {
532 return mCompositionEngine->getHwComposer();
533}
534
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700535renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
536 return mCompositionEngine->getRenderEngine();
537}
538
Lloyd Pique70d91362018-10-18 16:02:55 -0700539compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
540 return *mCompositionEngine.get();
541}
542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543void SurfaceFlinger::bootFinished()
544{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
552 // wait patiently for the window manager death
553 const String16 name("window");
554 sp<IBinder> window(defaultServiceManager()->getService(name));
555 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700556 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 }
Robert Carr720e5062018-07-30 17:45:14 -0700558 sp<IBinder> input(defaultServiceManager()->getService(
559 String16("inputflinger")));
560 if (input == nullptr) {
561 ALOGE("Failed to link to input service");
562 } else {
563 mInputFlinger = interface_cast<IInputFlinger>(input);
564 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 if (mVrFlinger) {
567 mVrFlinger->OnBootFinished();
568 }
569
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700571 // formerly we would just kill the process, but we now ask it to exit so it
572 // can choose where to stop the animation.
573 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700574
575 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
576 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
577 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700578
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 postMessageAsync(new LambdaMessage([this] {
580 readPersistentProperties();
581 mBootStage = BootStage::FINISHED;
582 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800583}
584
Dan Stoza436ccf32018-06-21 12:10:12 -0700585uint32_t SurfaceFlinger::getNewTexture() {
586 {
587 std::lock_guard lock(mTexturePoolMutex);
588 if (!mTexturePool.empty()) {
589 uint32_t name = mTexturePool.back();
590 mTexturePool.pop_back();
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
592 return name;
593 }
594
595 // The pool was too small, so increase it for the future
596 ++mTexturePoolSize;
597 }
598
599 // The pool was empty, so we need to get a new texture name directly using a
600 // blocking call to the main thread
601 uint32_t name = 0;
602 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
603 return name;
604}
605
Mathias Agopian3f844832013-08-07 21:24:32 -0700606void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700607 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700608}
609
Wei Wangf9b05ee2017-07-19 20:59:39 -0700610// Do not call property_set on main thread which will be blocked by init
611// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700613 ALOGI( "SurfaceFlinger's main thread ready to run. "
614 "Initializing graphics H/W...");
615
Ana Krulec757f63a2019-01-25 10:46:18 -0800616 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800620 mScheduler =
621 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
622 auto resyncCallback =
623 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800624
Ana Krulecc2870422019-01-29 19:00:58 -0800625 mAppConnectionHandle =
626 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
627 resyncCallback,
628 impl::EventThread::InterceptVSyncsCallback());
629 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
630 resyncCallback, [this](nsecs_t timestamp) {
631 mInterceptor->saveVSyncEvent(timestamp);
632 });
633
634 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
635 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
636 mSfConnectionHandle.get());
637
638 if (mUse90Hz) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 mPhaseOffsets->setRefreshRateType(
640 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800642
Steven Thomasb02664d2017-07-26 18:48:28 -0700643 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700644 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700645 renderEngineFeature |= (useColorManagement ?
646 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700647 renderEngineFeature |= (useContextPriority ?
648 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700649
650 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700651 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700652 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700653 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700654
655 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
656 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700657 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
658 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800659 // Process any initial hotplug and resulting display changes.
660 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 const auto display = getDefaultDisplayDeviceLocked();
662 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700663 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800665
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700667 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700668 // This callback is called from the vr flinger dispatch thread. We
669 // need to call signalTransaction(), which requires holding
670 // mStateLock when we're not on the main thread. Acquiring
671 // mStateLock from the vr flinger dispatch thread might trigger a
672 // deadlock in surface flinger (see b/66916578), so post a message
673 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700675 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
676 mVrFlingerRequestsDisplay = requestDisplay;
677 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
681 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 .value_or(0),
684 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (!mVrFlinger) {
686 ALOGE("Failed to start vrflinger");
687 }
688 }
689
Mathias Agopian92a979a2012-08-02 18:32:23 -0700690 // initialize our drawing state
691 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700692
Andy McFadden13a082e2012-08-24 10:16:42 -0700693 // set initial conditions (e.g. unblank default device)
694 initializeDisplays();
695
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700696 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700699
700 const bool presentFenceReliable =
701 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
702 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703
704 if (mStartPropertySetThread->Start() != NO_ERROR) {
705 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707
Ana Krulecc2870422019-01-29 19:00:58 -0800708 mScheduler->setExpiredIdleTimerCallback([this] {
709 Mutex::Autolock lock(mStateLock);
710 setRefreshRateTo(RefreshRateType::DEFAULT);
711 });
712 mScheduler->setResetIdleTimerCallback([this] {
713 Mutex::Autolock lock(mStateLock);
714 setRefreshRateTo(RefreshRateType::PERFORMANCE);
715 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800716
Ana Krulecc2870422019-01-29 19:00:58 -0800717 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
718 *display->getId()),
719 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800736
737 property_get("persist.sys.sf.color_mode", value, "0");
738 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700739}
740
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Start boot animation service by setting a property mailbox
743 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 if (mStartPropertySetThread->join() != NO_ERROR) {
747 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700752 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700756 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760
Jamie Gennis582270d2011-08-17 18:19:00 -0700761bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800763 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800764 return authenticateSurfaceTextureLocked(bufferProducer);
765}
766
767bool SurfaceFlinger::authenticateSurfaceTextureLocked(
768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800769 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800770 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800771}
772
Brian Anderson6b376712017-04-04 10:51:39 -0700773status_t SurfaceFlinger::getSupportedFrameTimestamps(
774 std::vector<FrameEvent>* outSupported) const {
775 *outSupported = {
776 FrameEvent::REQUESTED_PRESENT,
777 FrameEvent::ACQUIRE,
778 FrameEvent::LATCH,
779 FrameEvent::FIRST_REFRESH_START,
780 FrameEvent::LAST_REFRESH_START,
781 FrameEvent::GPU_COMPOSITION_DONE,
782 FrameEvent::DEQUEUE_READY,
783 FrameEvent::RELEASE,
784 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700787 if (!getHwComposer().hasCapability(
788 HWC2::Capability::PresentFenceIsNotReliable)) {
789 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
790 }
791 return NO_ERROR;
792}
793
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800794status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
795 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 return BAD_VALUE;
798 }
799
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800800 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700801 if (!displayId) {
802 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700803 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804
Mathias Agopian8b736f12012-08-13 17:54:26 -0700805 // TODO: Not sure if display density should handled by SF any longer
806 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700807 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700809 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800810 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 }
813 return density;
814 }
815 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700816 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("ro.sf.lcd_density"); }
820 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 DisplayInfo info = DisplayInfo();
826
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 float xdpi = hwConfig->getDpiX();
828 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700830 info.w = hwConfig->getWidth();
831 info.h = hwConfig->getHeight();
832 // Default display viewport to display width and height
833 info.viewportW = info.w;
834 info.viewportH = info.h;
835
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800836 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 // The density of the device is provided by a build property
838 float density = Density::getBuildDensity() / 160.0f;
839 if (density == 0) {
840 // the build doesn't provide a density -- this is wrong!
841 // use xdpi instead
842 ALOGE("ro.sf.lcd_density must be defined as a build property");
843 density = xdpi / 160.0f;
844 }
845 if (Density::getEmuDensity()) {
846 // if "qemu.sf.lcd_density" is specified, it overrides everything
847 xdpi = ydpi = density = Density::getEmuDensity();
848 density /= 160.0f;
849 }
850 info.density = density;
851
852 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700853 const auto display = getDefaultDisplayDeviceLocked();
854 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855
856 // This is for screenrecord
857 const Rect viewport = display->getViewport();
858 if (viewport.isValid()) {
859 info.viewportW = uint32_t(viewport.getWidth());
860 info.viewportH = uint32_t(viewport.getHeight());
861 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 } else {
863 // TODO: where should this value come from?
864 static const int TV_DENSITY = 213;
865 info.density = TV_DENSITY / 160.0f;
866 info.orientation = 0;
867 }
868
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800872 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800886 info.presentationDeadline =
887 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800892 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700893 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800894 std::swap(info.w, info.h);
895 }
896
Michael Wright28f24d02016-07-12 13:30:53 -0700897 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700898 }
899
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 return NO_ERROR;
901}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
904 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 return BAD_VALUE;
906 }
907
Ana Krulecc2870422019-01-29 19:00:58 -0800908 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700909 return NO_ERROR;
910}
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
913 const auto display = getDisplayDevice(displayToken);
914 if (!display) {
915 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800916 return BAD_VALUE;
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
923 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800924
Ana Krulec7d1d6832018-12-27 11:10:09 -0800925 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 // Lock is acquired by setRefreshRateTo.
927 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800928 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
929 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
930 return;
931 }
932
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933 // Lock is acquired by setRefreshRateTo.
934 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935 if (!display) {
936 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
937 displayToken.get());
938 return;
939 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700940 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800941 ALOGW("Attempt to set active config %d for virtual display", mode);
942 return;
943 }
944 int currentDisplayPowerMode = display->getPowerMode();
945 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
946 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700947 return;
948 }
949
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800950 // Don't check against the current mode yet. Worst case we set the desired
951 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800952 std::lock_guard<std::mutex> lock(mActiveConfigLock);
953 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
954
955 if (!mDesiredActiveConfigChanged) {
956 // This is the first time we set the desired
957 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
958
959 // This will trigger HWC refresh without resetting the idle timer.
960 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 mDesiredActiveConfigChanged = true;
963 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964}
965
966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
967 ATRACE_CALL();
968 postMessageSync(new LambdaMessage(
969 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
970 return NO_ERROR;
971}
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973void SurfaceFlinger::setActiveConfigInternal() {
974 ATRACE_CALL();
975
976 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800977 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978
979 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
980 display->setActiveConfig(mUpcomingActiveConfig.configId);
981
Ana Krulecc2870422019-01-29 19:00:58 -0800982 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
984}
985
Ady Abrahamb838aed2019-02-12 15:30:16 -0800986bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
987 // we may be in the process of changing the active state
988 if (mWaitForNextInvalidate) {
989 mWaitForNextInvalidate = false;
990
991 repaintEverythingForHWC();
992 // We do not want to give another frame to HWC while we are transitioning.
993 return true;
994 }
995
996 if (mCheckPendingFence) {
997 if (mPreviousPresentFence != Fence::NO_FENCE &&
998 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
999 // fence has not signaled yet. wait for the next invalidate
1000 repaintEverythingForHWC();
1001 return true;
1002 }
1003
1004 // We received the present fence from the HWC, so we assume it successfully updated
1005 // the config, hence we update SF.
1006 mCheckPendingFence = false;
1007 setActiveConfigInternal();
1008 }
1009
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010 // Store the local variable to release the lock.
1011 ActiveConfigInfo desiredActiveConfig;
1012 {
1013 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 if (!mDesiredActiveConfigChanged) {
1015 return false;
1016 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017 desiredActiveConfig = mDesiredActiveConfig;
1018 }
1019
1020 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001021 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1022 // display is not valid or we are already in the requested mode
1023 // on both cases there is nothing left to do
1024 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1025 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1026 mDesiredActiveConfigChanged = false;
1027 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1028 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030
1031 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1032 mUpcomingActiveConfig = desiredActiveConfig;
1033 const auto displayId = display->getId();
1034 LOG_ALWAYS_FATAL_IF(!displayId);
1035
1036 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1037 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1038
1039 // we need to submit an empty frame to HWC to start the process
1040 mWaitForNextInvalidate = true;
1041 mCheckPendingFence = true;
1042
1043 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001044}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001045
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1047 Vector<ColorMode>* outColorModes) {
1048 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001049 return BAD_VALUE;
1050 }
1051
Peiyong Lina52f0292018-03-14 17:26:31 -07001052 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001053 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001054 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1055
1056 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1057 if (!displayId) {
1058 return NAME_NOT_FOUND;
1059 }
1060
Dominik Laskowski075d3172018-05-24 15:50:06 -07001061 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001062 }
Michael Wright28f24d02016-07-12 13:30:53 -07001063 outColorModes->clear();
1064 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1065
1066 return NO_ERROR;
1067}
1068
Daniel Solomon42d04562019-01-20 21:03:19 -08001069status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1070 ui::DisplayPrimaries &primaries) {
1071 if (!displayToken) {
1072 return BAD_VALUE;
1073 }
1074
1075 // Currently we only support this API for a single internal display.
1076 if (getInternalDisplayToken() != displayToken) {
1077 return BAD_VALUE;
1078 }
1079
1080 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1081 return NO_ERROR;
1082}
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1085 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001086 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001087 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001089}
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001092 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093 Vector<ColorMode> modes;
1094 getDisplayColorModes(displayToken, &modes);
1095 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1096 if (mode < ColorMode::NATIVE || !exists) {
1097 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1098 decodeColorMode(mode).c_str(), mode, displayToken.get());
1099 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001100 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101 const auto display = getDisplayDevice(displayToken);
1102 if (!display) {
1103 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1104 decodeColorMode(mode).c_str(), mode, displayToken.get());
1105 } else if (display->isVirtual()) {
1106 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1107 decodeColorMode(mode).c_str(), mode);
1108 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001109 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1110 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 }
1112 }));
1113
Michael Wright28f24d02016-07-12 13:30:53 -07001114 return NO_ERROR;
1115}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001116
Svetoslavd85084b2014-03-20 10:28:31 -07001117status_t SurfaceFlinger::clearAnimationFrameStats() {
1118 Mutex::Autolock _l(mStateLock);
1119 mAnimFrameTracker.clearStats();
1120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1124 Mutex::Autolock _l(mStateLock);
1125 mAnimFrameTracker.getStats(outStats);
1126 return NO_ERROR;
1127}
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1130 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001131 Mutex::Autolock _l(mStateLock);
1132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133 const auto display = getDisplayDeviceLocked(displayToken);
1134 if (!display) {
1135 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001136 return BAD_VALUE;
1137 }
1138
Peiyong Linfb069302018-04-25 14:34:31 -07001139 // At this point the DisplayDeivce should already be set up,
1140 // meaning the luminance information is already queried from
1141 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001142 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001143 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1144 capabilities.getDesiredMaxLuminance(),
1145 capabilities.getDesiredMaxAverageLuminance(),
1146 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001147
1148 return NO_ERROR;
1149}
1150
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001151status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1152 ui::PixelFormat* outFormat,
1153 ui::Dataspace* outDataspace,
1154 uint8_t* outComponentMask) const {
1155 if (!outFormat || !outDataspace || !outComponentMask) {
1156 return BAD_VALUE;
1157 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001158 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001159 if (!display || !display->getId()) {
1160 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1161 return BAD_VALUE;
1162 }
1163 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1164 outDataspace, outComponentMask);
1165}
1166
Kevin DuBois74e53772018-11-19 10:52:38 -08001167status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1168 bool enable, uint8_t componentMask,
1169 uint64_t maxFrames) const {
1170 const auto display = getDisplayDevice(displayToken);
1171 if (!display || !display->getId()) {
1172 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1173 return BAD_VALUE;
1174 }
1175
1176 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1177 componentMask, maxFrames);
1178}
1179
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001180status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1181 uint64_t maxFrames, uint64_t timestamp,
1182 DisplayedFrameStats* outStats) const {
1183 const auto display = getDisplayDevice(displayToken);
1184 if (!display || !display->getId()) {
1185 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1186 return BAD_VALUE;
1187 }
1188
1189 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1190 outStats);
1191}
1192
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001193status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1194 if (!outSupported) {
1195 return BAD_VALUE;
1196 }
1197 *outSupported = getRenderEngine().supportsProtectedContent();
1198 return NO_ERROR;
1199}
1200
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001201status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1202 bool* outIsWideColorDisplay) const {
1203 if (!displayToken || !outIsWideColorDisplay) {
1204 return BAD_VALUE;
1205 }
1206 Mutex::Autolock _l(mStateLock);
1207 const auto display = getDisplayDeviceLocked(displayToken);
1208 if (!display) {
1209 return BAD_VALUE;
1210 }
1211 *outIsWideColorDisplay = display->hasWideColorGamut();
1212 return NO_ERROR;
1213}
1214
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001216 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001217 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218
Chia-I Wu90f669f2017-10-05 14:24:41 -07001219 if (mInjectVSyncs == enable) {
1220 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001221 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001222
Ana Krulecc2870422019-01-29 19:00:58 -08001223 auto resyncCallback =
1224 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001225
Ana Krulec98b5b242018-08-10 15:03:23 -07001226 // TODO(akrulec): Part of the Injector should be refactored, so that it
1227 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001228 if (enable) {
1229 ALOGV("VSync Injections enabled");
1230 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001231 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001232 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001233 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001234 impl::EventThread::InterceptVSyncsCallback(),
1235 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001237 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001238 } else {
1239 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001240 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1241 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 }
1243
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001244 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001245 }));
1246
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001247 return NO_ERROR;
1248}
1249
1250status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001251 Mutex::Autolock _l(mStateLock);
1252
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001253 if (!mInjectVSyncs) {
1254 ALOGE("VSync Injections not enabled");
1255 return BAD_VALUE;
1256 }
1257 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1258 ALOGV("Injecting VSync inside SurfaceFlinger");
1259 mVSyncInjector->onInjectSyncEvent(when);
1260 }
1261 return NO_ERROR;
1262}
1263
Lloyd Pique755e3192018-01-31 16:46:15 -08001264status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1265 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001266 // Try to acquire a lock for 1s, fail gracefully
1267 const status_t err = mStateLock.timedLock(s2ns(1));
1268 const bool locked = (err == NO_ERROR);
1269 if (!locked) {
1270 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1271 return TIMED_OUT;
1272 }
1273
1274 outLayers->clear();
1275 mCurrentState.traverseInZOrder([&](Layer* layer) {
1276 outLayers->push_back(layer->getLayerDebugInfo());
1277 });
1278
1279 mStateLock.unlock();
1280 return NO_ERROR;
1281}
1282
Peiyong Linc6780972018-10-28 15:24:08 -07001283status_t SurfaceFlinger::getCompositionPreference(
1284 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1285 Dataspace* outWideColorGamutDataspace,
1286 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001287 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001288 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001289 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001290 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001291 return NO_ERROR;
1292}
1293
Dan Stoza84ab9372018-12-17 15:27:57 -08001294status_t SurfaceFlinger::addRegionSamplingListener(
1295 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1296 const sp<IRegionSamplingListener>& /*listener*/) {
1297 return NO_ERROR;
1298}
1299
1300status_t SurfaceFlinger::removeRegionSamplingListener(
1301 const sp<IRegionSamplingListener>& /*listener*/) {
1302 return NO_ERROR;
1303}
1304
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001305// ----------------------------------------------------------------------------
1306
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001307sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1308 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001309 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001310 Mutex::Autolock lock(mStateLock);
1311 return getVsyncPeriod();
1312 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001313
Ana Krulecc2870422019-01-29 19:00:58 -08001314 const auto& handle =
1315 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001316
Ana Krulecc2870422019-01-29 19:00:58 -08001317 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001318}
1319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001321
1322void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324}
1325
1326void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001327 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001328}
1329
1330void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001331 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001332}
1333
1334void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001335 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001336 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001337}
1338
1339status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001340 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001341 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001342}
1343
1344status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001345 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001346 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347 if (res == NO_ERROR) {
1348 msg->wait();
1349 }
1350 return res;
1351}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001352
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001353void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001354 do {
1355 waitForEvent();
1356 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001357}
1358
Dominik Laskowski83b88212018-12-11 13:34:06 -08001359nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001360 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001361 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1362 return 0;
1363 }
1364
1365 const auto config = getHwComposer().getActiveConfig(*displayId);
1366 return config ? config->getVsyncPeriod() : 0;
1367}
1368
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001369void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1370 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001371 ATRACE_NAME("SF onVsync");
1372
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001374 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001375 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 return;
1377 }
1378
Dominik Laskowski075d3172018-05-24 15:50:06 -07001379 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001380 return;
1381 }
1382
Dominik Laskowski075d3172018-05-24 15:50:06 -07001383 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001384 // For now, we don't do anything with external display vsyncs.
1385 return;
1386 }
1387
Ana Krulecc2870422019-01-29 19:00:58 -08001388 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001389}
1390
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001392 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1393 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394}
1395
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001396void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1397 mPhaseOffsets->setRefreshRateType(refreshRate);
1398
1399 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1400 mVsyncModulator.setPhaseOffsets(early, gl, late);
1401
1402 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001403 return;
1404 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001405
Ana Krulec7d1d6832018-12-27 11:10:09 -08001406 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1407 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1408 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1409 // refresh cycle.
1410
1411 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001412 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001413 if (currentVsyncPeriod == 0) {
1414 return;
1415 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001416
Ana Krulec7d1d6832018-12-27 11:10:09 -08001417 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1418 // floating numbers.
1419 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001420 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1421 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001422 if (std::abs(currentFps - newFps) <= 1) {
1423 return;
1424 }
1425
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001426 const auto displayId = getInternalDisplayIdLocked();
1427 LOG_ALWAYS_FATAL_IF(!displayId);
1428
1429 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001430 for (int i = 0; i < configs.size(); i++) {
1431 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1432 if (vsyncPeriod == 0) {
1433 continue;
1434 }
1435 const float fps = 1e9 / vsyncPeriod;
1436 // TODO(b/113612090): There should be a better way at determining which config
1437 // has the right refresh rate.
1438 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001439 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001440 }
1441 }
1442}
1443
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001444void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001445 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001446 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001447 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448
Lloyd Piqueba04e622017-12-14 17:11:26 -08001449 // Ignore events that do not have the right sequenceId.
1450 if (sequenceId != getBE().mComposerSequenceId) {
1451 return;
1452 }
1453
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 // Only lock if we're not on the main thread. This function is normally
1455 // called on a hwbinder thread, but for the primary display it's called on
1456 // the main thread with the state lock already held, so don't attempt to
1457 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001458 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001459
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001461
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001462 if (std::this_thread::get_id() == mMainThreadId) {
1463 // Process all pending hot plug events immediately if we are on the main thread.
1464 processDisplayHotplugEventsLocked();
1465 }
1466
Lloyd Piqueba04e622017-12-14 17:11:26 -08001467 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001468}
1469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001471 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001475 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001476}
1477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001478void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001479 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001481 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001482 getHwComposer().setVsyncEnabled(*displayId,
1483 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1484 }
Mathias Agopian86303202012-07-24 22:46:10 -07001485}
1486
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001487// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001488void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001489 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001490 // Clear the drawing state so that the logic inside of
1491 // handleTransactionLocked will fire. It will determine the delta between
1492 // mCurrentState and mDrawingState and re-apply all changes when we make the
1493 // transition.
1494 mDrawingState.displays.clear();
1495 mDisplays.clear();
1496}
1497
Steven Thomas050b2c82017-03-06 11:45:16 -08001498void SurfaceFlinger::updateVrFlinger() {
1499 if (!mVrFlinger)
1500 return;
1501 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001502 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001503 return;
1504 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001505
Lloyd Pique441d5042018-10-18 16:49:51 -07001506 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 ALOGE("Vr flinger is only supported for remote hardware composer"
1508 " service connections. Ignoring request to transition to vr"
1509 " flinger.");
1510 mVrFlingerRequestsDisplay = false;
1511 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001512 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001513
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001514 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001515
Steven Thomas0123ac62018-07-12 11:32:34 -07001516 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001517 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001518
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001519 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001520
1521 // Clear out all the output layers from the composition engine for all
1522 // displays before destroying the hardware composer interface. This ensures
1523 // any HWC layers are destroyed through that interface before it becomes
1524 // invalid.
1525 for (const auto& [token, displayDevice] : mDisplays) {
1526 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1527 compositionengine::Output::OutputLayers());
1528 }
1529
Steven Thomas0123ac62018-07-12 11:32:34 -07001530 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1531 // called below. Clear the reference now so we don't accidentally use it
1532 // later.
1533 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001534
Steven Thomasb02664d2017-07-26 18:48:28 -07001535 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001537 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001538
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 // Delete the current instance before creating the new one
1541 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1542 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1543 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1544 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545
Lloyd Pique441d5042018-10-18 16:49:51 -07001546 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001547 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001548
1549 if (vrFlingerRequestsDisplay) {
1550 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001551 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552
1553 mVisibleRegionsDirty = true;
1554 invalidateHwcGeometry();
1555
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001556 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001557 display = getDefaultDisplayDeviceLocked();
1558 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001559 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001560
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001562 const nsecs_t vsyncPeriod = getVsyncPeriod();
1563 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001564
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001565 // The present fences returned from vr_hwc are not an accurate
1566 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001567 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568
Steven Thomasb02664d2017-07-26 18:48:28 -07001569 // Use phase of 0 since phase is not known.
1570 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001571 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001572 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001573
Ana Krulecc2870422019-01-29 19:00:58 -08001574 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001575
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001576 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578}
1579
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001581 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001582 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001583 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001584 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001585 break;
1586 }
1587
Ana Krulecc2870422019-01-29 19:00:58 -08001588 // This call is made each time SF wakes up and creates a new frame.
1589 mScheduler->incrementFrameCounter();
1590
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001591 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1592 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001593 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001594 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001595 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001596 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001597 if (mPropagateBackpressure) {
1598 signalLayerUpdate();
1599 break;
1600 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001601 }
Dan Stoza50182882016-07-08 12:02:20 -07001602
Steven Thomas050b2c82017-03-06 11:45:16 -08001603 // Now that we're going to make it to the handleMessageTransaction()
1604 // call below it's safe to call updateVrFlinger(), which will
1605 // potentially trigger a display handoff.
1606 updateVrFlinger();
1607
Dan Stoza6b9454d2014-11-07 16:00:59 -08001608 bool refreshNeeded = handleMessageTransaction();
1609 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001610
1611 updateCursorAsync();
1612 updateInputFlinger();
1613
Dan Stoza58784442014-12-02 16:58:17 -08001614 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001615 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001616 // Signal a refresh if a transaction modified the window state,
1617 // a new buffer was latched, or if HWC has requested a full
1618 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001619 signalRefresh();
1620 }
1621 break;
1622 }
1623 case MessageQueue::REFRESH: {
1624 handleMessageRefresh();
1625 break;
1626 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001627 }
1628}
1629
Dan Stoza6b9454d2014-11-07 16:00:59 -08001630bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001631 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001632
1633 // Apply any ready transactions in the queues if there are still transactions that have not been
1634 // applied, wake up during the next vsync period and check again
1635 bool transactionNeeded = false;
1636 if (!flushTransactionQueues()) {
1637 transactionNeeded = true;
1638 }
1639
Mathias Agopian4fec8732012-06-29 14:12:52 -07001640 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001641 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001642 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001643
1644 if (transactionNeeded) {
1645 setTransactionFlags(eTransactionNeeded);
1646 }
1647
1648 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001649}
1650
Mathias Agopian4fec8732012-06-29 14:12:52 -07001651void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001653
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001654 mRefreshPending = false;
1655
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001656 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001657 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001658 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001659 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001660 for (const auto& [token, display] : mDisplays) {
1661 beginFrame(display);
1662 prepareFrame(display);
1663 doDebugFlashRegions(display, repaintEverything);
1664 doComposition(display, repaintEverything);
1665 }
1666
Adrian Roos1e1a1282017-11-01 19:05:31 +01001667 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001668 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001669
1670 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001671 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001672
Dan Stozabfbffeb2016-07-21 14:49:33 -07001673 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001674 for (const auto& [token, displayDevice] : mDisplays) {
1675 auto display = displayDevice->getCompositionDisplay();
1676 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001677 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001678 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001679 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001680
Jorim Jaggi90535212018-05-23 23:44:06 +02001681 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001682
David Sodman7e4ae112018-02-09 15:02:28 -08001683 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001684
1685 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001686}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688
1689bool SurfaceFlinger::handleMessageInvalidate() {
1690 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001691 bool refreshNeeded = handlePageFlip();
1692
Vishnu Nair4351ad52019-02-11 14:13:02 -08001693 if (mVisibleRegionsDirty) {
1694 computeLayerBounds();
1695 }
1696
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001697 for (auto& layer : mLayersPendingRefresh) {
1698 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001699 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001700 invalidateLayerStack(layer, visibleReg);
1701 }
1702 mLayersPendingRefresh.clear();
1703 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001704}
1705
David Sodman79bba0e2018-08-05 18:07:49 -07001706void SurfaceFlinger::calculateWorkingSet() {
1707 ATRACE_CALL();
1708 ALOGV(__FUNCTION__);
1709
David Sodman79bba0e2018-08-05 18:07:49 -07001710 // build the h/w work list
1711 if (CC_UNLIKELY(mGeometryInvalid)) {
1712 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001713 for (const auto& [token, displayDevice] : mDisplays) {
1714 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001715 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001716 if (!displayId) {
1717 continue;
1718 }
David Sodman79bba0e2018-08-05 18:07:49 -07001719
Lloyd Pique32cbe282018-10-19 13:09:22 -07001720 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001721 for (size_t i = 0; i < currentLayers.size(); i++) {
1722 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001723
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001724 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001725 layer->forceClientComposition(displayDevice);
1726 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001727 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001728
Lloyd Pique32cbe282018-10-19 13:09:22 -07001729 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001730 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001731 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 }
David Sodman79bba0e2018-08-05 18:07:49 -07001733 }
1734 }
1735 }
1736
1737 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001738 for (const auto& [token, displayDevice] : mDisplays) {
1739 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001740 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001742 continue;
1743 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001744 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001745
1746 if (mDrawingState.colorMatrixChanged) {
1747 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001748 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001749 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001750 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001751 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001752 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1753 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001754 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001755 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001756 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1757 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001758 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001759 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001760 }
1761
Peiyong Lind3788632018-09-18 16:01:31 -07001762 // TODO(b/111562338) remove when composer 2.3 is shipped.
1763 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001764 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001765 }
1766
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001767 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001768 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001769 }
1770
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001771 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001772 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001773 layer->setCompositionType(displayDevice,
1774 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001775 continue;
1776 }
1777
Lloyd Pique32cbe282018-10-19 13:09:22 -07001778 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001779 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001780 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001781 }
1782
Peiyong Lin13effd12018-07-24 17:01:47 -07001783 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001784 ColorMode colorMode;
1785 Dataspace dataSpace;
1786 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001787 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001788 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001789 }
1790 }
1791
1792 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001793
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001794 for (const auto& [token, displayDevice] : mDisplays) {
1795 auto display = displayDevice->getCompositionDisplay();
1796 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001797 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001798 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1799 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1800 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001801 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001802 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001803 }
1804 }
David Sodman79bba0e2018-08-05 18:07:49 -07001805}
1806
Lloyd Pique32cbe282018-10-19 13:09:22 -07001807void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1808 bool repaintEverything) {
1809 auto display = displayDevice->getCompositionDisplay();
1810 const auto& displayState = display->getState();
1811
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812 // is debugging enabled
1813 if (CC_LIKELY(!mDebugRegion))
1814 return;
1815
Lloyd Pique32cbe282018-10-19 13:09:22 -07001816 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001817 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001818 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001819 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001820 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001821 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001822 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001824 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825 }
1826 }
1827
Lloyd Pique32cbe282018-10-19 13:09:22 -07001828 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829
1830 if (mDebugRegion > 1) {
1831 usleep(mDebugRegion * 1000);
1832 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001833
Lloyd Pique32cbe282018-10-19 13:09:22 -07001834 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001835}
1836
Adrian Roos1e1a1282017-11-01 19:05:31 +01001837void SurfaceFlinger::doTracing(const char* where) {
1838 ATRACE_CALL();
1839 ATRACE_NAME(where);
1840 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001841 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001842 }
1843}
1844
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001845void SurfaceFlinger::logLayerStats() {
1846 ATRACE_CALL();
1847 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001848 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001849 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001850 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001851 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001852 }
1853 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001854
1855 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001856 }
1857}
1858
David Sodman2b406362017-12-15 13:33:47 -08001859void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 ATRACE_CALL();
1862 ALOGV("preComposition");
1863
David Sodman2b406362017-12-15 13:33:47 -08001864 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1865
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001867 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001868 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001869 needExtraInvalidate = true;
1870 }
Robert Carr2047fae2016-11-28 14:09:09 -08001871 });
1872
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 if (needExtraInvalidate) {
1874 signalLayerUpdate();
1875 }
1876}
1877
Ana Krulece588e312018-09-18 12:32:24 -07001878void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1879 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001880 // Update queue of past composite+present times and determine the
1881 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001882 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001883 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001884 while (!getBE().mCompositePresentTimes.empty()) {
1885 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001886 // Cached values should have been updated before calling this method,
1887 // which helps avoid duplicate syscalls.
1888 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1889 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1890 break;
1891 }
1892 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001893 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001894 }
1895
1896 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001897 while (getBE().mCompositePresentTimes.size() > 16) {
1898 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 }
1900
Ana Krulece588e312018-09-18 12:32:24 -07001901 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001902}
1903
Ana Krulece588e312018-09-18 12:32:24 -07001904void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1905 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001906 // Integer division and modulo round toward 0 not -inf, so we need to
1907 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001908 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1909 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1910 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911
Ana Krulec757f63a2019-01-25 10:46:18 -08001912 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001913 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001914 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001915 }
1916
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917 // Snap the latency to a value that removes scheduling jitter from the
1918 // composition and present times, which often have >1ms of jitter.
1919 // Reducing jitter is important if an app attempts to extrapolate
1920 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001921 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001922 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001923 nsecs_t bias = stats.vsyncPeriod / 2;
1924 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1925 nsecs_t snappedCompositeToPresentLatency =
1926 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927
David Sodman99974d22017-11-28 12:04:33 -08001928 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001929 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1930 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001931 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001932}
1933
Ady Abraham8164d482019-01-11 14:47:59 -08001934// debug patch for b/119477596 - add stack guards to catch stack
1935// corruptions and disable clang optimizations.
1936// The code below is temporary and planned to be removed once stack
1937// corruptions are found.
1938#pragma clang optimize off
1939class StackGuard {
1940public:
1941 StackGuard(const char* name, const char* func, int line) {
1942 guarders.reserve(MIN_CAPACITY);
1943 guarders.push_back({this, name, func, line});
1944 validate();
1945 }
1946 ~StackGuard() {
1947 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1948 if (i->guard == this) {
1949 guarders.erase(i);
1950 break;
1951 }
1952 }
1953 }
1954
1955 static void validate() {
1956 for (const auto& guard : guarders) {
1957 if (guard.guard->cookie != COOKIE_VALUE) {
1958 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1959 CallStack stack(LOG_TAG);
1960 abort();
1961 }
1962 }
1963 }
1964
1965private:
1966 uint64_t cookie = COOKIE_VALUE;
1967 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1968 static constexpr size_t MIN_CAPACITY = 16;
1969
1970 struct GuarderElement {
1971 StackGuard* guard;
1972 const char* name;
1973 const char* func;
1974 int line;
1975 };
1976
1977 static std::vector<GuarderElement> guarders;
1978};
1979std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1980
1981#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1982
1983#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001984void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001985{
Ady Abraham8164d482019-01-11 14:47:59 -08001986 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001987 ATRACE_CALL();
1988 ALOGV("postComposition");
1989
Brian Anderson3546a3f2016-07-14 11:51:14 -07001990 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001991 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001992 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001993 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001994 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001995 }
Ady Abraham8164d482019-01-11 14:47:59 -08001996 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001997
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001998 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001999 const auto displayDevice = getDefaultDisplayDeviceLocked();
2000 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002001
David Sodman73beded2017-11-15 11:56:06 -08002002 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002003 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002004 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2005
Lloyd Pique32cbe282018-10-19 13:09:22 -07002006 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002008 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2009 ->getRenderSurface()
2010 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002011 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012 } else {
2013 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2014 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002015
Ady Abraham8164d482019-01-11 14:47:59 -08002016 ASSERT_ON_STACK_GUARD();
2017
David Sodman73beded2017-11-15 11:56:06 -08002018 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002019 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2020 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002021 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002022 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002023 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024
Ana Krulece588e312018-09-18 12:32:24 -07002025 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002027 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028
Ady Abraham8164d482019-01-11 14:47:59 -08002029 ASSERT_ON_STACK_GUARD();
2030
David Sodman2b406362017-12-15 13:33:47 -08002031 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032 // when we started doing work for this frame, but that should be okay
2033 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002034 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002035 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002036 DEFINE_STACK_GUARD(compositorTiming);
2037
Brian Andersond0010582017-03-07 13:20:31 -08002038 {
David Sodman99974d22017-11-28 12:04:33 -08002039 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002041 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002042
2043 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002044 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002045
Robert Carr2047fae2016-11-28 14:09:09 -08002046 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002047 bool frameLatched =
2048 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2049 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002050 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002051 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002052 recordBufferingStats(layer->getName().string(),
2053 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002054 }
Ady Abraham8164d482019-01-11 14:47:59 -08002055 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002056 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002057
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002058 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002060 mScheduler->addPresentFence(presentFenceTime);
2061 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002062 }
2063
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002064 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002065 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2066 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002067 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002068 }
2069 }
2070
Ady Abraham8164d482019-01-11 14:47:59 -08002071 ASSERT_ON_STACK_GUARD();
2072
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002073 if (mAnimCompositionPending) {
2074 mAnimCompositionPending = false;
2075
Brian Anderson4e606e32017-03-16 15:34:57 -07002076 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002077 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002078 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002079
2080 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002081 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082 // The HWC doesn't support present fences, so use the refresh
2083 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 const nsecs_t presentTime =
2085 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002086 DEFINE_STACK_GUARD(presentTime);
2087
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002089 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002090 }
2091 mAnimFrameTracker.advanceFrame();
2092 }
Dan Stozab90cf072015-03-05 11:05:59 -08002093
Ady Abraham8164d482019-01-11 14:47:59 -08002094 ASSERT_ON_STACK_GUARD();
2095
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002096 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002097 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002098 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002099 }
2100
Ady Abraham8164d482019-01-11 14:47:59 -08002101 ASSERT_ON_STACK_GUARD();
2102
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002103 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002104
Ady Abraham8164d482019-01-11 14:47:59 -08002105 ASSERT_ON_STACK_GUARD();
2106
Lloyd Pique32cbe282018-10-19 13:09:22 -07002107 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2108 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002109 return;
2110 }
2111
2112 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002113 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002114 if (mHasPoweredOff) {
2115 mHasPoweredOff = false;
2116 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002117 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002118 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002119 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002120 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002121 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2122 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002123 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002124 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002125 }
David Sodman4a36e932017-11-07 14:29:47 -08002126 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002127
2128 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002129 }
David Sodman4a36e932017-11-07 14:29:47 -08002130 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002131 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002132
2133 {
2134 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002135 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002136 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002137 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002138 if (refillCount > 0) {
2139 const size_t offset = mTexturePool.size();
2140 mTexturePool.resize(mTexturePoolSize);
2141 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2142 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2143 }
Ady Abraham8164d482019-01-11 14:47:59 -08002144 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002145 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002146
Marissa Wallfda30bb2018-10-12 11:34:28 -07002147 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002148 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002149
2150 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002151}
Ady Abraham8164d482019-01-11 14:47:59 -08002152#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153
Vishnu Nair4351ad52019-02-11 14:13:02 -08002154void SurfaceFlinger::computeLayerBounds() {
2155 for (const auto& pair : mDisplays) {
2156 const auto& displayDevice = pair.second;
2157 const auto display = displayDevice->getCompositionDisplay();
2158 for (const auto& layer : mDrawingState.layersSortedByZ) {
2159 // only consider the layers on the given layer stack
2160 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002161 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002162 }
2163
2164 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2165 }
2166 }
2167}
2168
Mathias Agopiancd60f992012-08-16 16:28:27 -07002169void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 ATRACE_CALL();
2171 ALOGV("rebuildLayerStacks");
2172
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002173 // We need to clear these out now as these may be holding on to a
2174 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2175 // also holds a reference. When the set of visible layers is recomputed,
2176 // some layers may be destroyed if the only thing keeping them alive was
2177 // that list of visible layers associated with each display. The layer
2178 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2179 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2180 for (const auto& [token, display] : mDisplays) {
2181 getBE().mCompositionInfo[token].clear();
2182 }
2183
Mathias Agopiancd60f992012-08-16 16:28:27 -07002184 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002185 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002186 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002187 mVisibleRegionsDirty = false;
2188 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002189
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002190 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002191 const auto& displayDevice = pair.second;
2192 auto display = displayDevice->getCompositionDisplay();
2193 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002194 Region opaqueRegion;
2195 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002196 compositionengine::Output::OutputLayers layersSortedByZ;
2197 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002198 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002199 const ui::Transform& tr = displayState.transform;
2200 const Rect bounds = displayState.bounds;
2201 if (displayState.isEnabled) {
2202 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002203
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002205 auto compositionLayer = layer->getCompositionLayer();
2206 if (compositionLayer == nullptr) {
2207 return;
2208 }
2209
Lloyd Pique32cbe282018-10-19 13:09:22 -07002210 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002211 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2212 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2213
Lloyd Pique07e33212018-12-18 16:33:37 -08002214 bool needsOutputLayer = false;
2215
Lloyd Piqueef36b002019-01-23 17:52:04 -08002216 if (display->belongsInOutput(layer->getLayerStack(),
2217 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002218 Region drawRegion(tr.transform(
2219 layer->visibleNonTransparentRegion));
2220 drawRegion.andSelf(bounds);
2221 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002222 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002223 }
Chia-I Wu83806892017-11-16 10:50:20 -08002224 }
2225
Lloyd Pique07e33212018-12-18 16:33:37 -08002226 if (needsOutputLayer) {
2227 layersSortedByZ.emplace_back(
2228 display->getOrCreateOutputLayer(displayId, compositionLayer,
2229 layerFE));
2230 deprecated_layersSortedByZ.add(layer);
2231
2232 auto& outputLayerState = layersSortedByZ.back()->editState();
2233 outputLayerState.visibleRegion =
2234 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2235 } else if (displayId) {
2236 // For layers that are being removed from a HWC display,
2237 // and that have queued frames, add them to a a list of
2238 // released layers so we can properly set a fence.
2239 bool hasExistingOutputLayer =
2240 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2241 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2242 mLayersWithQueuedFrames.cend(),
2243 layer) != mLayersWithQueuedFrames.cend();
2244
2245 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002246 layersNeedingFences.add(layer);
2247 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002248 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002249 });
2250 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002251
2252 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2253
2254 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 displayDevice->setLayersNeedingFences(layersNeedingFences);
2256
2257 Region undefinedRegion{bounds};
2258 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2259
2260 display->editState().undefinedRegion = undefinedRegion;
2261 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002262 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002263 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002264}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002265
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002266// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002267// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002268// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002270// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002271// The returned HDR data space is one of
2272// - Dataspace::UNKNOWN
2273// - Dataspace::BT2020_HLG
2274// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2276 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002277 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278 *outHdrDataSpace = Dataspace::UNKNOWN;
2279
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002281 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002282 case Dataspace::V0_SCRGB:
2283 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002284 case Dataspace::BT2020:
2285 case Dataspace::BT2020_ITU:
2286 case Dataspace::BT2020_LINEAR:
2287 case Dataspace::DISPLAY_BT2020:
2288 bestDataSpace = Dataspace::DISPLAY_BT2020;
2289 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002291 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002292 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002293 case Dataspace::BT2020_PQ:
2294 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002295 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002298 case Dataspace::BT2020_HLG:
2299 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002300 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301 // When there's mixed PQ content and HLG content, we set the HDR
2302 // data space to be BT2020_PQ and convert HLG to PQ.
2303 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2304 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002305 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002306 break;
2307 default:
2308 break;
2309 }
Romain Guy54f154a2017-10-24 21:40:32 +01002310 }
2311
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002312 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002313}
2314
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002316void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2317 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2319 *outMode = ColorMode::NATIVE;
2320 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002321 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002323 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002324
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002328 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2329
Peiyong Lina3ea5592019-02-10 14:45:00 -08002330 switch (mForceColorMode) {
2331 case ColorMode::SRGB:
2332 bestDataSpace = Dataspace::V0_SRGB;
2333 break;
2334 case ColorMode::DISPLAY_P3:
2335 bestDataSpace = Dataspace::DISPLAY_P3;
2336 break;
2337 default:
2338 break;
2339 }
2340
Peiyong Lindfde5112018-06-05 10:58:41 -07002341 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002342 const bool isHdr =
2343 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002344 if (isHdr) {
2345 bestDataSpace = hdrDataSpace;
2346 }
2347
Chia-I Wu0d711262018-05-21 15:19:35 -07002348 RenderIntent intent;
2349 switch (mDisplayColorSetting) {
2350 case DisplayColorSetting::MANAGED:
2351 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002352 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002353 break;
2354 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002355 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002356 break;
2357 default: // vendor display color setting
2358 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2359 break;
2360 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002361
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002362 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002363}
2364
Lloyd Pique32cbe282018-10-19 13:09:22 -07002365void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2366 auto display = displayDevice->getCompositionDisplay();
2367 const auto& displayState = display->getState();
2368
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002369 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002370 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2371 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002372
David Sodmanfa9b2af2017-12-24 13:28:59 -08002373 // If nothing has changed (!dirty), don't recompose.
2374 // If something changed, but we don't currently have any visible layers,
2375 // and didn't when we last did a composition, then skip it this time.
2376 // The second rule does two things:
2377 // - When all layers are removed from a display, we'll emit one black
2378 // frame, then nothing more until we get new layers.
2379 // - When a display is created with a private layer stack, we won't
2380 // emit any black frames until a layer is added to the layer stack.
2381 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002382
Dominik Laskowski075d3172018-05-24 15:50:06 -07002383 const char flagPrefix[] = {'-', '+'};
2384 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002385 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2386 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2387 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2388 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002389
Lloyd Pique31cb2942018-10-19 17:23:03 -07002390 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002393 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002394 }
2395}
2396
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2398 auto display = displayDevice->getCompositionDisplay();
2399 const auto& displayState = display->getState();
2400
2401 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002402 return;
David Sodman2b406362017-12-15 13:33:47 -08002403 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002404
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002405 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002408}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002409
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002411 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 ALOGV("doComposition");
2413
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414 auto display = displayDevice->getCompositionDisplay();
2415 const auto& displayState = display->getState();
2416
2417 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002419 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002420
David Sodmanfa9b2af2017-12-24 13:28:59 -08002421 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002423
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002425 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002427 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002428}
2429
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430void SurfaceFlinger::postFrame()
2431{
2432 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 const auto display = getDefaultDisplayDeviceLocked();
2434 if (display && getHwComposer().isConnected(*display->getId())) {
2435 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002436 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2437 logFrameStats();
2438 }
2439 }
2440}
2441
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002443 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 auto display = displayDevice->getCompositionDisplay();
2447 const auto& displayState = display->getState();
2448 const auto displayId = display->getId();
2449
David Sodmanfa9b2af2017-12-24 13:28:59 -08002450 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002451
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 if (displayId) {
2454 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002455 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002456 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002458 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002459
Chia-I Wu7b549592017-11-15 09:14:57 -08002460 // The layer buffer from the previous frame (if any) is released
2461 // by HWC only when the release fence from this frame (if any) is
2462 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002463 if (displayId && layer->hasHwcLayer(displayDevice)) {
2464 releaseFence =
2465 getHwComposer().getLayerReleaseFence(*displayId,
2466 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002467 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002468
2469 // If the layer was client composited in the previous frame, we
2470 // need to merge with the previous client target acquire fence.
2471 // Since we do not track that, always merge with the current
2472 // client target acquire fence when it is available, even though
2473 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002474 if (layer->getCompositionType(displayDevice) ==
2475 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002476 releaseFence =
2477 Fence::merge("LayerRelease", releaseFence,
2478 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002479 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002480
David Sodman15094112018-10-11 09:39:37 -07002481 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 }
Chia-I Wu83806892017-11-16 10:50:20 -08002483
2484 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002486 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002487 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002489 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002490 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002491 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002492 }
2493 }
2494
Dominik Laskowski075d3172018-05-24 15:50:06 -07002495 if (displayId) {
2496 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002497 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002498 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499}
2500
Mathias Agopian87baae12012-07-31 12:38:26 -07002501void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502{
Mathias Agopian841cde52012-03-01 15:44:37 -08002503 ATRACE_CALL();
2504
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002505 // here we keep a copy of the drawing state (that is the state that's
2506 // going to be overwritten by handleTransactionLocked()) outside of
2507 // mStateLock so that the side-effects of the State assignment
2508 // don't happen with mStateLock held (which can cause deadlocks).
2509 State drawingState(mDrawingState);
2510
Mathias Agopianca4d3602011-05-19 15:38:14 -07002511 Mutex::Autolock _l(mStateLock);
2512 const nsecs_t now = systemTime();
2513 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514
Mathias Agopianca4d3602011-05-19 15:38:14 -07002515 // Here we're guaranteed that some transaction flags are set
2516 // so we can call handleTransactionLocked() unconditionally.
2517 // We call getTransactionFlags(), which will also clear the flags,
2518 // with mStateLock held to guarantee that mCurrentState won't change
2519 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002520
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002521 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002523 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002524
Mathias Agopianca4d3602011-05-19 15:38:14 -07002525 mLastTransactionTime = systemTime() - now;
2526 mDebugInTransaction = 0;
2527 invalidateHwcGeometry();
2528 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002529}
2530
Lloyd Piqueba04e622017-12-14 17:11:26 -08002531void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2532 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 const std::optional<DisplayIdentificationInfo> info =
2534 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002535
Dominik Laskowski075d3172018-05-24 15:50:06 -07002536 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002537 continue;
2538 }
2539
Lloyd Piqueba04e622017-12-14 17:11:26 -08002540 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002542 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 mPhysicalDisplayTokens[info->id] = new BBinder();
2544 DisplayDeviceState state;
2545 state.displayId = info->id;
2546 state.isSecure = true; // All physical displays are currently considered secure.
2547 state.displayName = info->name;
2548 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2549 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002550 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002551 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002552 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2555 if (index >= 0) {
2556 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2557 mInterceptor->saveDisplayDeletion(state.sequenceId);
2558 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002559 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002561 }
2562
2563 processDisplayChangesLocked();
2564 }
2565
2566 mPendingHotplugEvents.clear();
2567}
2568
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002569void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002570 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2571 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002572}
2573
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002575 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002576 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 const sp<IGraphicBufferProducer>& producer) {
2578 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002579 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002581 creationArgs.isSecure = state.isSecure;
2582 creationArgs.displaySurface = dispSurface;
2583 creationArgs.hasWideColorGamut = false;
2584 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002585
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002586 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002587 creationArgs.isPrimary = isInternalDisplay;
2588
2589 if (useColorManagement && displayId) {
2590 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002591 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002592 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002593 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002594 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002595
Dominik Laskowski7e045462018-05-30 13:02:02 -07002596 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002598 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599 }
tangrobin6753a022018-08-10 10:58:54 +08002600 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 if (displayId) {
2603 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002604 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002606 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607
Lloyd Pique90c115d2018-09-18 21:39:42 -07002608 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002610 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611
Lloyd Pique99d3da52018-01-22 17:48:03 -08002612 // Make sure that composition can never be stalled by a virtual display
2613 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002614 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002615 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2617 }
2618
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 creationArgs.displayInstallOrientation =
2620 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002621
Lloyd Pique99d3da52018-01-22 17:48:03 -08002622 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002623 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624
Lloyd Pique90c115d2018-09-18 21:39:42 -07002625 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626
2627 if (maxFrameBufferAcquiredBuffers >= 3) {
2628 nativeWindowSurface->preallocateBuffers();
2629 }
2630
2631 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002632 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002633 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002635 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002637 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2638 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 if (!state.isVirtual()) {
2640 LOG_ALWAYS_FATAL_IF(!displayId);
2641 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002642 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002644 display->setLayerStack(state.layerStack);
2645 display->setProjection(state.orientation, state.viewport, state.frame);
2646 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649}
2650
Lloyd Pique347200f2017-12-14 17:00:15 -08002651void SurfaceFlinger::processDisplayChangesLocked() {
2652 // here we take advantage of Vector's copy-on-write semantics to
2653 // improve performance by skipping the transaction entirely when
2654 // know that the lists are identical
2655 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2656 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2657 if (!curr.isIdenticalTo(draw)) {
2658 mVisibleRegionsDirty = true;
2659 const size_t cc = curr.size();
2660 size_t dc = draw.size();
2661
2662 // find the displays that were removed
2663 // (ie: in drawing state but not in current state)
2664 // also handle displays that changed
2665 // (ie: displays that are in both lists)
2666 for (size_t i = 0; i < dc;) {
2667 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2668 if (j < 0) {
2669 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002671 // Save display ID before disconnecting.
2672 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002673 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002674
2675 if (!display->isVirtual()) {
2676 LOG_ALWAYS_FATAL_IF(!displayId);
2677 dispatchDisplayHotplugEvent(displayId->value, false);
2678 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002679 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002680
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002681 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 } else {
2683 // this display is in both lists. see if something changed.
2684 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002685 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2687 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2688 if (state_binder != draw_binder) {
2689 // changing the surface is like destroying and
2690 // recreating the DisplayDevice, so we just remove it
2691 // from the drawing state, so that it get re-added
2692 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002694 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002696 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002697 mDrawingState.displays.removeItemsAt(i);
2698 dc--;
2699 // at this point we must loop to the next item
2700 continue;
2701 }
2702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 }
2707 if ((state.orientation != draw[i].orientation) ||
2708 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 }
2711 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 }
2714 }
2715 }
2716 ++i;
2717 }
2718
2719 // find displays that were added
2720 // (ie: in current state but not in drawing state)
2721 for (size_t i = 0; i < cc; i++) {
2722 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2723 const DisplayDeviceState& state(curr[i]);
2724
Lloyd Pique542307f2018-10-19 13:24:08 -07002725 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 sp<IGraphicBufferProducer> producer;
2727 sp<IGraphicBufferProducer> bqProducer;
2728 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002729 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002730
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002732 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 // Virtual displays without a surface are dormant:
2734 // they have external state (layer stack, projection,
2735 // etc.) but no internal state (i.e. a DisplayDevice).
2736 if (state.surface != nullptr) {
2737 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002738 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 int width = 0;
2740 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2741 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2742 int height = 0;
2743 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2744 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2745 int intFormat = 0;
2746 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2747 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002748 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749
Dominik Laskowski075d3172018-05-24 15:50:06 -07002750 displayId =
2751 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 }
2753
2754 // TODO: Plumb requested format back up to consumer
2755
2756 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002757 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 bqProducer, bqConsumer,
2759 state.displayName);
2760
2761 dispSurface = vds;
2762 producer = vds;
2763 }
2764 } else {
2765 ALOGE_IF(state.surface != nullptr,
2766 "adding a supported display, but rendering "
2767 "surface is provided (%p), ignoring it",
2768 state.surface.get());
2769
Dominik Laskowski075d3172018-05-24 15:50:06 -07002770 displayId = state.displayId;
2771 LOG_ALWAYS_FATAL_IF(!displayId);
2772 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002773 producer = bqProducer;
2774 }
2775
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002776 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002778 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002779 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002781 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002783 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002784 }
2785 }
2786 }
2787 }
2788 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002789
2790 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002791}
2792
Mathias Agopian87baae12012-07-31 12:38:26 -07002793void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002794{
Dan Stoza7dde5992015-05-22 09:51:44 -07002795 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002796 mCurrentState.traverseInZOrder([](Layer* layer) {
2797 layer->notifyAvailableFrames();
2798 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002799
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002800 /*
2801 * Traversal of the children
2802 * (perform the transaction for each of them if needed)
2803 */
2804
Mathias Agopian3559b072012-08-15 13:46:03 -07002805 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002806 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002808 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809
2810 const uint32_t flags = layer->doTransaction(0);
2811 if (flags & Layer::eVisibleRegion)
2812 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002813
2814 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002815 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002816 }
Robert Carr2047fae2016-11-28 14:09:09 -08002817 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 }
2819
2820 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002821 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 */
2823
Mathias Agopiane57f2922012-08-09 16:29:12 -07002824 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002825 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002826 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002829 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002830 // The transform hint might have changed for some layers
2831 // (either because a display has changed, or because a layer
2832 // as changed).
2833 //
2834 // Walk through all the layers in currentLayers,
2835 // and update their transform hint.
2836 //
2837 // If a layer is visible only on a single display, then that
2838 // display is used to calculate the hint, otherwise we use the
2839 // default display.
2840 //
2841 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2842 // the hint is set before we acquire a buffer from the surface texture.
2843 //
2844 // NOTE: layer transactions have taken place already, so we use their
2845 // drawing state. However, SurfaceFlinger's own transaction has not
2846 // happened yet, so we must use the current state layer list
2847 // (soon to become the drawing state list).
2848 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002849 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002850 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002851 bool first = true;
2852 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002853 // NOTE: we rely on the fact that layers are sorted by
2854 // layerStack first (so we don't have to traverse the list
2855 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002856 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002857 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002858 currentlayerStack = layerStack;
2859 // figure out if this layerstack is mirrored
2860 // (more than one display) if so, pick the default display,
2861 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002862 hintDisplay = nullptr;
2863 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002864 if (display->getCompositionDisplay()
2865 ->belongsInOutput(layer->getLayerStack(),
2866 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002867 if (hintDisplay) {
2868 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002869 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002870 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002872 }
2873 }
2874 }
2875 }
Chet Haase91d25932013-04-11 15:24:55 -07002876
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002877 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002878 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2879 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002880
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002881 // could be null when this layer is using a layerStack
2882 // that is not visible on any display. Also can occur at
2883 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002885 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002886
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002888 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 if (hintDisplay) {
2890 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002891 }
Robert Carr2047fae2016-11-28 14:09:09 -08002892
2893 first = false;
2894 });
Mathias Agopian84300952012-11-21 16:02:13 -08002895 }
2896
2897
Mathias Agopian3559b072012-08-15 13:46:03 -07002898 /*
2899 * Perform our own transaction if needed
2900 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002901
2902 if (mLayersAdded) {
2903 mLayersAdded = false;
2904 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002905 mVisibleRegionsDirty = true;
2906 }
2907
2908 // some layers might have been removed, so
2909 // we need to update the regions they're exposing.
2910 if (mLayersRemoved) {
2911 mLayersRemoved = false;
2912 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002913 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002915 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002917 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002918 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002919 }
Robert Carr2047fae2016-11-28 14:09:09 -08002920 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 }
2922
Vishnu Nairec0ab382019-02-13 15:32:56 -08002923 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002925}
2926
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002927void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002928 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002929 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002930 return;
2931 }
2932
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002933 if (mVisibleRegionsDirty || mInputInfoChanged) {
2934 mInputInfoChanged = false;
2935 updateInputWindowInfo();
2936 }
2937
2938 executeInputWindowCommands();
2939}
2940
2941void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002942 Vector<InputWindowInfo> inputHandles;
2943
2944 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2945 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002946 // When calculating the screen bounds we ignore the transparent region since it may
2947 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002948 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002949 }
2950 });
2951 mInputFlinger->setInputWindows(inputHandles);
2952}
2953
Vishnu Nairec0ab382019-02-13 15:32:56 -08002954void SurfaceFlinger::commitInputWindowCommands() {
2955 mInputWindowCommands.merge(mPendingInputWindowCommands);
2956 mPendingInputWindowCommands.clear();
2957}
2958
chaviwfbe5d9c2018-12-26 12:23:37 -08002959void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002960 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2961 if (transferTouchFocusCommand.fromToken != nullptr &&
2962 transferTouchFocusCommand.toToken != nullptr &&
2963 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2964 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2965 transferTouchFocusCommand.toToken);
2966 }
2967 }
2968
2969 mInputWindowCommands.clear();
2970}
2971
Riley Andrews03414a12014-07-01 14:22:59 -07002972void SurfaceFlinger::updateCursorAsync()
2973{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002974 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002975 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002976 continue;
2977 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2980 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002981 }
2982 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002983}
2984
chaviw61626f22018-11-15 16:26:27 -08002985void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2986 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002987 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002988 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002989 }
2990 layer->releasePendingBuffer(systemTime());
2991}
2992
Mathias Agopian4fec8732012-06-29 14:12:52 -07002993void SurfaceFlinger::commitTransaction()
2994{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002995 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002997 for (const auto& l : mLayersPendingRemoval) {
2998 recordBufferingStats(l->getName().string(),
2999 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003000
Lloyd Pique07e33212018-12-18 16:33:37 -08003001 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003002 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003003 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003004 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003005 }
3006 mLayersPendingRemoval.clear();
3007 }
3008
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003009 // If this transaction is part of a window animation then the next frame
3010 // we composite should be considered an animation as well.
3011 mAnimCompositionPending = mAnimTransactionPending;
3012
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003014 // clear the "changed" flags in current state
3015 mCurrentState.colorMatrixChanged = false;
3016
Robert Carr1f0a16a2016-10-24 16:27:39 -07003017 mDrawingState.traverseInZOrder([](Layer* layer) {
3018 layer->commitChildList();
3019 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003020 mTransactionPending = false;
3021 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003022 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003023}
3024
Lloyd Pique32cbe282018-10-19 13:09:22 -07003025void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003027 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003028 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003029
Lloyd Pique32cbe282018-10-19 13:09:22 -07003030 auto display = displayDevice->getCompositionDisplay();
3031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 Region aboveOpaqueLayers;
3033 Region aboveCoveredLayers;
3034 Region dirty;
3035
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037
Robert Carr2047fae2016-11-28 14:09:09 -08003038 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003039 // start with the whole surface at its current location
3040 const Layer::State& s(layer->getDrawingState());
3041
Jesse Hall01e29052013-02-19 16:13:35 -08003042 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003043 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003044 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003045 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003046
Mathias Agopianab028732010-03-16 16:41:46 -07003047 /*
3048 * opaqueRegion: area of a surface that is fully opaque.
3049 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003051
3052 /*
3053 * visibleRegion: area of a surface that is visible on screen
3054 * and not fully transparent. This is essentially the layer's
3055 * footprint minus the opaque regions above it.
3056 * Areas covered by a translucent surface are considered visible.
3057 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003059
3060 /*
3061 * coveredRegion: area of a surface that is covered by all
3062 * visible regions above it (which includes the translucent areas).
3063 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003065
Jesse Halla8026d22012-09-25 13:25:04 -07003066 /*
3067 * transparentRegion: area of a surface that is hinted to be completely
3068 * transparent. This is only used to tell when the layer has no visible
3069 * non-transparent regions and can be removed from the layer list. It
3070 * does not affect the visibleRegion of this layer or any layers
3071 * beneath it. The hint may not be correct if apps don't respect the
3072 * SurfaceView restrictions (which, sadly, some don't).
3073 */
3074 Region transparentRegion;
3075
Mathias Agopianab028732010-03-16 16:41:46 -07003076
3077 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003078 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003079 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003080 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003081
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003083 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003084 if (!visibleRegion.isEmpty()) {
3085 // Remove the transparent area from the visible region
3086 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003087 if (tr.preserveRects()) {
3088 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003089 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003090 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003091 // transformation too complex, can't do the
3092 // transparent region optimization.
3093 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 }
Mathias Agopianab028732010-03-16 16:41:46 -07003095 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096
Mathias Agopianab028732010-03-16 16:41:46 -07003097 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003098 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003099 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003100 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003101 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003102 // the opaque region is the layer's footprint
3103 opaqueRegion = visibleRegion;
3104 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 }
3106 }
3107
Robert Carre5f4f692018-01-12 13:12:28 -08003108 if (visibleRegion.isEmpty()) {
3109 layer->clearVisibilityRegions();
3110 return;
3111 }
3112
Mathias Agopianab028732010-03-16 16:41:46 -07003113 // Clip the covered region to the visible region
3114 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3115
3116 // Update aboveCoveredLayers for next (lower) layer
3117 aboveCoveredLayers.orSelf(visibleRegion);
3118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119 // subtract the opaque region covered by the layers above us
3120 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121
3122 // compute this layer's dirty region
3123 if (layer->contentDirty) {
3124 // we need to invalidate the whole region
3125 dirty = visibleRegion;
3126 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003127 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128 layer->contentDirty = false;
3129 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003130 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003131 * the exposed region consists of two components:
3132 * 1) what's VISIBLE now and was COVERED before
3133 * 2) what's EXPOSED now less what was EXPOSED before
3134 *
3135 * note that (1) is conservative, we start with the whole
3136 * visible region but only keep what used to be covered by
3137 * something -- which mean it may have been exposed.
3138 *
3139 * (2) handles areas that were not covered by anything but got
3140 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003141 */
Mathias Agopianab028732010-03-16 16:41:46 -07003142 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003143 const Region oldVisibleRegion = layer->visibleRegion;
3144 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003145 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3146 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 }
3148 dirty.subtractSelf(aboveOpaqueLayers);
3149
3150 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003151 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152
Mathias Agopianab028732010-03-16 16:41:46 -07003153 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003155
Jesse Halla8026d22012-09-25 13:25:04 -07003156 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157 layer->setVisibleRegion(visibleRegion);
3158 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003159 layer->setVisibleNonTransparentRegion(
3160 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003161 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopian87baae12012-07-31 12:38:26 -07003163 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164}
3165
Chia-I Wuab0c3192017-08-01 11:29:00 -07003166void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003167 for (const auto& [token, displayDevice] : mDisplays) {
3168 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003169 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003170 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003171 }
3172 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003173}
3174
Daniel Solomon42d04562019-01-20 21:03:19 -08003175void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3176 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3177 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3178 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3179 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3180 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3181 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3182 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3183 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3184 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3185 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3186 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3187 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3188}
3189
Dan Stoza6b9454d2014-11-07 16:00:59 -08003190bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003192 ALOGV("handlePageFlip");
3193
Brian Andersond6927fb2016-07-23 23:37:30 -07003194 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195
Mathias Agopian4fec8732012-06-29 14:12:52 -07003196 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003197 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003198 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003199
3200 // Store the set of layers that need updates. This set must not change as
3201 // buffers are being latched, as this could result in a deadlock.
3202 // Example: Two producers share the same command stream and:
3203 // 1.) Layer 0 is latched
3204 // 2.) Layer 0 gets a new frame
3205 // 2.) Layer 1 gets a new frame
3206 // 3.) Layer 1 is latched.
3207 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3208 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003209 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003210 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003211 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003212 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003213 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003214 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003215 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003216 } else {
3217 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003218 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003219 } else {
3220 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003221 }
Robert Carr2047fae2016-11-28 14:09:09 -08003222 });
3223
Lloyd Piquef2c79392018-12-20 16:23:33 -08003224 if (!mLayersWithQueuedFrames.empty()) {
3225 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3226 // writes to Layer current state. See also b/119481871
3227 Mutex::Autolock lock(mStateLock);
3228
3229 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003230 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003231 mLayersPendingRefresh.push_back(layer);
3232 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003233 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003234 if (layer->isBufferLatched()) {
3235 newDataLatched = true;
3236 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003237 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003238 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003239
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003240 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003241
3242 // If we will need to wake up at some time in the future to deal with a
3243 // queued frame that shouldn't be displayed during this vsync period, wake
3244 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003245 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003246 signalLayerUpdate();
3247 }
3248
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003249 // enter boot animation on first buffer latch
3250 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3251 ALOGI("Enter boot animation");
3252 mBootStage = BootStage::BOOTANIMATION;
3253 }
3254
Dan Stoza6b9454d2014-11-07 16:00:59 -08003255 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003256 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257}
3258
Mathias Agopianad456f92011-01-13 17:53:01 -08003259void SurfaceFlinger::invalidateHwcGeometry()
3260{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003261 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003262}
3263
Lloyd Pique32cbe282018-10-19 13:09:22 -07003264void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003265 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003266 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003267 // We only need to actually compose the display if:
3268 // 1) It is being handled by hardware composer, which may need this to
3269 // keep its virtual display state machine in sync, or
3270 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003271 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003272 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003273 return;
3274 }
3275
Dan Stoza9e56aa02015-11-02 13:00:03 -08003276 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003277 base::unique_fd readyFence;
3278 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003279
3280 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003281 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282}
3283
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003284bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3285 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003286 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003287 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003288
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289 auto display = displayDevice->getCompositionDisplay();
3290 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003291 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003292
3293 const Region bounds(displayState.bounds);
3294 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003295 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003296 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003297
Peiyong Lind3788632018-09-18 16:01:31 -07003298 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003299 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003300
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003301 renderengine::DisplaySettings clientCompositionDisplay;
3302 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3303 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003304
Dan Stoza9e56aa02015-11-02 13:00:03 -08003305 if (hasClientComposition) {
3306 ALOGV("hasClientComposition");
3307
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003308 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003309
3310 if (buf == nullptr) {
3311 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3312 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003313 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003314 return false;
3315 }
3316
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003317 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3318 clientCompositionDisplay.clip = displayState.scissor;
3319 const ui::Transform& displayTransform = displayState.transform;
3320 mat4 m;
3321 m[0][0] = displayTransform[0][0];
3322 m[0][1] = displayTransform[0][1];
3323 m[0][3] = displayTransform[0][2];
3324 m[1][0] = displayTransform[1][0];
3325 m[1][1] = displayTransform[1][1];
3326 m[1][3] = displayTransform[1][2];
3327 m[3][0] = displayTransform[2][0];
3328 m[3][1] = displayTransform[2][1];
3329 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003330
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003331 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003332
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003333 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003334 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003335 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003336 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003337 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003338 clientCompositionDisplay.outputDataspace = outputDataspace;
3339 clientCompositionDisplay.maxLuminance =
3340 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003341
Lloyd Pique441d5042018-10-18 16:49:51 -07003342 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003343 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003344 getHwComposer()
3345 .hasDisplayCapability(displayId,
3346 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003347
Peiyong Lind3788632018-09-18 16:01:31 -07003348 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003349 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3350 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003351 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003352 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003353 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003354
Mathias Agopian85d751c2012-08-29 16:59:24 -07003355 /*
3356 * and then, render the layers targeted at the framebuffer
3357 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003358
Dan Stoza9e56aa02015-11-02 13:00:03 -08003359 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003360 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003361 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003362 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003363 const Region viewportRegion(displayState.viewport);
3364 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003365 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003366 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003367 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003368 switch (layer->getCompositionType(displayDevice)) {
3369 case Hwc2::IComposerClient::Composition::CURSOR:
3370 case Hwc2::IComposerClient::Composition::DEVICE:
3371 case Hwc2::IComposerClient::Composition::SIDEBAND:
3372 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003373 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003374 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003375 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003376 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003377 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003378 // never clear the very first layer since we're
3379 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003380 renderengine::LayerSettings layerSettings;
3381 Region dummyRegion;
3382 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3383 layerSettings);
3384
3385 if (prepared) {
3386 layerSettings.source.buffer.buffer = nullptr;
3387 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3388 layerSettings.alpha = half(0.0);
3389 layerSettings.disableBlending = true;
3390 clientCompositionLayers.push_back(layerSettings);
3391 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003392 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003393 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003394 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003395 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003396 renderengine::LayerSettings layerSettings;
3397 bool prepared =
3398 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3399 if (prepared) {
3400 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003401 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003402 break;
3403 }
3404 default:
3405 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003406 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003407 } else {
3408 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003409 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003410 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003411 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003412
Alec Mouri820c7402019-01-23 13:02:39 -08003413 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003414 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003415 clientCompositionDisplay.clearRegion = clearRegion;
3416 if (!debugRegion.isEmpty()) {
3417 Region::const_iterator it = debugRegion.begin();
3418 Region::const_iterator end = debugRegion.end();
3419 while (it != end) {
3420 const Rect& rect = *it++;
3421 renderengine::LayerSettings layerSettings;
3422 layerSettings.source.buffer.buffer = nullptr;
3423 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3424 layerSettings.geometry.boundaries = rect.toFloatRect();
3425 layerSettings.alpha = half(1.0);
3426 clientCompositionLayers.push_back(layerSettings);
3427 }
3428 }
3429 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3430 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003431 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003432 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003433}
3434
Chia-I Wu28e3a252018-09-07 12:05:02 -07003435void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003436 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003437 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438}
3439
Dan Stoza7d89d062015-04-30 13:29:25 -07003440status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003441 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003442 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003443 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003444 const sp<Layer>& parent,
3445 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003446{
Dan Stoza7d89d062015-04-30 13:29:25 -07003447 // add this layer to the current state list
3448 {
3449 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003450 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003451 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3452 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003453 return NO_MEMORY;
3454 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003455 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003456 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003457 } else if (parent == nullptr) {
3458 lbc->onRemovedFromCurrentState();
3459 } else if (parent->isRemovedFromCurrentState()) {
3460 parent->addChild(lbc);
3461 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003462 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003463 parent->addChild(lbc);
3464 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003465
Yiwei Zhang243b3782018-05-15 17:40:04 -07003466 if (gbc != nullptr) {
3467 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3468 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3469 mMaxGraphicBufferProducerListSize,
3470 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3471 mGraphicBufferProducerList.size(),
3472 mMaxGraphicBufferProducerListSize, mNumLayers);
3473 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003474 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003475 }
3476
Mathias Agopian96f08192010-06-02 23:28:45 -07003477 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003478 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003479
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003481}
3482
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003483uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003484 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003485}
3486
Mathias Agopian3f844832013-08-07 21:24:32 -07003487uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003488 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003489}
3490
Mathias Agopian3f844832013-08-07 21:24:32 -07003491uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003492 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003493}
3494
3495uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003496 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003497 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003498 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003500 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003501 }
3502 return old;
3503}
3504
Marissa Wall713b63f2018-10-17 15:42:43 -07003505bool SurfaceFlinger::flushTransactionQueues() {
3506 Mutex::Autolock _l(mStateLock);
3507 auto it = mTransactionQueues.begin();
3508 while (it != mTransactionQueues.end()) {
3509 auto& [applyToken, transactionQueue] = *it;
3510
3511 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003512 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3513 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003514 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003515 break;
3516 }
Robert Carr14167e02019-02-13 13:50:55 -08003517 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003518 transactionQueue.pop();
3519 }
3520
3521 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3522 }
3523 return mTransactionQueues.empty();
3524}
3525
chaviwca27f252018-02-06 16:46:39 -08003526bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3527 for (const ComposerState& state : states) {
3528 // Here we need to check that the interface we're given is indeed
3529 // one of our own. A malicious client could give us a nullptr
3530 // IInterface, or one of its own or even one of our own but a
3531 // different type. All these situations would cause us to crash.
3532 if (state.client == nullptr) {
3533 return true;
3534 }
3535
3536 sp<IBinder> binder = IInterface::asBinder(state.client);
3537 if (binder == nullptr) {
3538 return true;
3539 }
3540
3541 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3542 return true;
3543 }
3544 }
3545 return false;
3546}
3547
Marissa Wall17b4e452018-12-26 16:32:34 -08003548bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3549 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003550 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003551 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3552 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3553 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3554 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3555 return false;
3556 }
3557
Marissa Wall713b63f2018-10-17 15:42:43 -07003558 for (const ComposerState& state : states) {
3559 const layer_state_t& s = state.state;
3560 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3561 continue;
3562 }
3563 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003564 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003565 }
3566 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003567 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003568}
3569
3570void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3571 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003572 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 const InputWindowCommands& inputWindowCommands,
3574 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003575 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003576
3577 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3578
Mathias Agopian698c0872011-06-28 19:09:31 -07003579 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003580
chaviwca27f252018-02-06 16:46:39 -08003581 if (containsAnyInvalidClientState(states)) {
3582 return;
3583 }
3584
Marissa Wall713b63f2018-10-17 15:42:43 -07003585 // If its TransactionQueue already has a pending TransactionState or if it is pending
3586 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003587 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003588 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3589 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003590 setTransactionFlags(eTransactionNeeded);
3591 return;
3592 }
3593
Robert Carr14167e02019-02-13 13:50:55 -08003594 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003595}
3596
3597void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003598 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003599 const InputWindowCommands& inputWindowCommands,
3600 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003601 uint32_t transactionFlags = 0;
3602
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003603 if (flags & eAnimation) {
3604 // For window updates that are part of an animation we must wait for
3605 // previous animation "frames" to be handled.
3606 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003607 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003608 if (CC_UNLIKELY(err != NO_ERROR)) {
3609 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003610 // caller after a few seconds.
3611 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3612 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003613 mAnimTransactionPending = false;
3614 break;
3615 }
3616 }
3617 }
3618
chaviwca27f252018-02-06 16:46:39 -08003619 for (const DisplayState& display : displays) {
3620 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003621 }
3622
Marissa Walle2ffb422018-10-12 11:33:52 -07003623 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003624 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003625 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003626 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003627 // If the state doesn't require a traversal and there are callbacks, send them now
3628 if (!(clientStateFlags & eTraversalNeeded)) {
3629 mTransactionCompletedThread.sendCallbacks();
3630 }
3631 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003632
chaviw273171b2018-12-26 11:46:30 -08003633 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3634
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003635 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3636 // anyway. This can be used as a flush mechanism for previous async transactions.
3637 // Empty animation transaction can be used to simulate back-pressure, so also force a
3638 // transaction for empty animation transactions.
3639 if (transactionFlags == 0 &&
3640 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003641 transactionFlags = eTransactionNeeded;
3642 }
3643
Mathias Agopian386aa982011-11-07 21:58:03 -08003644 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003645 if (mInterceptor->isEnabled()) {
3646 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003647 }
Irvel468051e2016-06-13 16:44:44 -07003648
Mathias Agopian386aa982011-11-07 21:58:03 -08003649 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003650 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3651 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003652 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003653
3654 // if this is a synchronous transaction, wait for it to take effect
3655 // before returning.
3656 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003657 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003658 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003659 if (flags & eAnimation) {
3660 mAnimTransactionPending = true;
3661 }
3662 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003663 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3664 if (CC_UNLIKELY(err != NO_ERROR)) {
3665 // just in case something goes wrong in SF, return to the
3666 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003667 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3668 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003669 break;
3670 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 }
3673}
3674
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003675uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3676 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3677 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003678
Mathias Agopiane57f2922012-08-09 16:29:12 -07003679 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003680 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3681
3682 const uint32_t what = s.what;
3683 if (what & DisplayState::eSurfaceChanged) {
3684 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3685 state.surface = s.surface;
3686 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003687 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003688 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003689 if (what & DisplayState::eLayerStackChanged) {
3690 if (state.layerStack != s.layerStack) {
3691 state.layerStack = s.layerStack;
3692 flags |= eDisplayTransactionNeeded;
3693 }
3694 }
3695 if (what & DisplayState::eDisplayProjectionChanged) {
3696 if (state.orientation != s.orientation) {
3697 state.orientation = s.orientation;
3698 flags |= eDisplayTransactionNeeded;
3699 }
3700 if (state.frame != s.frame) {
3701 state.frame = s.frame;
3702 flags |= eDisplayTransactionNeeded;
3703 }
3704 if (state.viewport != s.viewport) {
3705 state.viewport = s.viewport;
3706 flags |= eDisplayTransactionNeeded;
3707 }
3708 }
3709 if (what & DisplayState::eDisplaySizeChanged) {
3710 if (state.width != s.width) {
3711 state.width = s.width;
3712 flags |= eDisplayTransactionNeeded;
3713 }
3714 if (state.height != s.height) {
3715 state.height = s.height;
3716 flags |= eDisplayTransactionNeeded;
3717 }
3718 }
3719
Mathias Agopiane57f2922012-08-09 16:29:12 -07003720 return flags;
3721}
3722
Robert Carr14167e02019-02-13 13:50:55 -08003723bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003724 IPCThreadState* ipc = IPCThreadState::self();
3725 const int pid = ipc->getCallingPid();
3726 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003727 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003728 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003729 return false;
3730 }
3731 return true;
3732}
3733
Robert Carr14167e02019-02-13 13:50:55 -08003734uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3735 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003736 const layer_state_t& s = composerState.state;
3737 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3738
Mathias Agopian13127d82013-03-05 17:47:11 -08003739 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003740 if (layer == nullptr) {
3741 return 0;
3742 }
3743
chaviw8b3871a2017-11-01 17:41:01 -07003744 uint32_t flags = 0;
3745
Garfield Tan8a3083e2018-12-03 13:21:07 -08003746 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003747 bool geometryAppliesWithResize =
3748 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003749
3750 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3751 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003752 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003753 layer->pushPendingState();
3754 }
3755
chaviw8b3871a2017-11-01 17:41:01 -07003756 if (what & layer_state_t::ePositionChanged) {
3757 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3758 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759 }
chaviw8b3871a2017-11-01 17:41:01 -07003760 }
3761 if (what & layer_state_t::eLayerChanged) {
3762 // NOTE: index needs to be calculated before we update the state
3763 const auto& p = layer->getParent();
3764 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003765 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003766 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003767 mCurrentState.layersSortedByZ.removeAt(idx);
3768 mCurrentState.layersSortedByZ.add(layer);
3769 // we need traversal (state changed)
3770 // AND transaction (list changed)
3771 flags |= eTransactionNeeded|eTraversalNeeded;
3772 }
chaviw8b3871a2017-11-01 17:41:01 -07003773 } else {
3774 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003775 flags |= eTransactionNeeded|eTraversalNeeded;
3776 }
3777 }
chaviw8b3871a2017-11-01 17:41:01 -07003778 }
3779 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003780 // NOTE: index needs to be calculated before we update the state
3781 const auto& p = layer->getParent();
3782 if (p == nullptr) {
3783 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3784 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3785 mCurrentState.layersSortedByZ.removeAt(idx);
3786 mCurrentState.layersSortedByZ.add(layer);
3787 // we need traversal (state changed)
3788 // AND transaction (list changed)
3789 flags |= eTransactionNeeded|eTraversalNeeded;
3790 }
3791 } else {
3792 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3793 flags |= eTransactionNeeded|eTraversalNeeded;
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 }
3796 }
3797 if (what & layer_state_t::eSizeChanged) {
3798 if (layer->setSize(s.w, s.h)) {
3799 flags |= eTraversalNeeded;
3800 }
3801 }
3802 if (what & layer_state_t::eAlphaChanged) {
3803 if (layer->setAlpha(s.alpha))
3804 flags |= eTraversalNeeded;
3805 }
3806 if (what & layer_state_t::eColorChanged) {
3807 if (layer->setColor(s.color))
3808 flags |= eTraversalNeeded;
3809 }
Peiyong Lind3788632018-09-18 16:01:31 -07003810 if (what & layer_state_t::eColorTransformChanged) {
3811 if (layer->setColorTransform(s.colorTransform)) {
3812 flags |= eTraversalNeeded;
3813 }
3814 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003815 if (what & layer_state_t::eBackgroundColorChanged) {
3816 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3817 flags |= eTraversalNeeded;
3818 }
3819 }
chaviw8b3871a2017-11-01 17:41:01 -07003820 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003821 // TODO: b/109894387
3822 //
3823 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3824 // rotation. To see the problem observe that if we have a square parent, and a child
3825 // of the same size, then we rotate the child 45 degrees around it's center, the child
3826 // must now be cropped to a non rectangular 8 sided region.
3827 //
3828 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3829 // private API, and the WindowManager only uses rotation in one case, which is on a top
3830 // level layer in which cropping is not an issue.
3831 //
3832 // However given that abuse of rotation matrices could lead to surfaces extending outside
3833 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3834 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3835 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003836 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003837 flags |= eTraversalNeeded;
3838 }
3839 if (what & layer_state_t::eTransparentRegionChanged) {
3840 if (layer->setTransparentRegionHint(s.transparentRegion))
3841 flags |= eTraversalNeeded;
3842 }
3843 if (what & layer_state_t::eFlagsChanged) {
3844 if (layer->setFlags(s.flags, s.mask))
3845 flags |= eTraversalNeeded;
3846 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003847 if (what & layer_state_t::eCropChanged_legacy) {
3848 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003849 flags |= eTraversalNeeded;
3850 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003851 if (what & layer_state_t::eCornerRadiusChanged) {
3852 if (layer->setCornerRadius(s.cornerRadius))
3853 flags |= eTraversalNeeded;
3854 }
chaviw8b3871a2017-11-01 17:41:01 -07003855 if (what & layer_state_t::eLayerStackChanged) {
3856 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3857 // We only allow setting layer stacks for top level layers,
3858 // everything else inherits layer stack from its parent.
3859 if (layer->hasParent()) {
3860 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3861 layer->getName().string());
3862 } else if (idx < 0) {
3863 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3864 "that also does not appear in the top level layer list. Something"
3865 " has gone wrong.", layer->getName().string());
3866 } else if (layer->setLayerStack(s.layerStack)) {
3867 mCurrentState.layersSortedByZ.removeAt(idx);
3868 mCurrentState.layersSortedByZ.add(layer);
3869 // we need traversal (state changed)
3870 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003871 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003872 }
3873 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003874 if (what & layer_state_t::eDeferTransaction_legacy) {
3875 if (s.barrierHandle_legacy != nullptr) {
3876 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3877 } else if (s.barrierGbp_legacy != nullptr) {
3878 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003879 if (authenticateSurfaceTextureLocked(gbp)) {
3880 const auto& otherLayer =
3881 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003882 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003883 } else {
3884 ALOGE("Attempt to defer transaction to to an"
3885 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003886 }
3887 }
chaviw8b3871a2017-11-01 17:41:01 -07003888 // We don't trigger a traversal here because if no other state is
3889 // changed, we don't want this to cause any more work
3890 }
3891 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003892 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003893 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003894 if (!hadParent) {
3895 mCurrentState.layersSortedByZ.remove(layer);
3896 }
chaviw8b3871a2017-11-01 17:41:01 -07003897 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003898 }
chaviw8b3871a2017-11-01 17:41:01 -07003899 }
3900 if (what & layer_state_t::eReparentChildren) {
3901 if (layer->reparentChildren(s.reparentHandle)) {
3902 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003903 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003904 }
chaviw8b3871a2017-11-01 17:41:01 -07003905 if (what & layer_state_t::eDetachChildren) {
3906 layer->detachChildren();
3907 }
3908 if (what & layer_state_t::eOverrideScalingModeChanged) {
3909 layer->setOverrideScalingMode(s.overrideScalingMode);
3910 // We don't trigger a traversal here because if no other state is
3911 // changed, we don't want this to cause any more work
3912 }
Marissa Wall61c58622018-07-18 10:12:20 -07003913 if (what & layer_state_t::eTransformChanged) {
3914 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3915 }
3916 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3917 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3918 flags |= eTraversalNeeded;
3919 }
3920 if (what & layer_state_t::eCropChanged) {
3921 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3922 }
Marissa Wall861616d2018-10-22 12:52:23 -07003923 if (what & layer_state_t::eFrameChanged) {
3924 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3925 }
Marissa Wall61c58622018-07-18 10:12:20 -07003926 if (what & layer_state_t::eAcquireFenceChanged) {
3927 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3928 }
3929 if (what & layer_state_t::eDataspaceChanged) {
3930 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3931 }
3932 if (what & layer_state_t::eHdrMetadataChanged) {
3933 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3934 }
3935 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3936 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3937 }
3938 if (what & layer_state_t::eApiChanged) {
3939 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3940 }
3941 if (what & layer_state_t::eSidebandStreamChanged) {
3942 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3943 }
Robert Carr720e5062018-07-30 17:45:14 -07003944 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003945 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3946 layer->setInputInfo(s.inputInfo);
3947 flags |= eTraversalNeeded;
3948 } else {
3949 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3950 }
Robert Carr720e5062018-07-30 17:45:14 -07003951 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003952 if (what & layer_state_t::eMetadataChanged) {
3953 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3954 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003955 std::vector<sp<CallbackHandle>> callbackHandles;
3956 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3957 mTransactionCompletedThread.run();
3958 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3959 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3960 }
3961 }
Marissa Wall73411622019-01-25 10:45:41 -08003962
3963 if (what & layer_state_t::eBufferChanged) {
3964 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3965 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3966 s.buffer);
3967 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003968 if (what & layer_state_t::eCachedBufferChanged) {
3969 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003970 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3971 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003972 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3973 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003974 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3975 // Do not put anything that updates layer state or modifies flags after
3976 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003977 return flags;
3978}
3979
chaviw273171b2018-12-26 11:46:30 -08003980uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3981 uint32_t flags = 0;
3982 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3983 flags |= eTraversalNeeded;
3984 }
3985
chaviwa911b102019-02-14 10:18:33 -08003986 if (inputWindowCommands.syncInputWindows) {
3987 flags |= eTraversalNeeded;
3988 }
3989
Vishnu Nairec0ab382019-02-13 15:32:56 -08003990 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003991 return flags;
3992}
3993
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003994status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3995 uint32_t h, PixelFormat format, uint32_t flags,
3996 LayerMetadata metadata, sp<IBinder>* handle,
3997 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003998 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003999 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004000 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004001 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004002 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004003
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004004 status_t result = NO_ERROR;
4005
4006 sp<Layer> layer;
4007
Cody Northropbc755282017-03-31 12:00:08 -06004008 String8 uniqueName = getUniqueLayerName(name);
4009
Mathias Agopian3165cc22012-08-08 19:42:09 -07004010 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004011 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004012 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4013 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004014
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004016 case ISurfaceComposerClient::eFXSurfaceBufferState:
4017 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4018 break;
chaviw13fdc492017-06-27 12:40:18 -07004019 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004020 // check if buffer size is set for color layer.
4021 if (w > 0 || h > 0) {
4022 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4023 int(w), int(h));
4024 return BAD_VALUE;
4025 }
4026
chaviw13fdc492017-06-27 12:40:18 -07004027 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004028 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004029 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004030 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004031 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004032 // check if buffer size is set for container layer.
4033 if (w > 0 || h > 0) {
4034 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4035 int(w), int(h));
4036 return BAD_VALUE;
4037 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004038 result = createContainerLayer(client,
4039 uniqueName, w, h, flags,
4040 handle, &layer);
4041 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004042 default:
4043 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 break;
4045 }
4046
Dan Stoza7d89d062015-04-30 13:29:25 -07004047 if (result != NO_ERROR) {
4048 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004050
Chia-I Wuab0c3192017-08-01 11:29:00 -07004051 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4052 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004053 if (metadata.has(METADATA_WINDOW_TYPE)) {
4054 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4055 if (windowType == 441731) {
4056 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4057 layer->setPrimaryDisplayOnly();
4058 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004059 }
4060
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004061 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004062
Robert Carrb89ea9d2018-12-10 13:01:14 -08004063 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4064 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4065 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004066 if (result != NO_ERROR) {
4067 return result;
4068 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004069 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004070
4071 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004072 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073}
4074
Cody Northropbc755282017-03-31 12:00:08 -06004075String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4076{
4077 bool matchFound = true;
4078 uint32_t dupeCounter = 0;
4079
4080 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4081 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4082
Dan Stoza436ccf32018-06-21 12:10:12 -07004083 // Grab the state lock since we're accessing mCurrentState
4084 Mutex::Autolock lock(mStateLock);
4085
Cody Northropbc755282017-03-31 12:00:08 -06004086 // Loop over layers until we're sure there is no matching name
4087 while (matchFound) {
4088 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004089 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004090 if (layer->getName() == uniqueName) {
4091 matchFound = true;
4092 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4093 }
4094 });
4095 }
4096
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004097 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4098 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004099
4100 return uniqueName;
4101}
4102
Marissa Wallfd668622018-05-10 10:21:13 -07004103status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4104 uint32_t w, uint32_t h, uint32_t flags,
4105 PixelFormat& format, sp<IBinder>* handle,
4106 sp<IGraphicBufferProducer>* gbp,
4107 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004108 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004109 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 case PIXEL_FORMAT_TRANSPARENT:
4111 case PIXEL_FORMAT_TRANSLUCENT:
4112 format = PIXEL_FORMAT_RGBA_8888;
4113 break;
4114 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004115 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004116 break;
4117 }
4118
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004119 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004120 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004121 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004122 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004123 *handle = layer->getHandle();
4124 *gbp = layer->getProducer();
4125 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004127
Marissa Wallfd668622018-05-10 10:21:13 -07004128 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130}
4131
Marissa Wall61c58622018-07-18 10:12:20 -07004132status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4133 uint32_t w, uint32_t h, uint32_t flags,
4134 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004135 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004136 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004137 *handle = layer->getHandle();
4138 *outLayer = layer;
4139
4140 return NO_ERROR;
4141}
4142
chaviw13fdc492017-06-27 12:40:18 -07004143status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004144 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004145 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004147 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004149 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004150}
4151
Robert Carr6b3f6c52018-08-13 13:05:17 -07004152status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4153 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4154 sp<IBinder>* handle, sp<Layer>* outLayer)
4155{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004156 *outLayer =
4157 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004158 *handle = (*outLayer)->getHandle();
4159 return NO_ERROR;
4160}
4161
4162
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004163void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004164 mLayersPendingRemoval.add(layer);
4165 mLayersRemoved = true;
4166 setTransactionFlags(eTransactionNeeded);
4167}
4168
Robert Carr695d5282018-12-18 15:27:58 -08004169void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004170{
Robert Carr2e102c92018-10-23 12:11:15 -07004171 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004172 // If a layer has a parent, we allow it to out-live it's handle
4173 // with the idea that the parent holds a reference and will eventually
4174 // be cleaned up. However no one cleans up the top-level so we do so
4175 // here.
4176 if (layer->getParent() == nullptr) {
4177 mCurrentState.layersSortedByZ.remove(layer);
4178 }
4179 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004180 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004181}
4182
Mathias Agopianb60314a2012-04-10 22:09:54 -07004183// ---------------------------------------------------------------------------
4184
Andy McFadden13a082e2012-08-24 10:16:42 -07004185void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004186 const auto display = getDefaultDisplayDeviceLocked();
4187 if (!display) return;
4188
4189 const sp<IBinder> token = display->getDisplayToken().promote();
4190 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004191
Jesse Hall01e29052013-02-19 16:13:35 -08004192 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004193 Vector<ComposerState> state;
4194 Vector<DisplayState> displays;
4195 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004196 d.what = DisplayState::eDisplayProjectionChanged |
4197 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004198 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004199 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004200 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004201 d.frame.makeInvalid();
4202 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004203 d.width = 0;
4204 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004205 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004206 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004207
Dominik Laskowskie9774092018-12-11 10:04:24 -08004208 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004209
Dominik Laskowski83b88212018-12-11 13:34:06 -08004210 const nsecs_t vsyncPeriod = getVsyncPeriod();
4211 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004212
Brian Andersond0010582017-03-07 13:20:31 -08004213 // Use phase of 0 since phase is not known.
4214 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004215 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004216 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004217}
4218
4219void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004220 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004221 postMessageAsync(
4222 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004223}
4224
Dominik Laskowskie9774092018-12-11 10:04:24 -08004225void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004226 if (display->isVirtual()) {
4227 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004228 return;
4229 }
4230
Dominik Laskowski075d3172018-05-24 15:50:06 -07004231 const auto displayId = display->getId();
4232 LOG_ALWAYS_FATAL_IF(!displayId);
4233
Dominik Laskowski34157762018-10-31 13:07:19 -07004234 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235
4236 int currentMode = display->getPowerMode();
4237 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004238 return;
4239 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004240
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004241 display->setPowerMode(mode);
4242
Lloyd Pique4dccc412018-01-22 17:21:36 -08004243 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004244 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004245 }
4246
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004247 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004248 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004249 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004250 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004251 mScheduler->onScreenAcquired(mAppConnectionHandle);
4252 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004253 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004254
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004255 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004256 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004257 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004258
4259 struct sched_param param = {0};
4260 param.sched_priority = 1;
4261 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4262 ALOGW("Couldn't set SCHED_FIFO on display on");
4263 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004264 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004265 // Turn off the display
4266 struct sched_param param = {0};
4267 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4268 ALOGW("Couldn't set SCHED_OTHER on display off");
4269 }
4270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004271 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004272 mScheduler->disableHardwareVsync(true);
4273 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004274 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004275
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 mVisibleRegionsDirty = true;
4278 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004279 } else if (mode == HWC_POWER_MODE_DOZE ||
4280 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004281 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004282 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004283 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004284 mScheduler->onScreenAcquired(mAppConnectionHandle);
4285 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004286 }
4287 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4288 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004290 mScheduler->disableHardwareVsync(true);
4291 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004292 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004295 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004296 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004298
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004299 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004300 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004301 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004302 // Update refresh rate stats.
4303 mRefreshRateStats->setPowerMode(mode);
4304 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004305 }
4306
Dominik Laskowski34157762018-10-31 13:07:19 -07004307 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004308}
4309
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004310void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004311 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312 const auto display = getDisplayDevice(displayToken);
4313 if (!display) {
4314 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4315 displayToken.get());
4316 } else if (display->isVirtual()) {
4317 ALOGW("Attempt to set power mode %d for virtual display", mode);
4318 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004319 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004320 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004321 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004322}
4323
4324// ---------------------------------------------------------------------------
4325
Dominik Laskowskic2867142019-01-21 11:33:38 -08004326status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4327 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004328 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004329
Mathias Agopianbd115332013-04-18 16:41:04 -07004330 IPCThreadState* ipc = IPCThreadState::self();
4331 const int pid = ipc->getCallingPid();
4332 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004333
Mathias Agopianbd115332013-04-18 16:41:04 -07004334 if ((uid != AID_SHELL) &&
4335 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4337 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004338 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004339 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004340 // (this would indicate SF is stuck, but we want to be able to
4341 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004342 status_t err = mStateLock.timedLock(s2ns(1));
4343 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004344 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345 StringAppendF(&result,
4346 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4347 "(no locks held)\n",
4348 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004349 }
4350
Dominik Laskowskic2867142019-01-21 11:33:38 -08004351 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004352
Dominik Laskowskic2867142019-01-21 11:33:38 -08004353 static const std::unordered_map<std::string, Dumper> dumpers = {
4354 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4355 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4356 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004357 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004358 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004359 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004360 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4361 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004362 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4363 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4364 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4365 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4366 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4367 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004368 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004369 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4370 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004371
Dominik Laskowskic2867142019-01-21 11:33:38 -08004372 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004373
Dominik Laskowskic2867142019-01-21 11:33:38 -08004374 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4375 (it->second)(args, asProto, result);
4376 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004377 if (asProto) {
4378 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4379 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4380 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004381 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004382 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004383 }
4384
Mathias Agopian9795c422009-08-26 16:36:26 -07004385 if (locked) {
4386 mStateLock.unlock();
4387 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004388 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004389 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004390 return NO_ERROR;
4391}
4392
Dominik Laskowskic2867142019-01-21 11:33:38 -08004393void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 mCurrentState.traverseInZOrder(
4395 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004396}
4397
Dominik Laskowskic2867142019-01-21 11:33:38 -08004398void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004399 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004400
Dominik Laskowskic2867142019-01-21 11:33:38 -08004401 if (args.size() > 1) {
4402 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004403 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004404 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004405 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004406 }
Robert Carr2047fae2016-11-28 14:09:09 -08004407 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004408 } else {
4409 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004410 }
4411}
4412
Dominik Laskowskic2867142019-01-21 11:33:38 -08004413void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004414 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004416 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004417 }
Robert Carr2047fae2016-11-28 14:09:09 -08004418 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004419
Svetoslavd85084b2014-03-20 10:28:31 -07004420 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004421}
4422
Dominik Laskowskic2867142019-01-21 11:33:38 -08004423void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4424 mTimeStats->parseArgs(asProto, args, result);
4425}
4426
Jamie Gennis6547ff42013-07-16 20:12:42 -07004427// This should only be called from the main thread. Otherwise it would need
4428// the lock and should use mCurrentState rather than mDrawingState.
4429void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004430 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004431 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004432 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004433
4434 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4435}
4436
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004438 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004439
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004440 if (isLayerTripleBufferingDisabled())
4441 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004442
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4444 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4445 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4446 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4447 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4448 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004449 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004450}
4451
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004452void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004453 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004454 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004455 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004456 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004457
Ana Krulecc2870422019-01-29 19:00:58 -08004458 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n\n", mUse90Hz ? "on" : "off");
4459 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004460}
4461
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4463 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004464 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4465 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004466 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004467 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004469 }
David Sodman4a36e932017-11-07 14:29:47 -08004470 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004471 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004472 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4474 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004475}
4476
Dan Stozae77c7662016-05-13 11:37:28 -07004477void SurfaceFlinger::recordBufferingStats(const char* layerName,
4478 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004479 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4480 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004481 for (const auto& segment : history) {
4482 if (!segment.usedThirdBuffer) {
4483 stats.twoBufferTime += segment.totalTime;
4484 }
4485 if (segment.occupancyAverage < 1.0f) {
4486 stats.doubleBufferedTime += segment.totalTime;
4487 } else if (segment.occupancyAverage < 2.0f) {
4488 stats.tripleBufferedTime += segment.totalTime;
4489 }
4490 ++stats.numSegments;
4491 stats.totalTime += segment.totalTime;
4492 }
4493}
4494
Yiwei Zhang5434a782018-12-05 18:06:32 -08004495void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4496 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004497
4498 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4499 const size_t count = currentLayers.size();
4500 for (size_t i=0 ; i<count ; i++) {
4501 currentLayers[i]->dumpFrameEvents(result);
4502 }
4503}
4504
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004506 result.append("Buffering stats:\n");
4507 result.append(" [Layer name] <Active time> <Two buffer> "
4508 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004509 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004510 typedef std::tuple<std::string, float, float, float> BufferTuple;
4511 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004512 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004513 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004514 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004515 if (stats.numSegments == 0) {
4516 continue;
4517 }
4518 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4519 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4520 stats.totalTime;
4521 float doubleBufferRatio = static_cast<float>(
4522 stats.doubleBufferedTime) / stats.totalTime;
4523 float tripleBufferRatio = static_cast<float>(
4524 stats.tripleBufferedTime) / stats.totalTime;
4525 sorted.insert({activeTime, {name, twoBufferRatio,
4526 doubleBufferRatio, tripleBufferRatio}});
4527 }
4528 for (const auto& sortedPair : sorted) {
4529 float activeTime = sortedPair.first;
4530 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4532 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004533 }
4534 result.append("\n");
4535}
4536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004538 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004539 const auto displayId = display->getId();
4540 if (!displayId) {
4541 continue;
4542 }
4543 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004544 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004545 continue;
4546 }
4547
Yiwei Zhang5434a782018-12-05 18:06:32 -08004548 StringAppendF(&result,
4549 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4550 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004551 uint8_t port;
4552 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004553 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004554 result.append("no identification data\n");
4555 continue;
4556 }
4557
4558 if (!isEdid(data)) {
4559 result.append("unknown identification data: ");
4560 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004562 }
4563 result.append("\n");
4564 continue;
4565 }
4566
4567 const auto edid = parseEdid(data);
4568 if (!edid) {
4569 result.append("invalid EDID: ");
4570 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004571 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004572 }
4573 result.append("\n");
4574 continue;
4575 }
4576
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004578 result.append(edid->displayName.data(), edid->displayName.length());
4579 result.append("\"\n");
4580 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004581}
4582
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4584 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4585 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4586 StringAppendF(&result, "DisplayColorSetting: %s\n",
4587 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004588
4589 // TODO: print out if wide-color mode is active or not
4590
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004591 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004592 const auto displayId = display->getId();
4593 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004594 continue;
4595 }
4596
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004598 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004599 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004600 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004601 }
4602
Lloyd Pique32cbe282018-10-19 13:09:22 -07004603 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 StringAppendF(&result, " Current color mode: %s (%d)\n",
4605 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004606 }
4607 result.append("\n");
4608}
4609
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004610LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004611 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004612 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4613 const State& state = useDrawing ? mDrawingState : mCurrentState;
4614 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004615 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004616 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004617 });
4618
4619 return layersProto;
4620}
4621
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004622LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4623 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004624 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004625
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004626 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004627 resolution->set_w(displayDevice->getWidth());
4628 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004629
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004630 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004631 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004632
Lloyd Pique32cbe282018-10-19 13:09:22 -07004633 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4634 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4635 layersProto.set_global_transform(displayState.orientation);
4636
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004637 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004638 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004639 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004640 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004641 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004642 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004643 }
4644 });
4645
4646 return layersProto;
4647}
4648
Dominik Laskowskic2867142019-01-21 11:33:38 -08004649void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4650 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004651 Colorizer colorizer(colorize);
4652
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 // figure out if we're stuck somewhere
4654 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004655 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4657
4658 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004659 * Dump library configuration.
4660 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661
4662 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004663 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004664 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004665 appendSfConfigString(result);
4666 appendUiConfigString(result);
4667 appendGuiConfigString(result);
4668 result.append("\n");
4669
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004670 result.append("\nDisplay identification data:\n");
4671 dumpDisplayIdentificationData(result);
4672
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004673 result.append("\nWide-Color information:\n");
4674 dumpWideColorInfo(result);
4675
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004677 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004679 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004680 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004681
Andy McFadden41d67d72014-04-25 16:58:34 -07004682 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004683 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004684 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004685 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004686 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004687
Dan Stozab90cf072015-03-05 11:05:59 -08004688 dumpStaticScreenStats(result);
4689 result.append("\n");
4690
Yiwei Zhang5434a782018-12-05 18:06:32 -08004691 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004692
Dan Stozae77c7662016-05-13 11:37:28 -07004693 dumpBufferingStats(result);
4694
Andy McFadden4803b742012-09-24 19:07:20 -07004695 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696 * Dump the visible layer list
4697 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004699 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4700 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4701 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004703
Chia-I Wu2f884132018-09-13 15:17:58 -07004704 {
4705 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4706 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004707 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004708 result.append("\n");
4709 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004710
4711 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004712 * Dump Display state
4713 */
4714
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004715 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004716 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004718 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004719 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004720 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004721 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004722
4723 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004724 * Dump SurfaceFlinger global state
4725 */
4726
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004727 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004728 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004729 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004730
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004731 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732
Dominik Laskowski075d3172018-05-24 15:50:06 -07004733 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004734 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4735 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4737 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004738 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004739 StringAppendF(&result,
4740 " transaction-flags : %08x\n"
4741 " gpu_to_cpu_unsupported : %d\n",
4742 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004743
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004744 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004745 displayId && getHwComposer().isConnected(*displayId)) {
4746 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004747 StringAppendF(&result,
4748 " refresh-rate : %f fps\n"
4749 " x-dpi : %f\n"
4750 " y-dpi : %f\n",
4751 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4752 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004753 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
Dan Stozae22aec72016-08-01 13:20:59 -07004757 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004758 * Tracing state
4759 */
4760 mTracing.dump(result);
4761 result.append("\n");
4762
4763 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004764 * HWC layer minidump
4765 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004766 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004767 const auto displayId = display->getId();
4768 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004769 continue;
4770 }
4771
Yiwei Zhang5434a782018-12-05 18:06:32 -08004772 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004773 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004774 const sp<DisplayDevice> displayDevice = display;
4775 mCurrentState.traverseInZOrder(
4776 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004777 result.append("\n");
4778 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004779
4780 /*
4781 * Dump HWComposer state
4782 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004783 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004784 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004786 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004787 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004788 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004789
4790 /*
4791 * Dump gralloc state
4792 */
4793 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4794 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004795
4796 /*
4797 * Dump VrFlinger state if in use.
4798 */
4799 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4800 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004802 result.append("\n");
4803 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004804
4805 /**
4806 * Scheduler dump state.
4807 */
Ana Krulecc2870422019-01-29 19:00:58 -08004808 result.append("\nScheduler state:\n");
4809 result.append(mScheduler->doDump() + "\n");
4810 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004811}
4812
Dominik Laskowski075d3172018-05-24 15:50:06 -07004813const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004814 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004815 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004816 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004817 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004818 }
4819 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004820
Dominik Laskowski34157762018-10-31 13:07:19 -07004821 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004822 static const Vector<sp<Layer>> empty;
4823 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004824}
4825
Chia-I Wu28f320b2018-05-03 11:02:56 -07004826void SurfaceFlinger::updateColorMatrixLocked() {
4827 mat4 colorMatrix;
4828 if (mGlobalSaturationFactor != 1.0f) {
4829 // Rec.709 luma coefficients
4830 float3 luminance{0.213f, 0.715f, 0.072f};
4831 luminance *= 1.0f - mGlobalSaturationFactor;
4832 mat4 saturationMatrix = mat4(
4833 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4834 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4835 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4836 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4837 );
4838 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4839 } else {
4840 colorMatrix = mClientColorMatrix * mDaltonizer();
4841 }
4842
4843 if (mCurrentState.colorMatrix != colorMatrix) {
4844 mCurrentState.colorMatrix = colorMatrix;
4845 mCurrentState.colorMatrixChanged = true;
4846 setTransactionFlags(eTransactionNeeded);
4847 }
4848}
4849
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004850status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004851#pragma clang diagnostic push
4852#pragma clang diagnostic error "-Wswitch-enum"
4853 switch (static_cast<ISurfaceComposerTag>(code)) {
4854 // These methods should at minimum make sure that the client requested
4855 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004856 case BOOT_FINISHED:
4857 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858 case CREATE_DISPLAY:
4859 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004860 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 case GET_ACTIVE_COLOR_MODE:
4862 case GET_ANIMATION_FRAME_STATS:
4863 case GET_HDR_CAPABILITIES:
4864 case SET_ACTIVE_CONFIG:
4865 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004866 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004867 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004868 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004869 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4870 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004871 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4872 IPCThreadState* ipc = IPCThreadState::self();
4873 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4874 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004875 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004876 }
Robert Carr1db73f62016-12-21 12:58:51 -08004877 return OK;
4878 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004879 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004880 IPCThreadState* ipc = IPCThreadState::self();
4881 const int pid = ipc->getCallingPid();
4882 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4884 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004885 return PERMISSION_DENIED;
4886 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 // Used by apps to hook Choreographer to SurfaceFlinger.
4890 case CREATE_DISPLAY_EVENT_CONNECTION:
4891 // The following calls are currently used by clients that do not
4892 // request necessary permissions. However, they do not expose any secret
4893 // information, so it is OK to pass them.
4894 case AUTHENTICATE_SURFACE:
4895 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004896 case GET_PHYSICAL_DISPLAY_IDS:
4897 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004898 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004899 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 case GET_DISPLAY_CONFIGS:
4901 case GET_DISPLAY_STATS:
4902 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4903 // Calling setTransactionState is safe, because you need to have been
4904 // granted a reference to Client* and Handle* to do anything with it.
4905 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004906 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004907 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004908 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004909 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004910 case IS_WIDE_COLOR_DISPLAY:
4911 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004912 return OK;
4913 }
4914 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004915 case CAPTURE_SCREEN:
4916 case ADD_REGION_SAMPLING_LISTENER:
4917 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004919 IPCThreadState* ipc = IPCThreadState::self();
4920 const int pid = ipc->getCallingPid();
4921 const int uid = ipc->getCallingUid();
4922 if ((uid != AID_GRAPHICS) &&
4923 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4924 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4925 return PERMISSION_DENIED;
4926 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927 return OK;
4928 }
4929 // The following codes are deprecated and should never be allowed to access SF.
4930 case CONNECT_DISPLAY_UNUSED:
4931 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4932 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4933 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004934 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936
4937 // These codes are used for the IBinder protocol to either interrogate the recipient
4938 // side of the transaction for its canonical interface descriptor or to dump its state.
4939 // We let them pass by default.
4940 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4941 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4942 code == IBinder::SYSPROPS_TRANSACTION) {
4943 return OK;
4944 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004945 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004947 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004948 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4949 return OK;
4950 }
4951 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4952 return PERMISSION_DENIED;
4953#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004954}
4955
Ana Krulec13be8ad2018-08-21 02:43:56 +00004956status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4957 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004958 status_t credentialCheck = CheckTransactCodeCredentials(code);
4959 if (credentialCheck != OK) {
4960 return credentialCheck;
4961 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004962
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004963 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4964 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004965 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004966 IPCThreadState* ipc = IPCThreadState::self();
4967 const int uid = ipc->getCallingUid();
4968 if (CC_UNLIKELY(uid != AID_SYSTEM
4969 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004970 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004971 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004972 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 return PERMISSION_DENIED;
4974 }
4975 int n;
4976 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004977 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004978 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004979 return NO_ERROR;
4980 case 1002: // SHOW_UPDATES
4981 n = data.readInt32();
4982 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004983 invalidateHwcGeometry();
4984 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004987 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004988 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004990 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004991 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004992 setTransactionFlags(
4993 eTransactionNeeded|
4994 eDisplayTransactionNeeded|
4995 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004996 return NO_ERROR;
4997 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004998 case 1006:{ // send empty update
4999 signalRefresh();
5000 return NO_ERROR;
5001 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005002 case 1008: // toggle use of hw composer
5003 n = data.readInt32();
5004 mDebugDisableHWC = n ? 1 : 0;
5005 invalidateHwcGeometry();
5006 repaintEverything();
5007 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005008 case 1009: // toggle use of transform hint
5009 n = data.readInt32();
5010 mDebugDisableTransformHint = n ? 1 : 0;
5011 invalidateHwcGeometry();
5012 repaintEverything();
5013 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005015 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 reply->writeInt32(0);
5017 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005018 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005019 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 return NO_ERROR;
5021 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005022 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005023 if (!display) {
5024 return NAME_NOT_FOUND;
5025 }
5026
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005027 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005028 return NO_ERROR;
5029 }
5030 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005031 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005032 // daltonize
5033 n = data.readInt32();
5034 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005035 case 1:
5036 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5037 break;
5038 case 2:
5039 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5040 break;
5041 case 3:
5042 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5043 break;
5044 default:
5045 mDaltonizer.setType(ColorBlindnessType::None);
5046 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005047 }
5048 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005049 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005050 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005051 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005052 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005053
5054 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005056 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005057 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005058 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 // apply a color matrix
5060 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005062 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005063 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005064 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005065 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005066 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005067 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005068 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005069 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005070 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005071
5072 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5073 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005074 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005075 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5076 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5077 }
5078
Chia-I Wu28f320b2018-05-03 11:02:56 -07005079 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005080 return NO_ERROR;
5081 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005082 // This is an experimental interface
5083 // Needs to be shifted to proper binder interface when we productize
5084 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005085 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005086 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005087 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005088 return NO_ERROR;
5089 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005090 case 1017: {
5091 n = data.readInt32();
5092 mForceFullDamage = static_cast<bool>(n);
5093 return NO_ERROR;
5094 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005095 case 1018: { // Modify Choreographer's phase offset
5096 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005097 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005098 return NO_ERROR;
5099 }
5100 case 1019: { // Modify SurfaceFlinger's phase offset
5101 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005102 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005103 return NO_ERROR;
5104 }
Irvel468051e2016-06-13 16:44:44 -07005105 case 1020: { // Layer updates interceptor
5106 n = data.readInt32();
5107 if (n) {
5108 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005109 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005110 }
5111 else{
5112 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005113 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005114 }
5115 return NO_ERROR;
5116 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005117 case 1021: { // Disable HWC virtual displays
5118 n = data.readInt32();
5119 mUseHwcVirtualDisplays = !n;
5120 return NO_ERROR;
5121 }
Romain Guy0147a172017-06-01 13:53:56 -07005122 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005123 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005124 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005125
Chia-I Wu28f320b2018-05-03 11:02:56 -07005126 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005127 return NO_ERROR;
5128 }
Romain Guy54f154a2017-10-24 21:40:32 +01005129 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005130 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005131 invalidateHwcGeometry();
5132 repaintEverything();
5133 return NO_ERROR;
5134 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005135 // Deprecate, use 1030 to check whether the device is color managed.
5136 case 1024: {
5137 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005138 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005139 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005140 n = data.readInt32();
5141 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005142 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005143 mTracing.enable();
5144 doTracing("tracing.enable");
5145 reply->writeInt32(NO_ERROR);
5146 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005147 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005148 status_t err = mTracing.disable();
5149 reply->writeInt32(err);
5150 }
5151 return NO_ERROR;
5152 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005153 case 1026: { // Get layer tracing status
5154 reply->writeBool(mTracing.isEnabled());
5155 return NO_ERROR;
5156 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005157 // Is a DisplayColorSetting supported?
5158 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 const auto display = getDefaultDisplayDevice();
5160 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005161 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005162 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005163
5164 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5165 switch (setting) {
5166 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005167 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005168 break;
5169 case DisplayColorSetting::UNMANAGED:
5170 reply->writeBool(true);
5171 break;
5172 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005173 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005174 break;
5175 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005176 reply->writeBool(
5177 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005178 break;
5179 }
5180 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005181 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005182 // Is VrFlinger active?
5183 case 1028: {
5184 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005185 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005186 return NO_ERROR;
5187 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005188 // Is device color managed?
5189 case 1030: {
5190 reply->writeBool(useColorManagement);
5191 return NO_ERROR;
5192 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005193 // Override default composition data space
5194 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5195 // && adb shell stop zygote && adb shell start zygote
5196 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5197 // adb shell stop zygote && adb shell start zygote
5198 case 1031: {
5199 Mutex::Autolock _l(mStateLock);
5200 n = data.readInt32();
5201 if (n) {
5202 n = data.readInt32();
5203 if (n) {
5204 Dataspace dataspace = static_cast<Dataspace>(n);
5205 if (!validateCompositionDataspace(dataspace)) {
5206 return BAD_VALUE;
5207 }
5208 mDefaultCompositionDataspace = dataspace;
5209 }
5210 n = data.readInt32();
5211 if (n) {
5212 Dataspace dataspace = static_cast<Dataspace>(n);
5213 if (!validateCompositionDataspace(dataspace)) {
5214 return BAD_VALUE;
5215 }
5216 mWideColorGamutCompositionDataspace = dataspace;
5217 }
5218 } else {
5219 // restore composition data space.
5220 mDefaultCompositionDataspace = defaultCompositionDataspace;
5221 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5222 }
5223 return NO_ERROR;
5224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005225 }
5226 }
5227 return err;
5228}
5229
Steven Thomas6d8110b2017-08-31 18:24:21 -07005230void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005231 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005232 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005233}
5234
Ana Krulec7d1d6832018-12-27 11:10:09 -08005235void SurfaceFlinger::repaintEverythingForHWC() {
5236 mRepaintEverything = true;
5237 mEventQueue->invalidateForHWC();
5238}
5239
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005240// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5241class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005242public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005243 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5244 ~WindowDisconnector() {
5245 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005246 }
5247
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005248private:
5249 ANativeWindow* mWindow;
5250 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005251};
5252
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005253status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005254 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5255 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005256 uint32_t reqWidth, uint32_t reqHeight,
5257 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005258 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005259 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005260
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005261 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005262
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005263 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5264
Chia-I Wu20261cb2018-08-23 12:55:44 -07005265 sp<DisplayDevice> display;
5266 {
5267 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005268
Chia-I Wu20261cb2018-08-23 12:55:44 -07005269 display = getDisplayDeviceLocked(displayToken);
5270 if (!display) return BAD_VALUE;
5271
Chia-I Wucb023152018-08-28 12:57:23 -07005272 // set the requested width/height to the logical display viewport size
5273 // by default
5274 if (reqWidth == 0 || reqHeight == 0) {
5275 reqWidth = uint32_t(display->getViewport().width());
5276 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005277 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005278 }
5279
Peiyong Lin0e003c92018-09-17 11:09:51 -07005280 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5281 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005282
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005283 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5284 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005285 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5286 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005287}
5288
5289status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005290 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5291 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005292 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005293 ATRACE_CALL();
5294
5295 class LayerRenderArea : public RenderArea {
5296 public:
Robert Carr578038f2018-03-09 12:25:24 -08005297 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005298 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5299 bool childrenOnly)
5300 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005301 mLayer(layer),
5302 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005303 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005304 mFlinger(flinger),
5305 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005306 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005307 Rect getBounds() const override {
5308 const Layer::State& layerState(mLayer->getDrawingState());
5309 return mLayer->getBufferSize(layerState);
5310 }
Marissa Wall61c58622018-07-18 10:12:20 -07005311 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005312 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005313 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005314 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005315 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005316 }
chaviwa76b2712017-09-20 12:02:26 -07005317 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005318 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005319 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005320 Rect getSourceCrop() const override {
5321 if (mCrop.isEmpty()) {
5322 return getBounds();
5323 } else {
5324 return mCrop;
5325 }
5326 }
Robert Carr578038f2018-03-09 12:25:24 -08005327 class ReparentForDrawing {
5328 public:
5329 const sp<Layer>& oldParent;
5330 const sp<Layer>& newParent;
5331
Vishnu Nair4351ad52019-02-11 14:13:02 -08005332 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5333 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005334 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005335 // Compute and cache the bounds for the new parent layer.
5336 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005337 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005338 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005339 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005340 };
5341
5342 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005343 const Rect sourceCrop = getSourceCrop();
5344 // no need to check rotation because there is none
5345 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5346 sourceCrop.height() != getReqHeight();
5347
Robert Carr578038f2018-03-09 12:25:24 -08005348 if (!mChildrenOnly) {
5349 mTransform = mLayer->getTransform().inverse();
5350 drawLayers();
5351 } else {
5352 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005353 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005354 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5355 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005356
Vishnu Nair4351ad52019-02-11 14:13:02 -08005357 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005358 drawLayers();
5359 }
5360 }
chaviwa76b2712017-09-20 12:02:26 -07005361
chaviwa76b2712017-09-20 12:02:26 -07005362 private:
chaviw7206d492017-11-10 16:16:12 -08005363 const sp<Layer> mLayer;
5364 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005365
5366 // In the "childrenOnly" case we reparent the children to a screenshot
5367 // layer which has no properties set and which does not draw.
5368 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005369 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005370 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005371
5372 SurfaceFlinger* mFlinger;
5373 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005374 };
5375
5376 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5377 auto parent = layerHandle->owner.promote();
5378
Robert Carr2e102c92018-10-23 12:11:15 -07005379 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005380 ALOGE("captureLayers called with a removed parent");
5381 return NAME_NOT_FOUND;
5382 }
5383
Robert Carr578038f2018-03-09 12:25:24 -08005384 const int uid = IPCThreadState::self()->getCallingUid();
5385 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005386 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005387 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5388 return PERMISSION_DENIED;
5389 }
5390
chaviw7206d492017-11-10 16:16:12 -08005391 Rect crop(sourceCrop);
5392 if (sourceCrop.width() <= 0) {
5393 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005394 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005395 }
5396
5397 if (sourceCrop.height() <= 0) {
5398 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005399 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005400 }
5401
5402 int32_t reqWidth = crop.width() * frameScale;
5403 int32_t reqHeight = crop.height() * frameScale;
5404
Chia-I Wu20261cb2018-08-23 12:55:44 -07005405 // really small crop or frameScale
5406 if (reqWidth <= 0) {
5407 reqWidth = 1;
5408 }
5409 if (reqHeight <= 0) {
5410 reqHeight = 1;
5411 }
5412
Peiyong Lin0e003c92018-09-17 11:09:51 -07005413 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005414
Robert Carr578038f2018-03-09 12:25:24 -08005415 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005416 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5417 if (!layer->isVisible()) {
5418 return;
Robert Carr578038f2018-03-09 12:25:24 -08005419 } else if (childrenOnly && layer == parent.get()) {
5420 return;
chaviwa76b2712017-09-20 12:02:26 -07005421 }
5422 visitor(layer);
5423 });
5424 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005425 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005426}
5427
5428status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5429 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005430 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005431 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005432 bool useIdentityTransform) {
5433 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005434
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005436 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5437 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005438 *outBuffer =
5439 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5440 static_cast<android_pixel_format>(reqPixelFormat), 1,
5441 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442
5443 // This mutex protects syncFd and captureResult for communication of the return values from the
5444 // main thread back to this Binder thread
5445 std::mutex captureMutex;
5446 std::condition_variable captureCondition;
5447 std::unique_lock<std::mutex> captureLock(captureMutex);
5448 int syncFd = -1;
5449 std::optional<status_t> captureResult;
5450
Robert Carr03480e22018-01-04 16:02:06 -08005451 const int uid = IPCThreadState::self()->getCallingUid();
5452 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5453
Dominik Laskowski8c001672018-05-30 16:52:06 -07005454 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005455 // If there is a refresh pending, bug out early and tell the binder thread to try again
5456 // after the refresh.
5457 if (mRefreshPending) {
5458 ATRACE_NAME("Skipping screenshot for now");
5459 std::unique_lock<std::mutex> captureLock(captureMutex);
5460 captureResult = std::make_optional<status_t>(EAGAIN);
5461 captureCondition.notify_one();
5462 return;
5463 }
5464
5465 status_t result = NO_ERROR;
5466 int fd = -1;
5467 {
5468 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005469 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005470 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5471 useIdentityTransform, forSystem, &fd);
5472 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473 }
5474
5475 {
5476 std::unique_lock<std::mutex> captureLock(captureMutex);
5477 syncFd = fd;
5478 captureResult = std::make_optional<status_t>(result);
5479 captureCondition.notify_one();
5480 }
5481 });
5482
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005483 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005485 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005486 while (*captureResult == EAGAIN) {
5487 captureResult.reset();
5488 result = postMessageAsync(message);
5489 if (result != NO_ERROR) {
5490 return result;
5491 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005492 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005493 }
5494 result = *captureResult;
5495 }
5496
5497 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005498 sync_wait(syncFd, -1);
5499 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005500 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005501
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005502 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005503}
5504
chaviwa76b2712017-09-20 12:02:26 -07005505void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005506 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005507 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5508 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005509 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005510
chaviwa76b2712017-09-20 12:02:26 -07005511 const auto reqWidth = renderArea.getReqWidth();
5512 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005513 const auto sourceCrop = renderArea.getSourceCrop();
5514 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005515
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005516 renderengine::DisplaySettings clientCompositionDisplay;
5517 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005518
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005519 // assume that bounds are never offset, and that they are the same as the
5520 // buffer bounds.
5521 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5522 ui::Transform transform = renderArea.getTransform();
5523 mat4 m;
5524 m[0][0] = transform[0][0];
5525 m[0][1] = transform[0][1];
5526 m[0][3] = transform[0][2];
5527 m[1][0] = transform[1][0];
5528 m[1][1] = transform[1][1];
5529 m[1][3] = transform[1][2];
5530 m[3][0] = transform[2][0];
5531 m[3][1] = transform[2][1];
5532 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005533
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005534 clientCompositionDisplay.globalTransform = m;
5535 mat4 rotMatrix;
5536 // Displacement for repositioning the clipping rectangle after rotating it
5537 // with the rotation hint.
5538 int displacementX = 0;
5539 int displacementY = 0;
5540 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5541 switch (rotation) {
5542 case ui::Transform::ROT_90:
5543 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5544 displacementX = reqWidth;
5545 break;
5546 case ui::Transform::ROT_180:
5547 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5548 displacementX = reqWidth;
5549 displacementY = reqHeight;
5550 break;
5551 case ui::Transform::ROT_270:
5552 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5553 displacementY = reqHeight;
5554 break;
5555 default:
5556 break;
5557 }
5558 // We need to transform the clipping window into the right spot.
5559 // First, rotate the clipping rectangle by the rotation hint to get the
5560 // right orientation
5561 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5562 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5563 const vec4 rotClipTL = rotMatrix * clipTL;
5564 const vec4 rotClipBR = rotMatrix * clipBR;
5565 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5566 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5567 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5568 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5569
5570 // Now reposition the clipping rectangle with the displacement vector
5571 // computed above.
5572 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5573
5574 clientCompositionDisplay.clip =
5575 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5576 newClipRight + displacementX, newClipBottom + displacementY);
5577
5578 // We need to perform the same transformation in layer space, so propagate
5579 // it to the global transform.
5580 mat4 clipTransform = displacementMat * rotMatrix;
5581 clientCompositionDisplay.globalTransform *= clipTransform;
5582 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5583 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005584
chaviw50da5042018-04-09 13:49:37 -07005585 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005586
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005587 renderengine::LayerSettings fillLayer;
5588 fillLayer.source.buffer.buffer = nullptr;
5589 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5590 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5591 fillLayer.alpha = half(alpha);
5592 clientCompositionLayers.push_back(fillLayer);
5593
5594 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005595 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005596 renderengine::LayerSettings layerSettings;
5597 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5598 layerSettings);
5599 if (prepared) {
5600 clientCompositionLayers.push_back(layerSettings);
5601 }
chaviwa76b2712017-09-20 12:02:26 -07005602 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005603
5604 clientCompositionDisplay.clearRegion = clearRegion;
5605 base::unique_fd drawFence;
5606 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5607 &drawFence);
5608
5609 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005610}
5611
chaviwa76b2712017-09-20 12:02:26 -07005612status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5613 TraverseLayersFunction traverseLayers,
5614 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005615 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005616 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005617 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005618 ATRACE_CALL();
5619
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005620 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005621
5622 traverseLayers([&](Layer* layer) {
5623 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5624 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005625
Robert Carr03480e22018-01-04 16:02:06 -08005626 // We allow the system server to take screenshots of secure layers for
5627 // use in situations like the Screen-rotation animation and place
5628 // the impetus on WindowManager to not persist them.
5629 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005630 ALOGW("FB is protected: PERMISSION_DENIED");
5631 return PERMISSION_DENIED;
5632 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005634 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005635}
5636
chaviw5f21a5e2019-02-14 10:00:34 -08005637void SurfaceFlinger::setInputWindowsFinished() {}
5638
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005639// ---------------------------------------------------------------------------
5640
Dan Stoza412903f2017-04-27 13:42:17 -07005641void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5642 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005643}
5644
Dan Stoza412903f2017-04-27 13:42:17 -07005645void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5646 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005647}
5648
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005649void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005650 const LayerVector::Visitor& visitor) {
5651 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005652 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005653 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005654 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005655 continue;
5656 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005657 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005658 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005659 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005660 return;
5661 }
chaviwa76b2712017-09-20 12:02:26 -07005662 if (!layer->isVisible()) {
5663 return;
5664 }
5665 visitor(layer);
5666 });
5667 }
5668}
5669
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005670}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005671
Lloyd Pique074e8122018-07-26 12:57:23 -07005672
Mathias Agopian3f844832013-08-07 21:24:32 -07005673#if defined(__gl_h_)
5674#error "don't include gl/gl.h in this file"
5675#endif
5676
5677#if defined(__gl2_h_)
5678#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005679#endif