blob: a2e7dd2af02a1658b1fee0bc9783daba1af3523d [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()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700295 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700296 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800297 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800298 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700300 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700301 mMainThreadId(std::this_thread::get_id()),
302 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800303
Lloyd Pique90c115d2018-09-18 21:39:42 -0700304SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
305 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800306 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800315
Steven Thomas050b2c82017-03-06 11:45:16 -0800316 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 mDefaultCompositionDataspace =
326 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
327 mWideColorGamutCompositionDataspace =
328 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
329 defaultCompositionDataspace = mDefaultCompositionDataspace;
330 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
331 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
332 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
333 wideColorGamutCompositionPixelFormat =
334 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
339 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
340 switch (tmpPrimaryDisplayOrientation) {
341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
353 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800355
Daniel Solomon42d04562019-01-20 21:03:19 -0800356 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
357 if (surfaceFlingerConfigsServiceV1_2) {
358 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
359 [&](auto tmpPrimaries) {
360 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
361 });
362 } else {
363 initDefaultDisplayNativePrimaries();
364 }
365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 // debugging stuff...
367 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700370 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 property_get("debug.sf.showupdates", value, "0");
373 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700375 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000376
377 // DDMS debugging deprecated (b/120782499)
378 property_get("debug.sf.ddms", value, "0");
379 int debugDdms = atoi(value);
380 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700381
382 property_get("debug.sf.disable_backpressure", value, "0");
383 mPropagateBackpressure = !atoi(value);
384 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700385
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800386 property_get("debug.sf.enable_hwc_vds", value, "0");
387 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800388 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800389
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800390 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800391 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800392 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700393
Yiwei Zhang243b3782018-05-15 17:40:04 -0700394 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700395 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
396 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
397
Ana Krulec98b5b242018-08-10 15:03:23 -0700398 property_get("debug.sf.use_scheduler", value, "0");
399 mUseScheduler = atoi(value);
400
Ady Abrahamc3e21312019-02-07 14:30:23 -0800401 if (!mUseScheduler) {
402 mPrimaryDispSync =
403 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
404 SurfaceFlinger::dispSyncPresentTimeOffset);
405 }
406
Ana Krulec757f63a2019-01-25 10:46:18 -0800407 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
408 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700409
Romain Guy11d63f42017-07-20 12:47:14 -0700410 // We should be reading 'persist.sys.sf.color_saturation' here
411 // but since /data may be encrypted, we need to wait until after vold
412 // comes online to attempt to read the property. The property is
413 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800414
415 if (useTrebleTestingOverride()) {
416 // Without the override SurfaceFlinger cannot connect to HIDL
417 // services that are not listed in the manifests. Considered
418 // deriving the setting from the set service name, but it
419 // would be brittle if the name that's not 'default' is used
420 // for production purposes later on.
421 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425void SurfaceFlinger::onFirstRef()
426{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800427 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430SurfaceFlinger::~SurfaceFlinger()
431{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Dan Stozac7014012014-02-14 15:03:43 -0800434void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435{
436 // the window manager died on us. prepare its eulogy.
437
Andy McFadden13a082e2012-08-24 10:16:42 -0700438 // restore initial conditions (default device unblank, etc)
439 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440
441 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700442 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443}
444
Robert Carr1db73f62016-12-21 12:58:51 -0800445static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700446 status_t err = client->initCheck();
447 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return nullptr;
451}
452
453sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
454 return initClient(new Client(this));
455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 // Display ID is assigned when virtual display is allocated by HWC.
478 DisplayDeviceState state;
479 state.isSecure = secure;
480 state.displayName = displayName;
481 mCurrentState.displays.add(token, state);
482 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
490 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
496 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 mInterceptor->saveDisplayDeletion(state.sequenceId);
501 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
506 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 const auto internalDisplayId = getInternalDisplayIdLocked();
509 if (!internalDisplayId) {
510 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 }
512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 std::vector<PhysicalDisplayId> displayIds;
514 displayIds.reserve(mPhysicalDisplayTokens.size());
515 displayIds.push_back(internalDisplayId->value);
516
517 for (const auto& [id, token] : mPhysicalDisplayTokens) {
518 if (id != *internalDisplayId) {
519 displayIds.push_back(id.value);
520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800523 return displayIds;
524}
525
526sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
527 Mutex::Autolock lock(mStateLock);
528 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
Ady Abraham37965d42018-11-01 13:43:32 -0700531status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
532 if (!outGetColorManagement) {
533 return BAD_VALUE;
534 }
535 *outGetColorManagement = useColorManagement;
536 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700537}
538
Lloyd Pique441d5042018-10-18 16:49:51 -0700539HWComposer& SurfaceFlinger::getHwComposer() const {
540 return mCompositionEngine->getHwComposer();
541}
542
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700543renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
544 return mCompositionEngine->getRenderEngine();
545}
546
Lloyd Pique70d91362018-10-18 16:02:55 -0700547compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
548 return *mCompositionEngine.get();
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551void SurfaceFlinger::bootFinished()
552{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700553 if (mStartPropertySetThread->join() != NO_ERROR) {
554 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556 const nsecs_t now = systemTime();
557 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000558 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559
560 // wait patiently for the window manager death
561 const String16 name("window");
562 sp<IBinder> window(defaultServiceManager()->getService(name));
563 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 }
Robert Carr720e5062018-07-30 17:45:14 -0700566 sp<IBinder> input(defaultServiceManager()->getService(
567 String16("inputflinger")));
568 if (input == nullptr) {
569 ALOGE("Failed to link to input service");
570 } else {
571 mInputFlinger = interface_cast<IInputFlinger>(input);
572 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 if (mVrFlinger) {
575 mVrFlinger->OnBootFinished();
576 }
577
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700579 // formerly we would just kill the process, but we now ask it to exit so it
580 // can choose where to stop the animation.
581 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700582
583 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
584 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
585 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700586
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800587 postMessageAsync(new LambdaMessage([this] {
588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
590 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800591}
592
Dan Stoza436ccf32018-06-21 12:10:12 -0700593uint32_t SurfaceFlinger::getNewTexture() {
594 {
595 std::lock_guard lock(mTexturePoolMutex);
596 if (!mTexturePool.empty()) {
597 uint32_t name = mTexturePool.back();
598 mTexturePool.pop_back();
599 ATRACE_INT("TexturePoolSize", mTexturePool.size());
600 return name;
601 }
602
603 // The pool was too small, so increase it for the future
604 ++mTexturePoolSize;
605 }
606
607 // The pool was empty, so we need to get a new texture name directly using a
608 // blocking call to the main thread
609 uint32_t name = 0;
610 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
611 return name;
612}
613
Mathias Agopian3f844832013-08-07 21:24:32 -0700614void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700615 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700616}
617
Wei Wangf9b05ee2017-07-19 20:59:39 -0700618// Do not call property_set on main thread which will be blocked by init
619// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700620void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700621 ALOGI( "SurfaceFlinger's main thread ready to run. "
622 "Initializing graphics H/W...");
623
Ana Krulec757f63a2019-01-25 10:46:18 -0800624 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627
Dominik Laskowski83b88212018-12-11 13:34:06 -0800628 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800632 mScheduler = getFactory().createScheduler(
633 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
634
Ana Krulec757f63a2019-01-25 10:46:18 -0800635 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
636 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
637 mPhaseOffsets->setRefreshRateType(
638 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700639
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 mAppConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800641 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800642 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700643 impl::EventThread::InterceptVSyncsCallback());
644 mSfConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800645 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800646 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 mInterceptor->saveVSyncEvent(timestamp);
648 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800649
Ana Krulec98b5b242018-08-10 15:03:23 -0700650 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700651 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
652 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 } else {
654 mEventThreadSource =
655 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800656 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 mEventThread =
658 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 impl::EventThread::InterceptVSyncsCallback(),
660 "appEventThread");
661 mSfEventThreadSource =
662 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800663 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700664
665 mSFEventThread =
666 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700667 [this](nsecs_t timestamp) {
668 mInterceptor->saveVSyncEvent(timestamp);
669 },
670 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800671 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700672 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700676 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700677 renderEngineFeature |= (useColorManagement ?
678 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700679 renderEngineFeature |= (useContextPriority ?
680 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700681
682 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700684 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700685 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700686
687 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
688 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700689 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
690 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800691 // Process any initial hotplug and resulting display changes.
692 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 const auto display = getDefaultDisplayDeviceLocked();
694 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800697
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700700 // This callback is called from the vr flinger dispatch thread. We
701 // need to call signalTransaction(), which requires holding
702 // mStateLock when we're not on the main thread. Acquiring
703 // mStateLock from the vr flinger dispatch thread might trigger a
704 // deadlock in surface flinger (see b/66916578), so post a message
705 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700706 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700707 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
708 mVrFlingerRequestsDisplay = requestDisplay;
709 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700710 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700712 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
713 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700714 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700715 .value_or(0),
716 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800717 if (!mVrFlinger) {
718 ALOGE("Failed to start vrflinger");
719 }
720 }
721
Ady Abrahamc3e21312019-02-07 14:30:23 -0800722 if (!mUseScheduler) {
723 mEventControlThread = getFactory().createEventControlThread(
724 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
725 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700726
Mathias Agopian92a979a2012-08-02 18:32:23 -0700727 // initialize our drawing state
728 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700729
Andy McFadden13a082e2012-08-24 10:16:42 -0700730 // set initial conditions (e.g. unblank default device)
731 initializeDisplays();
732
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700733 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700734
Wei Wangf9b05ee2017-07-19 20:59:39 -0700735 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700736
737 const bool presentFenceReliable =
738 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
739 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740
741 if (mStartPropertySetThread->Start() != NO_ERROR) {
742 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744
Ana Krulec7d1d6832018-12-27 11:10:09 -0800745 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800746 mScheduler->setExpiredIdleTimerCallback([this] {
747 Mutex::Autolock lock(mStateLock);
748 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800749 });
Ady Abrahama1a49af2019-02-07 14:36:55 -0800750 mScheduler->setResetIdleTimerCallback([this] {
751 Mutex::Autolock lock(mStateLock);
752 setRefreshRateTo(RefreshRateType::PERFORMANCE);
753 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800754
Alec Mourifb571ea2019-01-24 18:42:10 -0800755 mRefreshRateStats =
756 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
757 *display->getId()),
758 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800759 }
760
Dan Stoza9e56aa02015-11-02 13:00:03 -0800761 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700762}
763
Romain Guy11d63f42017-07-20 12:47:14 -0700764void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 Mutex::Autolock _l(mStateLock);
766
Romain Guy11d63f42017-07-20 12:47:14 -0700767 char value[PROPERTY_VALUE_MAX];
768
769 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800770 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700771 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800772 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100773
774 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700775 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700776}
777
Mathias Agopiana67e4182012-06-19 17:26:12 -0700778void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800779 // Start boot animation service by setting a property mailbox
780 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700781 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800782 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700783 if (mStartPropertySetThread->join() != NO_ERROR) {
784 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800785 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700786}
787
Mathias Agopian875d8e12013-06-07 15:35:48 -0700788size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700789 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700790}
791
Mathias Agopian875d8e12013-06-07 15:35:48 -0700792size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700793 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700794}
795
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800796// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800797
Jamie Gennis582270d2011-08-17 18:19:00 -0700798bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800799 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800800 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800801 return authenticateSurfaceTextureLocked(bufferProducer);
802}
803
804bool SurfaceFlinger::authenticateSurfaceTextureLocked(
805 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800806 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800807 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800808}
809
Brian Anderson6b376712017-04-04 10:51:39 -0700810status_t SurfaceFlinger::getSupportedFrameTimestamps(
811 std::vector<FrameEvent>* outSupported) const {
812 *outSupported = {
813 FrameEvent::REQUESTED_PRESENT,
814 FrameEvent::ACQUIRE,
815 FrameEvent::LATCH,
816 FrameEvent::FIRST_REFRESH_START,
817 FrameEvent::LAST_REFRESH_START,
818 FrameEvent::GPU_COMPOSITION_DONE,
819 FrameEvent::DEQUEUE_READY,
820 FrameEvent::RELEASE,
821 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700822 ConditionalLock _l(mStateLock,
823 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700824 if (!getHwComposer().hasCapability(
825 HWC2::Capability::PresentFenceIsNotReliable)) {
826 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
827 }
828 return NO_ERROR;
829}
830
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800831status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
832 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700833 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 return BAD_VALUE;
835 }
836
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800837 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700838 if (!displayId) {
839 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700840 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 // TODO: Not sure if display density should handled by SF any longer
843 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700844 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700845 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700846 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800847 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700848 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 }
850 return density;
851 }
852 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700853 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700854 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700855 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700856 return getDensityFromProperty("ro.sf.lcd_density"); }
857 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700858
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700860
Dominik Laskowski075d3172018-05-24 15:50:06 -0700861 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 DisplayInfo info = DisplayInfo();
863
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864 float xdpi = hwConfig->getDpiX();
865 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700866
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700867 info.w = hwConfig->getWidth();
868 info.h = hwConfig->getHeight();
869 // Default display viewport to display width and height
870 info.viewportW = info.w;
871 info.viewportH = info.h;
872
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800873 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700874 // The density of the device is provided by a build property
875 float density = Density::getBuildDensity() / 160.0f;
876 if (density == 0) {
877 // the build doesn't provide a density -- this is wrong!
878 // use xdpi instead
879 ALOGE("ro.sf.lcd_density must be defined as a build property");
880 density = xdpi / 160.0f;
881 }
882 if (Density::getEmuDensity()) {
883 // if "qemu.sf.lcd_density" is specified, it overrides everything
884 xdpi = ydpi = density = Density::getEmuDensity();
885 density /= 160.0f;
886 }
887 info.density = density;
888
889 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890 const auto display = getDefaultDisplayDeviceLocked();
891 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700892
893 // This is for screenrecord
894 const Rect viewport = display->getViewport();
895 if (viewport.isValid()) {
896 info.viewportW = uint32_t(viewport.getWidth());
897 info.viewportH = uint32_t(viewport.getHeight());
898 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 } else {
900 // TODO: where should this value come from?
901 static const int TV_DENSITY = 213;
902 info.density = TV_DENSITY / 160.0f;
903 info.orientation = 0;
904 }
905
Dan Stoza7f7da322014-05-02 15:26:25 -0700906 info.xdpi = xdpi;
907 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800908 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800909 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910
Andy McFadden91b2ca82014-06-13 14:04:23 -0700911 // This is how far in advance a buffer must be queued for
912 // presentation at a given time. If you want a buffer to appear
913 // on the screen at time N, you must submit the buffer before
914 // (N - presentationDeadline).
915 //
916 // Normally it's one full refresh period (to give SF a chance to
917 // latch the buffer), but this can be reduced by configuring a
918 // DispSync offset. Any additional delays introduced by the hardware
919 // composer or panel must be accounted for here.
920 //
921 // We add an additional 1ms to allow for processing time and
922 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800923 info.presentationDeadline =
924 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700925
926 // All non-virtual displays are currently considered secure.
927 info.secure = true;
928
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800929 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700930 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800931 std::swap(info.w, info.h);
932 }
933
Michael Wright28f24d02016-07-12 13:30:53 -0700934 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700935 }
936
Dan Stoza7f7da322014-05-02 15:26:25 -0700937 return NO_ERROR;
938}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
941 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700942 return BAD_VALUE;
943 }
944
Ana Krulece588e312018-09-18 12:32:24 -0700945 if (mUseScheduler) {
946 mScheduler->getDisplayStatInfo(stats);
947 } else {
948 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
949 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
950 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700951 return NO_ERROR;
952}
953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
955 const auto display = getDisplayDevice(displayToken);
956 if (!display) {
957 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800958 return BAD_VALUE;
959 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700960
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700961 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700962}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700963
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
965 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800966
Ana Krulec7d1d6832018-12-27 11:10:09 -0800967 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800968 // Lock is acquired by setRefreshRateTo.
969 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800970 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
971 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
972 return;
973 }
974
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975 // Lock is acquired by setRefreshRateTo.
976 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800977 if (!display) {
978 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
979 displayToken.get());
980 return;
981 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700982 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800983 ALOGW("Attempt to set active config %d for virtual display", mode);
984 return;
985 }
986 int currentDisplayPowerMode = display->getPowerMode();
987 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
988 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700989 return;
990 }
991
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992 // Don't check against the current mode yet. Worst case we set the desired
993 // config twice.
994 {
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
996 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
997 }
998 // This will trigger HWC refresh without resetting the idle timer.
999 repaintEverythingForHWC();
1000}
1001
1002status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1003 ATRACE_CALL();
1004 postMessageSync(new LambdaMessage(
1005 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1006 return NO_ERROR;
1007}
1008
1009void SurfaceFlinger::setActiveConfigInHWC() {
1010 ATRACE_CALL();
1011
1012 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1013 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001014 return;
1015 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001016 const auto displayId = display->getId();
1017 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001018
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1020 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1021 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1022 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1023}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001024
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001025void SurfaceFlinger::setActiveConfigInternal() {
1026 ATRACE_CALL();
1027
1028 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1029 if (mUseScheduler) {
1030 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1031 }
1032
1033 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1034 display->setActiveConfig(mUpcomingActiveConfig.configId);
1035
1036 mSetActiveConfigState = SetActiveConfigState::NONE;
1037 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1038
Dominik Laskowski83b88212018-12-11 13:34:06 -08001039 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001040 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1041}
1042
1043bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1044 // Store the local variable to release the lock.
1045 ActiveConfigInfo desiredActiveConfig;
1046 {
1047 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1048 desiredActiveConfig = mDesiredActiveConfig;
1049 }
1050
1051 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1052 if (display) {
1053 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1054 display->getActiveConfig() != desiredActiveConfig.configId) {
1055 // Step 1) Desired active config was set, it is different than the
1056 // config currently in use. Notify HWC.
1057 mUpcomingActiveConfig = desiredActiveConfig;
1058 setActiveConfigInHWC();
1059 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1060 // Step 2) HWC was notified and we received refresh from it.
1061 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1062 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1063 repaintEverythingForHWC();
1064 // We do not want to give another frame to HWC while we are transitioning.
1065 return false;
1066 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1067 !(mPreviousPresentFence != Fence::NO_FENCE &&
1068 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1069 // Step 3) We received the present fence from the HWC, so we assume it
1070 // successfully updated the config, hence we update SF.
1071 setActiveConfigInternal();
1072 // If the config changed again while we were transitioning, restart the
1073 // process.
1074 if (desiredActiveConfig != mUpcomingActiveConfig) {
1075 mUpcomingActiveConfig = desiredActiveConfig;
1076 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1077 }
1078 }
1079 }
1080 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001081}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001082
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001083status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1084 Vector<ColorMode>* outColorModes) {
1085 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001086 return BAD_VALUE;
1087 }
1088
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001090 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001091 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1092
1093 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1094 if (!displayId) {
1095 return NAME_NOT_FOUND;
1096 }
1097
Dominik Laskowski075d3172018-05-24 15:50:06 -07001098 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001099 }
Michael Wright28f24d02016-07-12 13:30:53 -07001100 outColorModes->clear();
1101 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1102
1103 return NO_ERROR;
1104}
1105
Daniel Solomon42d04562019-01-20 21:03:19 -08001106status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1107 ui::DisplayPrimaries &primaries) {
1108 if (!displayToken) {
1109 return BAD_VALUE;
1110 }
1111
1112 // Currently we only support this API for a single internal display.
1113 if (getInternalDisplayToken() != displayToken) {
1114 return BAD_VALUE;
1115 }
1116
1117 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1118 return NO_ERROR;
1119}
1120
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1122 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001123 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001124 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001125 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001126}
1127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001129 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130 Vector<ColorMode> modes;
1131 getDisplayColorModes(displayToken, &modes);
1132 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1133 if (mode < ColorMode::NATIVE || !exists) {
1134 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1135 decodeColorMode(mode).c_str(), mode, displayToken.get());
1136 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001137 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001138 const auto display = getDisplayDevice(displayToken);
1139 if (!display) {
1140 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1141 decodeColorMode(mode).c_str(), mode, displayToken.get());
1142 } else if (display->isVirtual()) {
1143 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1144 decodeColorMode(mode).c_str(), mode);
1145 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001146 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1147 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001148 }
1149 }));
1150
Michael Wright28f24d02016-07-12 13:30:53 -07001151 return NO_ERROR;
1152}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001153
Svetoslavd85084b2014-03-20 10:28:31 -07001154status_t SurfaceFlinger::clearAnimationFrameStats() {
1155 Mutex::Autolock _l(mStateLock);
1156 mAnimFrameTracker.clearStats();
1157 return NO_ERROR;
1158}
1159
1160status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1161 Mutex::Autolock _l(mStateLock);
1162 mAnimFrameTracker.getStats(outStats);
1163 return NO_ERROR;
1164}
1165
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001166status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1167 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001168 Mutex::Autolock _l(mStateLock);
1169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001170 const auto display = getDisplayDeviceLocked(displayToken);
1171 if (!display) {
1172 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001173 return BAD_VALUE;
1174 }
1175
Peiyong Linfb069302018-04-25 14:34:31 -07001176 // At this point the DisplayDeivce should already be set up,
1177 // meaning the luminance information is already queried from
1178 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001179 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001180 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1181 capabilities.getDesiredMaxLuminance(),
1182 capabilities.getDesiredMaxAverageLuminance(),
1183 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001184
1185 return NO_ERROR;
1186}
1187
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001188status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1189 ui::PixelFormat* outFormat,
1190 ui::Dataspace* outDataspace,
1191 uint8_t* outComponentMask) const {
1192 if (!outFormat || !outDataspace || !outComponentMask) {
1193 return BAD_VALUE;
1194 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001195 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001196 if (!display || !display->getId()) {
1197 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1198 return BAD_VALUE;
1199 }
1200 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1201 outDataspace, outComponentMask);
1202}
1203
Kevin DuBois74e53772018-11-19 10:52:38 -08001204status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1205 bool enable, uint8_t componentMask,
1206 uint64_t maxFrames) const {
1207 const auto display = getDisplayDevice(displayToken);
1208 if (!display || !display->getId()) {
1209 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1210 return BAD_VALUE;
1211 }
1212
1213 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1214 componentMask, maxFrames);
1215}
1216
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001217status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1218 uint64_t maxFrames, uint64_t timestamp,
1219 DisplayedFrameStats* outStats) const {
1220 const auto display = getDisplayDevice(displayToken);
1221 if (!display || !display->getId()) {
1222 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1223 return BAD_VALUE;
1224 }
1225
1226 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1227 outStats);
1228}
1229
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001230status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1231 if (!outSupported) {
1232 return BAD_VALUE;
1233 }
1234 *outSupported = getRenderEngine().supportsProtectedContent();
1235 return NO_ERROR;
1236}
1237
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001238status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1239 bool* outIsWideColorDisplay) const {
1240 if (!displayToken || !outIsWideColorDisplay) {
1241 return BAD_VALUE;
1242 }
1243 Mutex::Autolock _l(mStateLock);
1244 const auto display = getDisplayDeviceLocked(displayToken);
1245 if (!display) {
1246 return BAD_VALUE;
1247 }
1248 *outIsWideColorDisplay = display->hasWideColorGamut();
1249 return NO_ERROR;
1250}
1251
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001252status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001253 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001254 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001255
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 if (mInjectVSyncs == enable) {
1257 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001259
Dominik Laskowski83b88212018-12-11 13:34:06 -08001260 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261
Ana Krulec98b5b242018-08-10 15:03:23 -07001262 // TODO(akrulec): Part of the Injector should be refactored, so that it
1263 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001264 if (enable) {
1265 ALOGV("VSync Injections enabled");
1266 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001267 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001268 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001269 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001270 impl::EventThread::InterceptVSyncsCallback(),
1271 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001273 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001274 } else {
1275 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001276 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277 }
1278
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001279 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001280 }));
1281
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001282 return NO_ERROR;
1283}
1284
1285status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001286 Mutex::Autolock _l(mStateLock);
1287
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001288 if (!mInjectVSyncs) {
1289 ALOGE("VSync Injections not enabled");
1290 return BAD_VALUE;
1291 }
1292 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1293 ALOGV("Injecting VSync inside SurfaceFlinger");
1294 mVSyncInjector->onInjectSyncEvent(when);
1295 }
1296 return NO_ERROR;
1297}
1298
Lloyd Pique755e3192018-01-31 16:46:15 -08001299status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1300 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001301 // Try to acquire a lock for 1s, fail gracefully
1302 const status_t err = mStateLock.timedLock(s2ns(1));
1303 const bool locked = (err == NO_ERROR);
1304 if (!locked) {
1305 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1306 return TIMED_OUT;
1307 }
1308
1309 outLayers->clear();
1310 mCurrentState.traverseInZOrder([&](Layer* layer) {
1311 outLayers->push_back(layer->getLayerDebugInfo());
1312 });
1313
1314 mStateLock.unlock();
1315 return NO_ERROR;
1316}
1317
Peiyong Linc6780972018-10-28 15:24:08 -07001318status_t SurfaceFlinger::getCompositionPreference(
1319 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1320 Dataspace* outWideColorGamutDataspace,
1321 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001322 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001323 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001324 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001325 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001326 return NO_ERROR;
1327}
1328
Dan Stoza84ab9372018-12-17 15:27:57 -08001329status_t SurfaceFlinger::addRegionSamplingListener(
1330 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1331 const sp<IRegionSamplingListener>& /*listener*/) {
1332 return NO_ERROR;
1333}
1334
1335status_t SurfaceFlinger::removeRegionSamplingListener(
1336 const sp<IRegionSamplingListener>& /*listener*/) {
1337 return NO_ERROR;
1338}
1339
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001340// ----------------------------------------------------------------------------
1341
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001342sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1343 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001344 auto resyncCallback = makeResyncCallback([this] {
1345 Mutex::Autolock lock(mStateLock);
1346 return getVsyncPeriod();
1347 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001348
Ana Krulec98b5b242018-08-10 15:03:23 -07001349 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001350 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1351 : mAppConnectionHandle;
1352
Ady Abrahama1a49af2019-02-07 14:36:55 -08001353 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001354 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001355 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001356 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001357 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001358 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001359 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001360 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001361}
1362
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001363// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001364
1365void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001366 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367}
1368
1369void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001370 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001371}
1372
1373void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001374 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001375}
1376
1377void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001378 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001379 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001380}
1381
1382status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001383 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001384 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001385}
1386
1387status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001388 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001389 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001390 if (res == NO_ERROR) {
1391 msg->wait();
1392 }
1393 return res;
1394}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001395
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001396void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001397 do {
1398 waitForEvent();
1399 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001400}
1401
Dominik Laskowski83b88212018-12-11 13:34:06 -08001402nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001403 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001404 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1405 return 0;
1406 }
1407
1408 const auto config = getHwComposer().getActiveConfig(*displayId);
1409 return config ? config->getVsyncPeriod() : 0;
1410}
1411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001412void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001413 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001414 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001415 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001416 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001417 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001418 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001419 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001420}
1421
Dominik Laskowski83b88212018-12-11 13:34:06 -08001422void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001423 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001424 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1425 if (mUseScheduler) {
1426 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001427 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001428 } else if (!mScheduler->getHWSyncAvailable()) {
1429 // Hardware vsync is not currently available, so abort the resync
1430 // attempt for now
1431 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001432 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001433 } else {
1434 if (makeAvailable) {
1435 mHWVsyncAvailable = true;
1436 } else if (!mHWVsyncAvailable) {
1437 // Hardware vsync is not currently available, so abort the resync
1438 // attempt for now
1439 return;
1440 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001441 }
1442
Dominik Laskowski83b88212018-12-11 13:34:06 -08001443 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001444 return;
1445 }
1446
Ana Krulece588e312018-09-18 12:32:24 -07001447 if (mUseScheduler) {
1448 mScheduler->setVsyncPeriod(period);
1449 } else {
1450 mPrimaryDispSync->reset();
1451 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001452
Ana Krulece588e312018-09-18 12:32:24 -07001453 if (!mPrimaryHWVsyncEnabled) {
1454 mPrimaryDispSync->beginResync();
1455 mEventControlThread->setVsyncEnabled(true);
1456 mPrimaryHWVsyncEnabled = true;
1457 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001458 }
1459}
1460
Jesse Hall948fe0c2013-10-14 12:56:09 -07001461void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001462 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001463 Mutex::Autolock _l(mHWVsyncLock);
1464 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001465 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001466 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001467 mPrimaryHWVsyncEnabled = false;
1468 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001469 if (makeUnavailable) {
1470 mHWVsyncAvailable = false;
1471 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001472}
1473
Dominik Laskowski83b88212018-12-11 13:34:06 -08001474void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001475 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001476
Dan Stoza57164302017-05-08 14:03:54 -07001477 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001478 const nsecs_t last = lastResyncTime.exchange(now);
1479
1480 if (now - last > kIgnoreDelay) {
1481 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001482 }
1483}
1484
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001485void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1486 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001487 ATRACE_NAME("SF onVsync");
1488
Steven Thomas3cfac282017-02-06 12:29:30 -08001489 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001491 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001492 return;
1493 }
1494
Dominik Laskowski075d3172018-05-24 15:50:06 -07001495 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001496 return;
1497 }
1498
Dominik Laskowski075d3172018-05-24 15:50:06 -07001499 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001500 // For now, we don't do anything with external display vsyncs.
1501 return;
1502 }
1503
Ana Krulece588e312018-09-18 12:32:24 -07001504 if (mUseScheduler) {
1505 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001506 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001507 bool needsHwVsync = false;
1508 { // Scope for the lock
1509 Mutex::Autolock _l(mHWVsyncLock);
1510 if (mPrimaryHWVsyncEnabled) {
1511 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1512 }
1513 }
1514
1515 if (needsHwVsync) {
1516 enableHardwareVsync();
1517 } else {
1518 disableHardwareVsync(false);
1519 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001520 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001521}
1522
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001523void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001524 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1525 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001526}
1527
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001528void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1529 mPhaseOffsets->setRefreshRateType(refreshRate);
1530
1531 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1532 mVsyncModulator.setPhaseOffsets(early, gl, late);
1533
1534 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001535 return;
1536 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001537
Ana Krulec7d1d6832018-12-27 11:10:09 -08001538 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1539 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1540 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1541 // refresh cycle.
1542
1543 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001544 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001545 if (currentVsyncPeriod == 0) {
1546 return;
1547 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001548
Ana Krulec7d1d6832018-12-27 11:10:09 -08001549 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1550 // floating numbers.
1551 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001552 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1553 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001554 if (std::abs(currentFps - newFps) <= 1) {
1555 return;
1556 }
1557
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001558 const auto displayId = getInternalDisplayIdLocked();
1559 LOG_ALWAYS_FATAL_IF(!displayId);
1560
1561 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001562 for (int i = 0; i < configs.size(); i++) {
1563 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1564 if (vsyncPeriod == 0) {
1565 continue;
1566 }
1567 const float fps = 1e9 / vsyncPeriod;
1568 // TODO(b/113612090): There should be a better way at determining which config
1569 // has the right refresh rate.
1570 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001571 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001572 }
1573 }
1574}
1575
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001576void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001577 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001578 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001579 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001580
Lloyd Piqueba04e622017-12-14 17:11:26 -08001581 // Ignore events that do not have the right sequenceId.
1582 if (sequenceId != getBE().mComposerSequenceId) {
1583 return;
1584 }
1585
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 // Only lock if we're not on the main thread. This function is normally
1587 // called on a hwbinder thread, but for the primary display it's called on
1588 // the main thread with the state lock already held, so don't attempt to
1589 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001590 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001591
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001592 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001593
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001594 if (std::this_thread::get_id() == mMainThreadId) {
1595 // Process all pending hot plug events immediately if we are on the main thread.
1596 processDisplayHotplugEventsLocked();
1597 }
1598
Lloyd Piqueba04e622017-12-14 17:11:26 -08001599 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001600}
1601
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001602void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001603 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001604 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001605 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001606 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001607 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001608}
1609
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001610void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001611 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001612 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001613 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001614 getHwComposer().setVsyncEnabled(*displayId,
1615 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1616 }
Mathias Agopian86303202012-07-24 22:46:10 -07001617}
1618
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001619// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001620void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001621 if (mUseScheduler) {
1622 mScheduler->disableHardwareVsync(true);
1623 } else {
1624 disableHardwareVsync(true);
1625 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001626 // Clear the drawing state so that the logic inside of
1627 // handleTransactionLocked will fire. It will determine the delta between
1628 // mCurrentState and mDrawingState and re-apply all changes when we make the
1629 // transition.
1630 mDrawingState.displays.clear();
1631 mDisplays.clear();
1632}
1633
Steven Thomas050b2c82017-03-06 11:45:16 -08001634void SurfaceFlinger::updateVrFlinger() {
1635 if (!mVrFlinger)
1636 return;
1637 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001638 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001639 return;
1640 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001641
Lloyd Pique441d5042018-10-18 16:49:51 -07001642 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 ALOGE("Vr flinger is only supported for remote hardware composer"
1644 " service connections. Ignoring request to transition to vr"
1645 " flinger.");
1646 mVrFlingerRequestsDisplay = false;
1647 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001648 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001649
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001650 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001651
Steven Thomas0123ac62018-07-12 11:32:34 -07001652 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001653 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001654
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001655 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001656
1657 // Clear out all the output layers from the composition engine for all
1658 // displays before destroying the hardware composer interface. This ensures
1659 // any HWC layers are destroyed through that interface before it becomes
1660 // invalid.
1661 for (const auto& [token, displayDevice] : mDisplays) {
1662 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1663 compositionengine::Output::OutputLayers());
1664 }
1665
Steven Thomas0123ac62018-07-12 11:32:34 -07001666 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1667 // called below. Clear the reference now so we don't accidentally use it
1668 // later.
1669 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001670
Steven Thomasb02664d2017-07-26 18:48:28 -07001671 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001672 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001673 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001674
Steven Thomasb02664d2017-07-26 18:48:28 -07001675 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001676 // Delete the current instance before creating the new one
1677 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1679 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1680 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001681
Lloyd Pique441d5042018-10-18 16:49:51 -07001682 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001683 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001684
1685 if (vrFlingerRequestsDisplay) {
1686 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001687 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001688
1689 mVisibleRegionsDirty = true;
1690 invalidateHwcGeometry();
1691
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001692 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001693 display = getDefaultDisplayDeviceLocked();
1694 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001695 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001696
Steven Thomasb02664d2017-07-26 18:48:28 -07001697 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001698 const nsecs_t vsyncPeriod = getVsyncPeriod();
1699 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001700
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001701 // The present fences returned from vr_hwc are not an accurate
1702 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001703 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001704 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1705 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001706 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001707 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001708 !hasSyncFramework);
1709 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001710
Steven Thomasb02664d2017-07-26 18:48:28 -07001711 // Use phase of 0 since phase is not known.
1712 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001713 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001714 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001715
Dominik Laskowski83b88212018-12-11 13:34:06 -08001716 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001717
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001718 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001719 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001720}
1721
Mathias Agopian4fec8732012-06-29 14:12:52 -07001722void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001723 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001724 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001725 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001726 if (!updateSetActiveConfigStateMachine()) {
1727 break;
1728 }
1729
Ana Krulec3084c052018-11-21 20:27:17 +01001730 if (mUseScheduler) {
1731 // This call is made each time SF wakes up and creates a new frame.
1732 mScheduler->incrementFrameCounter();
1733 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001734 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1735 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001736 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001737 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001738 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001739 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001740 if (mPropagateBackpressure) {
1741 signalLayerUpdate();
1742 break;
1743 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001744 }
Dan Stoza50182882016-07-08 12:02:20 -07001745
Steven Thomas050b2c82017-03-06 11:45:16 -08001746 // Now that we're going to make it to the handleMessageTransaction()
1747 // call below it's safe to call updateVrFlinger(), which will
1748 // potentially trigger a display handoff.
1749 updateVrFlinger();
1750
Dan Stoza6b9454d2014-11-07 16:00:59 -08001751 bool refreshNeeded = handleMessageTransaction();
1752 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001753
1754 updateCursorAsync();
1755 updateInputFlinger();
1756
Dan Stoza58784442014-12-02 16:58:17 -08001757 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001758 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001759 // Signal a refresh if a transaction modified the window state,
1760 // a new buffer was latched, or if HWC has requested a full
1761 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001762 signalRefresh();
1763 }
1764 break;
1765 }
1766 case MessageQueue::REFRESH: {
1767 handleMessageRefresh();
1768 break;
1769 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001770 }
1771}
1772
Dan Stoza6b9454d2014-11-07 16:00:59 -08001773bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001774 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001775
1776 // Apply any ready transactions in the queues if there are still transactions that have not been
1777 // applied, wake up during the next vsync period and check again
1778 bool transactionNeeded = false;
1779 if (!flushTransactionQueues()) {
1780 transactionNeeded = true;
1781 }
1782
Mathias Agopian4fec8732012-06-29 14:12:52 -07001783 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001784 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001785 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001786
1787 if (transactionNeeded) {
1788 setTransactionFlags(eTransactionNeeded);
1789 }
1790
1791 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001792}
1793
Mathias Agopian4fec8732012-06-29 14:12:52 -07001794void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001795 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001796
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001797 mRefreshPending = false;
1798
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001799 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001800 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001801 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001802 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001803 for (const auto& [token, display] : mDisplays) {
1804 beginFrame(display);
1805 prepareFrame(display);
1806 doDebugFlashRegions(display, repaintEverything);
1807 doComposition(display, repaintEverything);
1808 }
1809
Adrian Roos1e1a1282017-11-01 19:05:31 +01001810 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001811 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001812
1813 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001814 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001815
Dan Stozabfbffeb2016-07-21 14:49:33 -07001816 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001817 for (const auto& [token, displayDevice] : mDisplays) {
1818 auto display = displayDevice->getCompositionDisplay();
1819 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001820 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001821 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001822 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001823
Alec Mouri86770e52018-09-24 22:40:58 +00001824 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001825 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001826 if (mHadClientComposition) {
1827 base::unique_fd flushFence(getRenderEngine().flush());
1828 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1829 getBE().flushFence = new Fence(std::move(flushFence));
1830 } else {
1831 // Cleanup for hygiene.
1832 getBE().flushFence = Fence::NO_FENCE;
1833 }
1834 }
1835
Jorim Jaggi90535212018-05-23 23:44:06 +02001836 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001837
David Sodman7e4ae112018-02-09 15:02:28 -08001838 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001839
1840 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001841}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001842
David Sodmanfa9b2af2017-12-24 13:28:59 -08001843
1844bool SurfaceFlinger::handleMessageInvalidate() {
1845 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001846 bool refreshNeeded = handlePageFlip();
1847
Vishnu Nair4351ad52019-02-11 14:13:02 -08001848 if (mVisibleRegionsDirty) {
1849 computeLayerBounds();
1850 }
1851
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001852 for (auto& layer : mLayersPendingRefresh) {
1853 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001854 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001855 invalidateLayerStack(layer, visibleReg);
1856 }
1857 mLayersPendingRefresh.clear();
1858 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001859}
1860
David Sodman79bba0e2018-08-05 18:07:49 -07001861void SurfaceFlinger::calculateWorkingSet() {
1862 ATRACE_CALL();
1863 ALOGV(__FUNCTION__);
1864
David Sodman79bba0e2018-08-05 18:07:49 -07001865 // build the h/w work list
1866 if (CC_UNLIKELY(mGeometryInvalid)) {
1867 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868 for (const auto& [token, displayDevice] : mDisplays) {
1869 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001870 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001871 if (!displayId) {
1872 continue;
1873 }
David Sodman79bba0e2018-08-05 18:07:49 -07001874
Lloyd Pique32cbe282018-10-19 13:09:22 -07001875 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001876 for (size_t i = 0; i < currentLayers.size(); i++) {
1877 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001878
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001879 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001880 layer->forceClientComposition(displayDevice);
1881 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001882 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001883
Lloyd Pique32cbe282018-10-19 13:09:22 -07001884 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001885 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001886 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001887 }
David Sodman79bba0e2018-08-05 18:07:49 -07001888 }
1889 }
1890 }
1891
1892 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001893 for (const auto& [token, displayDevice] : mDisplays) {
1894 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001895 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001896 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001897 continue;
1898 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001899 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001900
1901 if (mDrawingState.colorMatrixChanged) {
1902 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001903 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001904 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001905 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001906 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001907 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1908 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001909 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001910 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001911 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1912 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001913 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001914 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001915 }
1916
Peiyong Lind3788632018-09-18 16:01:31 -07001917 // TODO(b/111562338) remove when composer 2.3 is shipped.
1918 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001919 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001920 }
1921
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001922 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001923 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001924 }
1925
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001926 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001927 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001928 layer->setCompositionType(displayDevice,
1929 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001930 continue;
1931 }
1932
Lloyd Pique32cbe282018-10-19 13:09:22 -07001933 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001934 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001935 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001936 }
1937
Peiyong Lin13effd12018-07-24 17:01:47 -07001938 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001939 ColorMode colorMode;
1940 Dataspace dataSpace;
1941 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001942 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001943 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001944 }
1945 }
1946
1947 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001948
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001949 for (const auto& [token, displayDevice] : mDisplays) {
1950 auto display = displayDevice->getCompositionDisplay();
1951 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001952 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001953 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1954 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1955 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001956 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001957 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001958 }
1959 }
David Sodman79bba0e2018-08-05 18:07:49 -07001960}
1961
Lloyd Pique32cbe282018-10-19 13:09:22 -07001962void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1963 bool repaintEverything) {
1964 auto display = displayDevice->getCompositionDisplay();
1965 const auto& displayState = display->getState();
1966
Mathias Agopiancd60f992012-08-16 16:28:27 -07001967 // is debugging enabled
1968 if (CC_LIKELY(!mDebugRegion))
1969 return;
1970
Lloyd Pique32cbe282018-10-19 13:09:22 -07001971 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001972 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001973 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001974 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001975 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001976 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001977 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001979 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001980 }
1981 }
1982
Lloyd Pique32cbe282018-10-19 13:09:22 -07001983 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001984
1985 if (mDebugRegion > 1) {
1986 usleep(mDebugRegion * 1000);
1987 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001988
Lloyd Pique32cbe282018-10-19 13:09:22 -07001989 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990}
1991
Adrian Roos1e1a1282017-11-01 19:05:31 +01001992void SurfaceFlinger::doTracing(const char* where) {
1993 ATRACE_CALL();
1994 ATRACE_NAME(where);
1995 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001996 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001997 }
1998}
1999
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002000void SurfaceFlinger::logLayerStats() {
2001 ATRACE_CALL();
2002 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002003 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002004 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002005 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002006 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002007 }
2008 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002009
2010 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002011 }
2012}
2013
David Sodman2b406362017-12-15 13:33:47 -08002014void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002016 ATRACE_CALL();
2017 ALOGV("preComposition");
2018
David Sodman2b406362017-12-15 13:33:47 -08002019 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2020
Mathias Agopiancd60f992012-08-16 16:28:27 -07002021 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002022 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002023 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002024 needExtraInvalidate = true;
2025 }
Robert Carr2047fae2016-11-28 14:09:09 -08002026 });
2027
Mathias Agopiancd60f992012-08-16 16:28:27 -07002028 if (needExtraInvalidate) {
2029 signalLayerUpdate();
2030 }
2031}
2032
Ana Krulece588e312018-09-18 12:32:24 -07002033void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2034 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002035 // Update queue of past composite+present times and determine the
2036 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002037 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002039 while (!getBE().mCompositePresentTimes.empty()) {
2040 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041 // Cached values should have been updated before calling this method,
2042 // which helps avoid duplicate syscalls.
2043 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2044 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2045 break;
2046 }
2047 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002048 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 }
2050
2051 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002052 while (getBE().mCompositePresentTimes.size() > 16) {
2053 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 }
2055
Ana Krulece588e312018-09-18 12:32:24 -07002056 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002057}
2058
Ana Krulece588e312018-09-18 12:32:24 -07002059void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2060 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061 // Integer division and modulo round toward 0 not -inf, so we need to
2062 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002063 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2064 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2065 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066
Ana Krulec757f63a2019-01-25 10:46:18 -08002067 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002068 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002069 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002070 }
2071
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072 // Snap the latency to a value that removes scheduling jitter from the
2073 // composition and present times, which often have >1ms of jitter.
2074 // Reducing jitter is important if an app attempts to extrapolate
2075 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002076 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002078 nsecs_t bias = stats.vsyncPeriod / 2;
2079 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2080 nsecs_t snappedCompositeToPresentLatency =
2081 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002082
David Sodman99974d22017-11-28 12:04:33 -08002083 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002084 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2085 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002086 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002087}
2088
Ady Abraham8164d482019-01-11 14:47:59 -08002089// debug patch for b/119477596 - add stack guards to catch stack
2090// corruptions and disable clang optimizations.
2091// The code below is temporary and planned to be removed once stack
2092// corruptions are found.
2093#pragma clang optimize off
2094class StackGuard {
2095public:
2096 StackGuard(const char* name, const char* func, int line) {
2097 guarders.reserve(MIN_CAPACITY);
2098 guarders.push_back({this, name, func, line});
2099 validate();
2100 }
2101 ~StackGuard() {
2102 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2103 if (i->guard == this) {
2104 guarders.erase(i);
2105 break;
2106 }
2107 }
2108 }
2109
2110 static void validate() {
2111 for (const auto& guard : guarders) {
2112 if (guard.guard->cookie != COOKIE_VALUE) {
2113 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2114 CallStack stack(LOG_TAG);
2115 abort();
2116 }
2117 }
2118 }
2119
2120private:
2121 uint64_t cookie = COOKIE_VALUE;
2122 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2123 static constexpr size_t MIN_CAPACITY = 16;
2124
2125 struct GuarderElement {
2126 StackGuard* guard;
2127 const char* name;
2128 const char* func;
2129 int line;
2130 };
2131
2132 static std::vector<GuarderElement> guarders;
2133};
2134std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2135
2136#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2137
2138#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002139void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002140{
Ady Abraham8164d482019-01-11 14:47:59 -08002141 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 ATRACE_CALL();
2143 ALOGV("postComposition");
2144
Brian Anderson3546a3f2016-07-14 11:51:14 -07002145 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002146 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002147 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002148 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002149 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002150 }
Ady Abraham8164d482019-01-11 14:47:59 -08002151 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002152
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002153 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002154 const auto displayDevice = getDefaultDisplayDeviceLocked();
2155 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156
David Sodman73beded2017-11-15 11:56:06 -08002157 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002158 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002159 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2160
Lloyd Pique32cbe282018-10-19 13:09:22 -07002161 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002162 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002163 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2164 ->getRenderSurface()
2165 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002166 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002167 } else {
2168 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2169 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002170
Ady Abraham8164d482019-01-11 14:47:59 -08002171 ASSERT_ON_STACK_GUARD();
2172
David Sodman73beded2017-11-15 11:56:06 -08002173 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002174 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2175 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002176 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002177 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002178 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002179
Ana Krulece588e312018-09-18 12:32:24 -07002180 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002181 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002182 if (mUseScheduler) {
2183 mScheduler->getDisplayStatInfo(&stats);
2184 } else {
2185 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2186 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2187 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002188
Ady Abraham8164d482019-01-11 14:47:59 -08002189 ASSERT_ON_STACK_GUARD();
2190
David Sodman2b406362017-12-15 13:33:47 -08002191 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002192 // when we started doing work for this frame, but that should be okay
2193 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002194 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002195 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002196 DEFINE_STACK_GUARD(compositorTiming);
2197
Brian Andersond0010582017-03-07 13:20:31 -08002198 {
David Sodman99974d22017-11-28 12:04:33 -08002199 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002200 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002201 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002202
2203 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002204 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002205
Robert Carr2047fae2016-11-28 14:09:09 -08002206 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002207 bool frameLatched =
2208 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2209 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002210 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002211 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002212 recordBufferingStats(layer->getName().string(),
2213 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002214 }
Ady Abraham8164d482019-01-11 14:47:59 -08002215 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002216 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002217
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002218 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002219 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002220 if (mUseScheduler) {
2221 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002222 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002223 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002224 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2225 enableHardwareVsync();
2226 } else {
2227 disableHardwareVsync(false);
2228 }
Ady Abraham8164d482019-01-11 14:47:59 -08002229 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002230 }
2231 }
2232
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002233 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002234 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2235 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002236 if (mUseScheduler) {
2237 mScheduler->enableHardwareVsync();
2238 } else {
2239 enableHardwareVsync();
2240 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002241 }
2242 }
2243
Ady Abraham8164d482019-01-11 14:47:59 -08002244 ASSERT_ON_STACK_GUARD();
2245
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002246 if (mAnimCompositionPending) {
2247 mAnimCompositionPending = false;
2248
Brian Anderson4e606e32017-03-16 15:34:57 -07002249 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002250 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002251 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002252
2253 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002254 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002255 // The HWC doesn't support present fences, so use the refresh
2256 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 const nsecs_t presentTime =
2258 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002259 DEFINE_STACK_GUARD(presentTime);
2260
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002261 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002262 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002263 }
2264 mAnimFrameTracker.advanceFrame();
2265 }
Dan Stozab90cf072015-03-05 11:05:59 -08002266
Ady Abraham8164d482019-01-11 14:47:59 -08002267 ASSERT_ON_STACK_GUARD();
2268
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002269 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002270 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002271 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002272 }
2273
Ady Abraham8164d482019-01-11 14:47:59 -08002274 ASSERT_ON_STACK_GUARD();
2275
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002276 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002277
Ady Abraham8164d482019-01-11 14:47:59 -08002278 ASSERT_ON_STACK_GUARD();
2279
Lloyd Pique32cbe282018-10-19 13:09:22 -07002280 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2281 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002282 return;
2283 }
2284
2285 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002286 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002287 if (mHasPoweredOff) {
2288 mHasPoweredOff = false;
2289 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002290 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002291 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002292 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002293 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002294 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2295 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002296 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002297 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002298 }
David Sodman4a36e932017-11-07 14:29:47 -08002299 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002300
2301 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002302 }
David Sodman4a36e932017-11-07 14:29:47 -08002303 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002304 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002305
2306 {
2307 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002308 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002309 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002310 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002311 if (refillCount > 0) {
2312 const size_t offset = mTexturePool.size();
2313 mTexturePool.resize(mTexturePoolSize);
2314 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2315 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2316 }
Ady Abraham8164d482019-01-11 14:47:59 -08002317 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002318 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002319
Marissa Wallfda30bb2018-10-12 11:34:28 -07002320 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002321 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002322
2323 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002324}
Ady Abraham8164d482019-01-11 14:47:59 -08002325#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002326
Vishnu Nair4351ad52019-02-11 14:13:02 -08002327void SurfaceFlinger::computeLayerBounds() {
2328 for (const auto& pair : mDisplays) {
2329 const auto& displayDevice = pair.second;
2330 const auto display = displayDevice->getCompositionDisplay();
2331 for (const auto& layer : mDrawingState.layersSortedByZ) {
2332 // only consider the layers on the given layer stack
2333 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002334 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002335 }
2336
2337 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2338 }
2339 }
2340}
2341
Mathias Agopiancd60f992012-08-16 16:28:27 -07002342void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002343 ATRACE_CALL();
2344 ALOGV("rebuildLayerStacks");
2345
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002346 // We need to clear these out now as these may be holding on to a
2347 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2348 // also holds a reference. When the set of visible layers is recomputed,
2349 // some layers may be destroyed if the only thing keeping them alive was
2350 // that list of visible layers associated with each display. The layer
2351 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2352 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2353 for (const auto& [token, display] : mDisplays) {
2354 getBE().mCompositionInfo[token].clear();
2355 }
2356
Mathias Agopiancd60f992012-08-16 16:28:27 -07002357 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002358 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002359 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002360 mVisibleRegionsDirty = false;
2361 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002362
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002363 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002364 const auto& displayDevice = pair.second;
2365 auto display = displayDevice->getCompositionDisplay();
2366 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002367 Region opaqueRegion;
2368 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002369 compositionengine::Output::OutputLayers layersSortedByZ;
2370 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002371 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372 const ui::Transform& tr = displayState.transform;
2373 const Rect bounds = displayState.bounds;
2374 if (displayState.isEnabled) {
2375 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002376
Jeff Sharkey76488112017-02-27 14:15:18 -07002377 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002378 auto compositionLayer = layer->getCompositionLayer();
2379 if (compositionLayer == nullptr) {
2380 return;
2381 }
2382
Lloyd Pique32cbe282018-10-19 13:09:22 -07002383 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002384 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2385 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2386
Lloyd Pique07e33212018-12-18 16:33:37 -08002387 bool needsOutputLayer = false;
2388
Lloyd Piqueef36b002019-01-23 17:52:04 -08002389 if (display->belongsInOutput(layer->getLayerStack(),
2390 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002391 Region drawRegion(tr.transform(
2392 layer->visibleNonTransparentRegion));
2393 drawRegion.andSelf(bounds);
2394 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002395 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002396 }
Chia-I Wu83806892017-11-16 10:50:20 -08002397 }
2398
Lloyd Pique07e33212018-12-18 16:33:37 -08002399 if (needsOutputLayer) {
2400 layersSortedByZ.emplace_back(
2401 display->getOrCreateOutputLayer(displayId, compositionLayer,
2402 layerFE));
2403 deprecated_layersSortedByZ.add(layer);
2404
2405 auto& outputLayerState = layersSortedByZ.back()->editState();
2406 outputLayerState.visibleRegion =
2407 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2408 } else if (displayId) {
2409 // For layers that are being removed from a HWC display,
2410 // and that have queued frames, add them to a a list of
2411 // released layers so we can properly set a fence.
2412 bool hasExistingOutputLayer =
2413 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2414 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2415 mLayersWithQueuedFrames.cend(),
2416 layer) != mLayersWithQueuedFrames.cend();
2417
2418 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002419 layersNeedingFences.add(layer);
2420 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002421 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002422 });
2423 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002424
2425 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2426
2427 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002428 displayDevice->setLayersNeedingFences(layersNeedingFences);
2429
2430 Region undefinedRegion{bounds};
2431 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2432
2433 display->editState().undefinedRegion = undefinedRegion;
2434 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002435 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002436 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002437}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002438
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002439// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002440// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002441// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002442// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002443// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002444// The returned HDR data space is one of
2445// - Dataspace::UNKNOWN
2446// - Dataspace::BT2020_HLG
2447// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2449 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002450 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002451 *outHdrDataSpace = Dataspace::UNKNOWN;
2452
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002453 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002454 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002455 case Dataspace::V0_SCRGB:
2456 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002457 case Dataspace::BT2020:
2458 case Dataspace::BT2020_ITU:
2459 case Dataspace::BT2020_LINEAR:
2460 case Dataspace::DISPLAY_BT2020:
2461 bestDataSpace = Dataspace::DISPLAY_BT2020;
2462 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002463 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002464 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002465 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002466 case Dataspace::BT2020_PQ:
2467 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002468 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002469 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002470 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002471 case Dataspace::BT2020_HLG:
2472 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002473 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002474 // When there's mixed PQ content and HLG content, we set the HDR
2475 // data space to be BT2020_PQ and convert HLG to PQ.
2476 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2477 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002478 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002479 break;
2480 default:
2481 break;
2482 }
Romain Guy54f154a2017-10-24 21:40:32 +01002483 }
2484
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002485 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002486}
2487
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002488// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002489void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2490 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002491 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2492 *outMode = ColorMode::NATIVE;
2493 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002494 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002495 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002496 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002497
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002498 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002500
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002501 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2502
Peiyong Lindfde5112018-06-05 10:58:41 -07002503 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002504 const bool isHdr =
2505 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002506 if (isHdr) {
2507 bestDataSpace = hdrDataSpace;
2508 }
2509
Chia-I Wu0d711262018-05-21 15:19:35 -07002510 RenderIntent intent;
2511 switch (mDisplayColorSetting) {
2512 case DisplayColorSetting::MANAGED:
2513 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002514 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002515 break;
2516 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002517 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002518 break;
2519 default: // vendor display color setting
2520 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2521 break;
2522 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002523
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002524 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002525}
2526
Lloyd Pique32cbe282018-10-19 13:09:22 -07002527void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2528 auto display = displayDevice->getCompositionDisplay();
2529 const auto& displayState = display->getState();
2530
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002531 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2533 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002534
David Sodmanfa9b2af2017-12-24 13:28:59 -08002535 // If nothing has changed (!dirty), don't recompose.
2536 // If something changed, but we don't currently have any visible layers,
2537 // and didn't when we last did a composition, then skip it this time.
2538 // The second rule does two things:
2539 // - When all layers are removed from a display, we'll emit one black
2540 // frame, then nothing more until we get new layers.
2541 // - When a display is created with a private layer stack, we won't
2542 // emit any black frames until a layer is added to the layer stack.
2543 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 const char flagPrefix[] = {'-', '+'};
2546 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002547 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2548 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2549 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2550 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002551
Lloyd Pique31cb2942018-10-19 17:23:03 -07002552 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002553
David Sodmanfa9b2af2017-12-24 13:28:59 -08002554 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002555 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002556 }
2557}
2558
Lloyd Pique32cbe282018-10-19 13:09:22 -07002559void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2560 auto display = displayDevice->getCompositionDisplay();
2561 const auto& displayState = display->getState();
2562
2563 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002564 return;
David Sodman2b406362017-12-15 13:33:47 -08002565 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002566
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002567 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002569 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002570}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002571
Lloyd Pique32cbe282018-10-19 13:09:22 -07002572void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002573 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 ALOGV("doComposition");
2575
Lloyd Pique32cbe282018-10-19 13:09:22 -07002576 auto display = displayDevice->getCompositionDisplay();
2577 const auto& displayState = display->getState();
2578
2579 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002580 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002581 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002582
David Sodmanfa9b2af2017-12-24 13:28:59 -08002583 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002584 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002585
Lloyd Pique32cbe282018-10-19 13:09:22 -07002586 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002587 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002588 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002589 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002590}
2591
David Sodmanfa9b2af2017-12-24 13:28:59 -08002592void SurfaceFlinger::postFrame()
2593{
2594 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 const auto display = getDefaultDisplayDeviceLocked();
2596 if (display && getHwComposer().isConnected(*display->getId())) {
2597 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002598 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2599 logFrameStats();
2600 }
2601 }
2602}
2603
Lloyd Pique32cbe282018-10-19 13:09:22 -07002604void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002605 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002607
Lloyd Pique32cbe282018-10-19 13:09:22 -07002608 auto display = displayDevice->getCompositionDisplay();
2609 const auto& displayState = display->getState();
2610 const auto displayId = display->getId();
2611
David Sodmanfa9b2af2017-12-24 13:28:59 -08002612 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002613
Lloyd Pique32cbe282018-10-19 13:09:22 -07002614 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 if (displayId) {
2616 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002617 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002618 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002619 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002620 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002621
Chia-I Wu7b549592017-11-15 09:14:57 -08002622 // The layer buffer from the previous frame (if any) is released
2623 // by HWC only when the release fence from this frame (if any) is
2624 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002625 if (displayId && layer->hasHwcLayer(displayDevice)) {
2626 releaseFence =
2627 getHwComposer().getLayerReleaseFence(*displayId,
2628 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002629 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002630
2631 // If the layer was client composited in the previous frame, we
2632 // need to merge with the previous client target acquire fence.
2633 // Since we do not track that, always merge with the current
2634 // client target acquire fence when it is available, even though
2635 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002636 if (layer->getCompositionType(displayDevice) ==
2637 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002638 releaseFence =
2639 Fence::merge("LayerRelease", releaseFence,
2640 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002641 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002642
David Sodman15094112018-10-11 09:39:37 -07002643 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 }
Chia-I Wu83806892017-11-16 10:50:20 -08002645
2646 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002647 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002648 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002649 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002651 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002652 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002653 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002654 }
2655 }
2656
Dominik Laskowski075d3172018-05-24 15:50:06 -07002657 if (displayId) {
2658 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002659 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002660 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661}
2662
Mathias Agopian87baae12012-07-31 12:38:26 -07002663void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664{
Mathias Agopian841cde52012-03-01 15:44:37 -08002665 ATRACE_CALL();
2666
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002667 // here we keep a copy of the drawing state (that is the state that's
2668 // going to be overwritten by handleTransactionLocked()) outside of
2669 // mStateLock so that the side-effects of the State assignment
2670 // don't happen with mStateLock held (which can cause deadlocks).
2671 State drawingState(mDrawingState);
2672
Mathias Agopianca4d3602011-05-19 15:38:14 -07002673 Mutex::Autolock _l(mStateLock);
2674 const nsecs_t now = systemTime();
2675 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002676
Mathias Agopianca4d3602011-05-19 15:38:14 -07002677 // Here we're guaranteed that some transaction flags are set
2678 // so we can call handleTransactionLocked() unconditionally.
2679 // We call getTransactionFlags(), which will also clear the flags,
2680 // with mStateLock held to guarantee that mCurrentState won't change
2681 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002682
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002683 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002684 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002685 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002686
Mathias Agopianca4d3602011-05-19 15:38:14 -07002687 mLastTransactionTime = systemTime() - now;
2688 mDebugInTransaction = 0;
2689 invalidateHwcGeometry();
2690 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002691}
2692
Lloyd Piqueba04e622017-12-14 17:11:26 -08002693void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2694 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002695 const std::optional<DisplayIdentificationInfo> info =
2696 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002697
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002699 continue;
2700 }
2701
Lloyd Piqueba04e622017-12-14 17:11:26 -08002702 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002704 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 mPhysicalDisplayTokens[info->id] = new BBinder();
2706 DisplayDeviceState state;
2707 state.displayId = info->id;
2708 state.isSecure = true; // All physical displays are currently considered secure.
2709 state.displayName = info->name;
2710 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2711 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002712 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002713 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002714 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002715
Dominik Laskowski075d3172018-05-24 15:50:06 -07002716 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2717 if (index >= 0) {
2718 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2719 mInterceptor->saveDisplayDeletion(state.sequenceId);
2720 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002721 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002722 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002723 }
2724
2725 processDisplayChangesLocked();
2726 }
2727
2728 mPendingHotplugEvents.clear();
2729}
2730
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002731void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002732 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002733 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2734 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002735 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002736 mEventThread->onHotplugReceived(displayId, connected);
2737 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002738 }
2739}
2740
Lloyd Pique99d3da52018-01-22 17:48:03 -08002741sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002742 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002743 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002744 const sp<IGraphicBufferProducer>& producer) {
2745 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002746 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002748 creationArgs.isSecure = state.isSecure;
2749 creationArgs.displaySurface = dispSurface;
2750 creationArgs.hasWideColorGamut = false;
2751 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002752
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002753 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002754 creationArgs.isPrimary = isInternalDisplay;
2755
2756 if (useColorManagement && displayId) {
2757 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002758 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002759 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002760 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002761 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002762
Dominik Laskowski7e045462018-05-30 13:02:02 -07002763 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002764 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002765 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002766 }
tangrobin6753a022018-08-10 10:58:54 +08002767 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 if (displayId) {
2770 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002771 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002772 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002773 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002774
Lloyd Pique90c115d2018-09-18 21:39:42 -07002775 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002776 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002777 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002778
Lloyd Pique99d3da52018-01-22 17:48:03 -08002779 // Make sure that composition can never be stalled by a virtual display
2780 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002781 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002782 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002783 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2784 }
2785
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 creationArgs.displayInstallOrientation =
2787 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002788
Lloyd Pique99d3da52018-01-22 17:48:03 -08002789 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002790 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002791
Lloyd Pique90c115d2018-09-18 21:39:42 -07002792 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002793
2794 if (maxFrameBufferAcquiredBuffers >= 3) {
2795 nativeWindowSurface->preallocateBuffers();
2796 }
2797
2798 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002799 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002800 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002801 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002802 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002803 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002804 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2805 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002806 if (!state.isVirtual()) {
2807 LOG_ALWAYS_FATAL_IF(!displayId);
2808 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002809 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002810
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002811 display->setLayerStack(state.layerStack);
2812 display->setProjection(state.orientation, state.viewport, state.frame);
2813 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002814
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002815 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002816}
2817
Lloyd Pique347200f2017-12-14 17:00:15 -08002818void SurfaceFlinger::processDisplayChangesLocked() {
2819 // here we take advantage of Vector's copy-on-write semantics to
2820 // improve performance by skipping the transaction entirely when
2821 // know that the lists are identical
2822 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2823 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2824 if (!curr.isIdenticalTo(draw)) {
2825 mVisibleRegionsDirty = true;
2826 const size_t cc = curr.size();
2827 size_t dc = draw.size();
2828
2829 // find the displays that were removed
2830 // (ie: in drawing state but not in current state)
2831 // also handle displays that changed
2832 // (ie: displays that are in both lists)
2833 for (size_t i = 0; i < dc;) {
2834 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2835 if (j < 0) {
2836 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002837 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002838 // Save display ID before disconnecting.
2839 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002840 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002841
2842 if (!display->isVirtual()) {
2843 LOG_ALWAYS_FATAL_IF(!displayId);
2844 dispatchDisplayHotplugEvent(displayId->value, false);
2845 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002846 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002847
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002849 } else {
2850 // this display is in both lists. see if something changed.
2851 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002852 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002853 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2854 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2855 if (state_binder != draw_binder) {
2856 // changing the surface is like destroying and
2857 // recreating the DisplayDevice, so we just remove it
2858 // from the drawing state, so that it get re-added
2859 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002860 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002861 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002862 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002863 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002864 mDrawingState.displays.removeItemsAt(i);
2865 dc--;
2866 // at this point we must loop to the next item
2867 continue;
2868 }
2869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002870 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002871 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002873 }
2874 if ((state.orientation != draw[i].orientation) ||
2875 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002876 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002877 }
2878 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002879 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002880 }
2881 }
2882 }
2883 ++i;
2884 }
2885
2886 // find displays that were added
2887 // (ie: in current state but not in drawing state)
2888 for (size_t i = 0; i < cc; i++) {
2889 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2890 const DisplayDeviceState& state(curr[i]);
2891
Lloyd Pique542307f2018-10-19 13:24:08 -07002892 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002893 sp<IGraphicBufferProducer> producer;
2894 sp<IGraphicBufferProducer> bqProducer;
2895 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002896 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002897
Dominik Laskowski075d3172018-05-24 15:50:06 -07002898 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002899 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002900 // Virtual displays without a surface are dormant:
2901 // they have external state (layer stack, projection,
2902 // etc.) but no internal state (i.e. a DisplayDevice).
2903 if (state.surface != nullptr) {
2904 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002905 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002906 int width = 0;
2907 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2908 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2909 int height = 0;
2910 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2911 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2912 int intFormat = 0;
2913 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2914 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002915 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002916
Dominik Laskowski075d3172018-05-24 15:50:06 -07002917 displayId =
2918 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002919 }
2920
2921 // TODO: Plumb requested format back up to consumer
2922
2923 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002924 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002925 bqProducer, bqConsumer,
2926 state.displayName);
2927
2928 dispSurface = vds;
2929 producer = vds;
2930 }
2931 } else {
2932 ALOGE_IF(state.surface != nullptr,
2933 "adding a supported display, but rendering "
2934 "surface is provided (%p), ignoring it",
2935 state.surface.get());
2936
Dominik Laskowski075d3172018-05-24 15:50:06 -07002937 displayId = state.displayId;
2938 LOG_ALWAYS_FATAL_IF(!displayId);
2939 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002940 producer = bqProducer;
2941 }
2942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002943 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002944 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002945 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002946 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002947 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002948 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002949 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002950 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002951 }
2952 }
2953 }
2954 }
2955 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002956
2957 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002958}
2959
Mathias Agopian87baae12012-07-31 12:38:26 -07002960void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002961{
Dan Stoza7dde5992015-05-22 09:51:44 -07002962 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002963 mCurrentState.traverseInZOrder([](Layer* layer) {
2964 layer->notifyAvailableFrames();
2965 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967 /*
2968 * Traversal of the children
2969 * (perform the transaction for each of them if needed)
2970 */
2971
Mathias Agopian3559b072012-08-15 13:46:03 -07002972 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002973 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002975 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976
2977 const uint32_t flags = layer->doTransaction(0);
2978 if (flags & Layer::eVisibleRegion)
2979 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002980
2981 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002982 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002983 }
Robert Carr2047fae2016-11-28 14:09:09 -08002984 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 }
2986
2987 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002988 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 */
2990
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002992 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002993 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002994 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002996 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002997 // The transform hint might have changed for some layers
2998 // (either because a display has changed, or because a layer
2999 // as changed).
3000 //
3001 // Walk through all the layers in currentLayers,
3002 // and update their transform hint.
3003 //
3004 // If a layer is visible only on a single display, then that
3005 // display is used to calculate the hint, otherwise we use the
3006 // default display.
3007 //
3008 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
3009 // the hint is set before we acquire a buffer from the surface texture.
3010 //
3011 // NOTE: layer transactions have taken place already, so we use their
3012 // drawing state. However, SurfaceFlinger's own transaction has not
3013 // happened yet, so we must use the current state layer list
3014 // (soon to become the drawing state list).
3015 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003016 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08003017 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08003018 bool first = true;
3019 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08003020 // NOTE: we rely on the fact that layers are sorted by
3021 // layerStack first (so we don't have to traverse the list
3022 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08003024 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08003025 currentlayerStack = layerStack;
3026 // figure out if this layerstack is mirrored
3027 // (more than one display) if so, pick the default display,
3028 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003029 hintDisplay = nullptr;
3030 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08003031 if (display->getCompositionDisplay()
3032 ->belongsInOutput(layer->getLayerStack(),
3033 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003034 if (hintDisplay) {
3035 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003036 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003037 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003038 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003039 }
3040 }
3041 }
3042 }
Chet Haase91d25932013-04-11 15:24:55 -07003043
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003044 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003045 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3046 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003047
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003048 // could be null when this layer is using a layerStack
3049 // that is not visible on any display. Also can occur at
3050 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003051 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003052 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003053
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003054 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003055 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003056 if (hintDisplay) {
3057 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003058 }
Robert Carr2047fae2016-11-28 14:09:09 -08003059
3060 first = false;
3061 });
Mathias Agopian84300952012-11-21 16:02:13 -08003062 }
3063
3064
Mathias Agopian3559b072012-08-15 13:46:03 -07003065 /*
3066 * Perform our own transaction if needed
3067 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003068
3069 if (mLayersAdded) {
3070 mLayersAdded = false;
3071 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003072 mVisibleRegionsDirty = true;
3073 }
3074
3075 // some layers might have been removed, so
3076 // we need to update the regions they're exposing.
3077 if (mLayersRemoved) {
3078 mLayersRemoved = false;
3079 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003080 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003081 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003082 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003083 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003084 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003085 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003086 }
Robert Carr2047fae2016-11-28 14:09:09 -08003087 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088 }
3089
3090 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003091}
3092
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003093void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003094 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003095 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003096 return;
3097 }
3098
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003099 if (mVisibleRegionsDirty || mInputInfoChanged) {
3100 mInputInfoChanged = false;
3101 updateInputWindowInfo();
3102 }
3103
3104 executeInputWindowCommands();
3105}
3106
3107void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003108 Vector<InputWindowInfo> inputHandles;
3109
3110 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3111 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003112 // When calculating the screen bounds we ignore the transparent region since it may
3113 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003114 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003115 }
3116 });
3117 mInputFlinger->setInputWindows(inputHandles);
3118}
3119
chaviwfbe5d9c2018-12-26 12:23:37 -08003120void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003121 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3122 if (transferTouchFocusCommand.fromToken != nullptr &&
3123 transferTouchFocusCommand.toToken != nullptr &&
3124 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3125 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3126 transferTouchFocusCommand.toToken);
3127 }
3128 }
3129
3130 mInputWindowCommands.clear();
3131}
3132
Riley Andrews03414a12014-07-01 14:22:59 -07003133void SurfaceFlinger::updateCursorAsync()
3134{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003135 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003136 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003137 continue;
3138 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003139
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003140 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3141 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003142 }
3143 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144}
3145
chaviw61626f22018-11-15 16:26:27 -08003146void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3147 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003148 nsecs_t expectedPresentTime;
3149 if (mUseScheduler) {
3150 expectedPresentTime = mScheduler->expectedPresentTime();
3151 } else {
3152 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3153 }
chaviw61626f22018-11-15 16:26:27 -08003154 if (layer->shouldPresentNow(expectedPresentTime)) {
3155 bool ignored = false;
3156 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3157 }
3158 }
3159 layer->releasePendingBuffer(systemTime());
3160}
3161
Mathias Agopian4fec8732012-06-29 14:12:52 -07003162void SurfaceFlinger::commitTransaction()
3163{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003164 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003165 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 for (const auto& l : mLayersPendingRemoval) {
3167 recordBufferingStats(l->getName().string(),
3168 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003169
Lloyd Pique07e33212018-12-18 16:33:37 -08003170 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003171 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003172 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003173 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003174 }
3175 mLayersPendingRemoval.clear();
3176 }
3177
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003178 // If this transaction is part of a window animation then the next frame
3179 // we composite should be considered an animation as well.
3180 mAnimCompositionPending = mAnimTransactionPending;
3181
Mathias Agopian4fec8732012-06-29 14:12:52 -07003182 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003183 // clear the "changed" flags in current state
3184 mCurrentState.colorMatrixChanged = false;
3185
Robert Carr1f0a16a2016-10-24 16:27:39 -07003186 mDrawingState.traverseInZOrder([](Layer* layer) {
3187 layer->commitChildList();
3188 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003189 mTransactionPending = false;
3190 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003191 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192}
3193
Lloyd Pique32cbe282018-10-19 13:09:22 -07003194void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003195 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003196 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003197 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003198
Lloyd Pique32cbe282018-10-19 13:09:22 -07003199 auto display = displayDevice->getCompositionDisplay();
3200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 Region aboveOpaqueLayers;
3202 Region aboveCoveredLayers;
3203 Region dirty;
3204
Mathias Agopian87baae12012-07-31 12:38:26 -07003205 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206
Robert Carr2047fae2016-11-28 14:09:09 -08003207 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003208 // start with the whole surface at its current location
3209 const Layer::State& s(layer->getDrawingState());
3210
Jesse Hall01e29052013-02-19 16:13:35 -08003211 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003212 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003213 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003214 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003215
Mathias Agopianab028732010-03-16 16:41:46 -07003216 /*
3217 * opaqueRegion: area of a surface that is fully opaque.
3218 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003220
3221 /*
3222 * visibleRegion: area of a surface that is visible on screen
3223 * and not fully transparent. This is essentially the layer's
3224 * footprint minus the opaque regions above it.
3225 * Areas covered by a translucent surface are considered visible.
3226 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003228
3229 /*
3230 * coveredRegion: area of a surface that is covered by all
3231 * visible regions above it (which includes the translucent areas).
3232 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003234
Jesse Halla8026d22012-09-25 13:25:04 -07003235 /*
3236 * transparentRegion: area of a surface that is hinted to be completely
3237 * transparent. This is only used to tell when the layer has no visible
3238 * non-transparent regions and can be removed from the layer list. It
3239 * does not affect the visibleRegion of this layer or any layers
3240 * beneath it. The hint may not be correct if apps don't respect the
3241 * SurfaceView restrictions (which, sadly, some don't).
3242 */
3243 Region transparentRegion;
3244
Mathias Agopianab028732010-03-16 16:41:46 -07003245
3246 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003247 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003248 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003249 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003250
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003251 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003252 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003253 if (!visibleRegion.isEmpty()) {
3254 // Remove the transparent area from the visible region
3255 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003256 if (tr.preserveRects()) {
3257 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003258 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003259 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003260 // transformation too complex, can't do the
3261 // transparent region optimization.
3262 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003263 }
Mathias Agopianab028732010-03-16 16:41:46 -07003264 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265
Mathias Agopianab028732010-03-16 16:41:46 -07003266 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003267 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003268 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003269 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003270 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003271 // the opaque region is the layer's footprint
3272 opaqueRegion = visibleRegion;
3273 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 }
3275 }
3276
Robert Carre5f4f692018-01-12 13:12:28 -08003277 if (visibleRegion.isEmpty()) {
3278 layer->clearVisibilityRegions();
3279 return;
3280 }
3281
Mathias Agopianab028732010-03-16 16:41:46 -07003282 // Clip the covered region to the visible region
3283 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3284
3285 // Update aboveCoveredLayers for next (lower) layer
3286 aboveCoveredLayers.orSelf(visibleRegion);
3287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288 // subtract the opaque region covered by the layers above us
3289 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290
3291 // compute this layer's dirty region
3292 if (layer->contentDirty) {
3293 // we need to invalidate the whole region
3294 dirty = visibleRegion;
3295 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003296 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297 layer->contentDirty = false;
3298 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003299 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003300 * the exposed region consists of two components:
3301 * 1) what's VISIBLE now and was COVERED before
3302 * 2) what's EXPOSED now less what was EXPOSED before
3303 *
3304 * note that (1) is conservative, we start with the whole
3305 * visible region but only keep what used to be covered by
3306 * something -- which mean it may have been exposed.
3307 *
3308 * (2) handles areas that were not covered by anything but got
3309 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003310 */
Mathias Agopianab028732010-03-16 16:41:46 -07003311 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003312 const Region oldVisibleRegion = layer->visibleRegion;
3313 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003314 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3315 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316 }
3317 dirty.subtractSelf(aboveOpaqueLayers);
3318
3319 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003320 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321
Mathias Agopianab028732010-03-16 16:41:46 -07003322 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003324
Jesse Halla8026d22012-09-25 13:25:04 -07003325 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003326 layer->setVisibleRegion(visibleRegion);
3327 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003328 layer->setVisibleNonTransparentRegion(
3329 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003330 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331
Mathias Agopian87baae12012-07-31 12:38:26 -07003332 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003333}
3334
Chia-I Wuab0c3192017-08-01 11:29:00 -07003335void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003336 for (const auto& [token, displayDevice] : mDisplays) {
3337 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003338 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003340 }
3341 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003342}
3343
Daniel Solomon42d04562019-01-20 21:03:19 -08003344void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3345 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3346 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3347 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3348 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3349 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3350 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3351 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3352 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3353 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3354 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3355 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3356 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3357}
3358
Dan Stoza6b9454d2014-11-07 16:00:59 -08003359bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003360{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003361 ALOGV("handlePageFlip");
3362
Brian Andersond6927fb2016-07-23 23:37:30 -07003363 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003364
Mathias Agopian4fec8732012-06-29 14:12:52 -07003365 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003366 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003367 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003368
3369 // Store the set of layers that need updates. This set must not change as
3370 // buffers are being latched, as this could result in a deadlock.
3371 // Example: Two producers share the same command stream and:
3372 // 1.) Layer 0 is latched
3373 // 2.) Layer 0 gets a new frame
3374 // 2.) Layer 1 gets a new frame
3375 // 3.) Layer 1 is latched.
3376 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3377 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003378 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003379 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003380 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003381 nsecs_t expectedPresentTime;
3382 if (mUseScheduler) {
3383 expectedPresentTime = mScheduler->expectedPresentTime();
3384 } else {
3385 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3386 }
Ana Krulec010d2192018-10-08 06:29:54 -07003387 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003388 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003389 } else {
3390 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003391 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003392 } else {
3393 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003394 }
Robert Carr2047fae2016-11-28 14:09:09 -08003395 });
3396
Lloyd Piquef2c79392018-12-20 16:23:33 -08003397 if (!mLayersWithQueuedFrames.empty()) {
3398 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3399 // writes to Layer current state. See also b/119481871
3400 Mutex::Autolock lock(mStateLock);
3401
3402 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003403 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3404 mLayersPendingRefresh.push_back(layer);
3405 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003406 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003407 if (layer->isBufferLatched()) {
3408 newDataLatched = true;
3409 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003410 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003411 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003412
Alec Mouri86770e52018-09-24 22:40:58 +00003413 // Clear the renderengine fence here...
3414 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3415 // clear instead of sp::clear.
3416 getBE().flushFence = Fence::NO_FENCE;
3417
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003418 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003419
3420 // If we will need to wake up at some time in the future to deal with a
3421 // queued frame that shouldn't be displayed during this vsync period, wake
3422 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003423 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003424 signalLayerUpdate();
3425 }
3426
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003427 // enter boot animation on first buffer latch
3428 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3429 ALOGI("Enter boot animation");
3430 mBootStage = BootStage::BOOTANIMATION;
3431 }
3432
Dan Stoza6b9454d2014-11-07 16:00:59 -08003433 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003434 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003435}
3436
Mathias Agopianad456f92011-01-13 17:53:01 -08003437void SurfaceFlinger::invalidateHwcGeometry()
3438{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003439 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003440}
3441
Lloyd Pique32cbe282018-10-19 13:09:22 -07003442void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003443 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003444 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003445 // We only need to actually compose the display if:
3446 // 1) It is being handled by hardware composer, which may need this to
3447 // keep its virtual display state machine in sync, or
3448 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003449 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003450 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003451 return;
3452 }
3453
Dan Stoza9e56aa02015-11-02 13:00:03 -08003454 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003455 base::unique_fd readyFence;
3456 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003457
3458 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003459 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460}
3461
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003462bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3463 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003464 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003465 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003466
Lloyd Pique32cbe282018-10-19 13:09:22 -07003467 auto display = displayDevice->getCompositionDisplay();
3468 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003469 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003470
3471 const Region bounds(displayState.bounds);
3472 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003473 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003474 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003475
Peiyong Lind3788632018-09-18 16:01:31 -07003476 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003477 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003478
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003479 renderengine::DisplaySettings clientCompositionDisplay;
3480 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3481 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003482
Dan Stoza9e56aa02015-11-02 13:00:03 -08003483 if (hasClientComposition) {
3484 ALOGV("hasClientComposition");
3485
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003486 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003487
3488 if (buf == nullptr) {
3489 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3490 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003491 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003492 return false;
3493 }
3494
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003495 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3496 clientCompositionDisplay.clip = displayState.scissor;
3497 const ui::Transform& displayTransform = displayState.transform;
3498 mat4 m;
3499 m[0][0] = displayTransform[0][0];
3500 m[0][1] = displayTransform[0][1];
3501 m[0][3] = displayTransform[0][2];
3502 m[1][0] = displayTransform[1][0];
3503 m[1][1] = displayTransform[1][1];
3504 m[1][3] = displayTransform[1][2];
3505 m[3][0] = displayTransform[2][0];
3506 m[3][1] = displayTransform[2][1];
3507 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003508
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003509 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003510
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003511 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003512 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003513 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003514 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003515 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003516 clientCompositionDisplay.outputDataspace = outputDataspace;
3517 clientCompositionDisplay.maxLuminance =
3518 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003519
Lloyd Pique441d5042018-10-18 16:49:51 -07003520 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003521 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003522 getHwComposer()
3523 .hasDisplayCapability(displayId,
3524 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003525
Peiyong Lind3788632018-09-18 16:01:31 -07003526 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003527 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3528 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003529 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003530 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003531 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003532
Mathias Agopian85d751c2012-08-29 16:59:24 -07003533 /*
3534 * and then, render the layers targeted at the framebuffer
3535 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003536
Dan Stoza9e56aa02015-11-02 13:00:03 -08003537 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003538 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003539 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003540 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003541 const Region viewportRegion(displayState.viewport);
3542 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003543 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003544 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003545 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003546 switch (layer->getCompositionType(displayDevice)) {
3547 case Hwc2::IComposerClient::Composition::CURSOR:
3548 case Hwc2::IComposerClient::Composition::DEVICE:
3549 case Hwc2::IComposerClient::Composition::SIDEBAND:
3550 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003551 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003552 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003553 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003554 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003555 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003556 // never clear the very first layer since we're
3557 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003558 renderengine::LayerSettings layerSettings;
3559 Region dummyRegion;
3560 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3561 layerSettings);
3562
3563 if (prepared) {
3564 layerSettings.source.buffer.buffer = nullptr;
3565 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3566 layerSettings.alpha = half(0.0);
3567 layerSettings.disableBlending = true;
3568 clientCompositionLayers.push_back(layerSettings);
3569 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003570 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003571 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003572 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003573 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003574 renderengine::LayerSettings layerSettings;
3575 bool prepared =
3576 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3577 if (prepared) {
3578 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003579 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003580 break;
3581 }
3582 default:
3583 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003584 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003585 } else {
3586 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003587 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003588 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003589 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003590
Alec Mouri820c7402019-01-23 13:02:39 -08003591 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003592 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003593 clientCompositionDisplay.clearRegion = clearRegion;
3594 if (!debugRegion.isEmpty()) {
3595 Region::const_iterator it = debugRegion.begin();
3596 Region::const_iterator end = debugRegion.end();
3597 while (it != end) {
3598 const Rect& rect = *it++;
3599 renderengine::LayerSettings layerSettings;
3600 layerSettings.source.buffer.buffer = nullptr;
3601 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3602 layerSettings.geometry.boundaries = rect.toFloatRect();
3603 layerSettings.alpha = half(1.0);
3604 clientCompositionLayers.push_back(layerSettings);
3605 }
3606 }
3607 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3608 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003609 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003610 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611}
3612
Chia-I Wu28e3a252018-09-07 12:05:02 -07003613void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003614 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003615 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616}
3617
Dan Stoza7d89d062015-04-30 13:29:25 -07003618status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003619 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003620 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003621 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003622 const sp<Layer>& parent,
3623 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003624{
Dan Stoza7d89d062015-04-30 13:29:25 -07003625 // add this layer to the current state list
3626 {
3627 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003628 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003629 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3630 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003631 return NO_MEMORY;
3632 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003633 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003634 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003635 } else if (parent == nullptr) {
3636 lbc->onRemovedFromCurrentState();
3637 } else if (parent->isRemovedFromCurrentState()) {
3638 parent->addChild(lbc);
3639 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003640 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003641 parent->addChild(lbc);
3642 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003643
Yiwei Zhang243b3782018-05-15 17:40:04 -07003644 if (gbc != nullptr) {
3645 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3646 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3647 mMaxGraphicBufferProducerListSize,
3648 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3649 mGraphicBufferProducerList.size(),
3650 mMaxGraphicBufferProducerListSize, mNumLayers);
3651 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003652 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003653 }
3654
Mathias Agopian96f08192010-06-02 23:28:45 -07003655 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003656 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003657
Dan Stoza7d89d062015-04-30 13:29:25 -07003658 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003659}
3660
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003661uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003662 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003663}
3664
Mathias Agopian3f844832013-08-07 21:24:32 -07003665uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003666 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667}
3668
Mathias Agopian3f844832013-08-07 21:24:32 -07003669uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003670 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003671}
3672
3673uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003674 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003675 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003676 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003677 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003678 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679 }
3680 return old;
3681}
3682
Marissa Wall713b63f2018-10-17 15:42:43 -07003683bool SurfaceFlinger::flushTransactionQueues() {
3684 Mutex::Autolock _l(mStateLock);
3685 auto it = mTransactionQueues.begin();
3686 while (it != mTransactionQueues.end()) {
3687 auto& [applyToken, transactionQueue] = *it;
3688
3689 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003690 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3691 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003692 break;
3693 }
chaviw273171b2018-12-26 11:46:30 -08003694 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003695 transactionQueue.pop();
3696 }
3697
3698 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3699 }
3700 return mTransactionQueues.empty();
3701}
3702
chaviwca27f252018-02-06 16:46:39 -08003703bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3704 for (const ComposerState& state : states) {
3705 // Here we need to check that the interface we're given is indeed
3706 // one of our own. A malicious client could give us a nullptr
3707 // IInterface, or one of its own or even one of our own but a
3708 // different type. All these situations would cause us to crash.
3709 if (state.client == nullptr) {
3710 return true;
3711 }
3712
3713 sp<IBinder> binder = IInterface::asBinder(state.client);
3714 if (binder == nullptr) {
3715 return true;
3716 }
3717
3718 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3719 return true;
3720 }
3721 }
3722 return false;
3723}
3724
Marissa Wall17b4e452018-12-26 16:32:34 -08003725bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3726 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003727 nsecs_t expectedPresentTime;
3728 if (mUseScheduler) {
3729 expectedPresentTime = mScheduler->expectedPresentTime();
3730 } else {
3731 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3732 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003733 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3734 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3735 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3736 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3737 return false;
3738 }
3739
Marissa Wall713b63f2018-10-17 15:42:43 -07003740 for (const ComposerState& state : states) {
3741 const layer_state_t& s = state.state;
3742 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3743 continue;
3744 }
3745 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003746 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003747 }
3748 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003749 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003750}
3751
3752void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3753 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003754 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003755 const InputWindowCommands& inputWindowCommands,
3756 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003757 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003758 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759
chaviwca27f252018-02-06 16:46:39 -08003760 if (containsAnyInvalidClientState(states)) {
3761 return;
3762 }
3763
Marissa Wall713b63f2018-10-17 15:42:43 -07003764 // If its TransactionQueue already has a pending TransactionState or if it is pending
3765 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003766 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3767 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003768 setTransactionFlags(eTransactionNeeded);
3769 return;
3770 }
3771
chaviw273171b2018-12-26 11:46:30 -08003772 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003773}
3774
3775void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003776 const Vector<DisplayState>& displays, uint32_t flags,
3777 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003778 uint32_t transactionFlags = 0;
3779
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003780 if (flags & eAnimation) {
3781 // For window updates that are part of an animation we must wait for
3782 // previous animation "frames" to be handled.
3783 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003784 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003785 if (CC_UNLIKELY(err != NO_ERROR)) {
3786 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003787 // caller after a few seconds.
3788 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3789 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003790 mAnimTransactionPending = false;
3791 break;
3792 }
3793 }
3794 }
3795
chaviwca27f252018-02-06 16:46:39 -08003796 for (const DisplayState& display : displays) {
3797 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003798 }
3799
Marissa Walle2ffb422018-10-12 11:33:52 -07003800 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003801 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003802 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003803 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003804 // If the state doesn't require a traversal and there are callbacks, send them now
3805 if (!(clientStateFlags & eTraversalNeeded)) {
3806 mTransactionCompletedThread.sendCallbacks();
3807 }
3808 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003809
chaviw273171b2018-12-26 11:46:30 -08003810 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3811
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003812 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3813 // anyway. This can be used as a flush mechanism for previous async transactions.
3814 // Empty animation transaction can be used to simulate back-pressure, so also force a
3815 // transaction for empty animation transactions.
3816 if (transactionFlags == 0 &&
3817 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003818 transactionFlags = eTransactionNeeded;
3819 }
3820
Mathias Agopian386aa982011-11-07 21:58:03 -08003821 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003822 if (mInterceptor->isEnabled()) {
3823 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003824 }
Irvel468051e2016-06-13 16:44:44 -07003825
Mathias Agopian386aa982011-11-07 21:58:03 -08003826 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003827 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3828 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003829 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003830
3831 // if this is a synchronous transaction, wait for it to take effect
3832 // before returning.
3833 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003834 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003835 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003836 if (flags & eAnimation) {
3837 mAnimTransactionPending = true;
3838 }
3839 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003840 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3841 if (CC_UNLIKELY(err != NO_ERROR)) {
3842 // just in case something goes wrong in SF, return to the
3843 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003844 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3845 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003846 break;
3847 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003848 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 }
3850}
3851
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003852uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3853 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3854 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003855
Mathias Agopiane57f2922012-08-09 16:29:12 -07003856 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003857 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3858
3859 const uint32_t what = s.what;
3860 if (what & DisplayState::eSurfaceChanged) {
3861 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3862 state.surface = s.surface;
3863 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003864 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003865 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003866 if (what & DisplayState::eLayerStackChanged) {
3867 if (state.layerStack != s.layerStack) {
3868 state.layerStack = s.layerStack;
3869 flags |= eDisplayTransactionNeeded;
3870 }
3871 }
3872 if (what & DisplayState::eDisplayProjectionChanged) {
3873 if (state.orientation != s.orientation) {
3874 state.orientation = s.orientation;
3875 flags |= eDisplayTransactionNeeded;
3876 }
3877 if (state.frame != s.frame) {
3878 state.frame = s.frame;
3879 flags |= eDisplayTransactionNeeded;
3880 }
3881 if (state.viewport != s.viewport) {
3882 state.viewport = s.viewport;
3883 flags |= eDisplayTransactionNeeded;
3884 }
3885 }
3886 if (what & DisplayState::eDisplaySizeChanged) {
3887 if (state.width != s.width) {
3888 state.width = s.width;
3889 flags |= eDisplayTransactionNeeded;
3890 }
3891 if (state.height != s.height) {
3892 state.height = s.height;
3893 flags |= eDisplayTransactionNeeded;
3894 }
3895 }
3896
Mathias Agopiane57f2922012-08-09 16:29:12 -07003897 return flags;
3898}
3899
Robert Carrd4ae7f32018-06-07 16:10:57 -07003900bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3901 IPCThreadState* ipc = IPCThreadState::self();
3902 const int pid = ipc->getCallingPid();
3903 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003904 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003905 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003906 return false;
3907 }
3908 return true;
3909}
3910
chaviwca27f252018-02-06 16:46:39 -08003911uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3912 const layer_state_t& s = composerState.state;
3913 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3914
Mathias Agopian13127d82013-03-05 17:47:11 -08003915 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003916 if (layer == nullptr) {
3917 return 0;
3918 }
3919
chaviw8b3871a2017-11-01 17:41:01 -07003920 uint32_t flags = 0;
3921
Garfield Tan8a3083e2018-12-03 13:21:07 -08003922 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003923 bool geometryAppliesWithResize =
3924 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003925
3926 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3927 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003928 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003929 layer->pushPendingState();
3930 }
3931
chaviw8b3871a2017-11-01 17:41:01 -07003932 if (what & layer_state_t::ePositionChanged) {
3933 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3934 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003935 }
chaviw8b3871a2017-11-01 17:41:01 -07003936 }
3937 if (what & layer_state_t::eLayerChanged) {
3938 // NOTE: index needs to be calculated before we update the state
3939 const auto& p = layer->getParent();
3940 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003941 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003942 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003943 mCurrentState.layersSortedByZ.removeAt(idx);
3944 mCurrentState.layersSortedByZ.add(layer);
3945 // we need traversal (state changed)
3946 // AND transaction (list changed)
3947 flags |= eTransactionNeeded|eTraversalNeeded;
3948 }
chaviw8b3871a2017-11-01 17:41:01 -07003949 } else {
3950 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003951 flags |= eTransactionNeeded|eTraversalNeeded;
3952 }
3953 }
chaviw8b3871a2017-11-01 17:41:01 -07003954 }
3955 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003956 // NOTE: index needs to be calculated before we update the state
3957 const auto& p = layer->getParent();
3958 if (p == nullptr) {
3959 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3960 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3961 mCurrentState.layersSortedByZ.removeAt(idx);
3962 mCurrentState.layersSortedByZ.add(layer);
3963 // we need traversal (state changed)
3964 // AND transaction (list changed)
3965 flags |= eTransactionNeeded|eTraversalNeeded;
3966 }
3967 } else {
3968 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3969 flags |= eTransactionNeeded|eTraversalNeeded;
3970 }
chaviw8b3871a2017-11-01 17:41:01 -07003971 }
3972 }
3973 if (what & layer_state_t::eSizeChanged) {
3974 if (layer->setSize(s.w, s.h)) {
3975 flags |= eTraversalNeeded;
3976 }
3977 }
3978 if (what & layer_state_t::eAlphaChanged) {
3979 if (layer->setAlpha(s.alpha))
3980 flags |= eTraversalNeeded;
3981 }
3982 if (what & layer_state_t::eColorChanged) {
3983 if (layer->setColor(s.color))
3984 flags |= eTraversalNeeded;
3985 }
Peiyong Lind3788632018-09-18 16:01:31 -07003986 if (what & layer_state_t::eColorTransformChanged) {
3987 if (layer->setColorTransform(s.colorTransform)) {
3988 flags |= eTraversalNeeded;
3989 }
3990 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003991 if (what & layer_state_t::eBackgroundColorChanged) {
3992 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3993 flags |= eTraversalNeeded;
3994 }
3995 }
chaviw8b3871a2017-11-01 17:41:01 -07003996 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003997 // TODO: b/109894387
3998 //
3999 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4000 // rotation. To see the problem observe that if we have a square parent, and a child
4001 // of the same size, then we rotate the child 45 degrees around it's center, the child
4002 // must now be cropped to a non rectangular 8 sided region.
4003 //
4004 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4005 // private API, and the WindowManager only uses rotation in one case, which is on a top
4006 // level layer in which cropping is not an issue.
4007 //
4008 // However given that abuse of rotation matrices could lead to surfaces extending outside
4009 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4010 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4011 // transformations.
4012 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07004013 flags |= eTraversalNeeded;
4014 }
4015 if (what & layer_state_t::eTransparentRegionChanged) {
4016 if (layer->setTransparentRegionHint(s.transparentRegion))
4017 flags |= eTraversalNeeded;
4018 }
4019 if (what & layer_state_t::eFlagsChanged) {
4020 if (layer->setFlags(s.flags, s.mask))
4021 flags |= eTraversalNeeded;
4022 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004023 if (what & layer_state_t::eCropChanged_legacy) {
4024 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004025 flags |= eTraversalNeeded;
4026 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004027 if (what & layer_state_t::eCornerRadiusChanged) {
4028 if (layer->setCornerRadius(s.cornerRadius))
4029 flags |= eTraversalNeeded;
4030 }
chaviw8b3871a2017-11-01 17:41:01 -07004031 if (what & layer_state_t::eLayerStackChanged) {
4032 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4033 // We only allow setting layer stacks for top level layers,
4034 // everything else inherits layer stack from its parent.
4035 if (layer->hasParent()) {
4036 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4037 layer->getName().string());
4038 } else if (idx < 0) {
4039 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4040 "that also does not appear in the top level layer list. Something"
4041 " has gone wrong.", layer->getName().string());
4042 } else if (layer->setLayerStack(s.layerStack)) {
4043 mCurrentState.layersSortedByZ.removeAt(idx);
4044 mCurrentState.layersSortedByZ.add(layer);
4045 // we need traversal (state changed)
4046 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004047 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004048 }
4049 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004050 if (what & layer_state_t::eDeferTransaction_legacy) {
4051 if (s.barrierHandle_legacy != nullptr) {
4052 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4053 } else if (s.barrierGbp_legacy != nullptr) {
4054 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004055 if (authenticateSurfaceTextureLocked(gbp)) {
4056 const auto& otherLayer =
4057 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004058 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004059 } else {
4060 ALOGE("Attempt to defer transaction to to an"
4061 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004062 }
4063 }
chaviw8b3871a2017-11-01 17:41:01 -07004064 // We don't trigger a traversal here because if no other state is
4065 // changed, we don't want this to cause any more work
4066 }
4067 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004068 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004069 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004070 if (!hadParent) {
4071 mCurrentState.layersSortedByZ.remove(layer);
4072 }
chaviw8b3871a2017-11-01 17:41:01 -07004073 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004074 }
chaviw8b3871a2017-11-01 17:41:01 -07004075 }
4076 if (what & layer_state_t::eReparentChildren) {
4077 if (layer->reparentChildren(s.reparentHandle)) {
4078 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004079 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004080 }
chaviw8b3871a2017-11-01 17:41:01 -07004081 if (what & layer_state_t::eDetachChildren) {
4082 layer->detachChildren();
4083 }
4084 if (what & layer_state_t::eOverrideScalingModeChanged) {
4085 layer->setOverrideScalingMode(s.overrideScalingMode);
4086 // We don't trigger a traversal here because if no other state is
4087 // changed, we don't want this to cause any more work
4088 }
Marissa Wall61c58622018-07-18 10:12:20 -07004089 if (what & layer_state_t::eTransformChanged) {
4090 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4091 }
4092 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4093 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4094 flags |= eTraversalNeeded;
4095 }
4096 if (what & layer_state_t::eCropChanged) {
4097 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4098 }
Marissa Wall861616d2018-10-22 12:52:23 -07004099 if (what & layer_state_t::eFrameChanged) {
4100 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4101 }
Marissa Wall61c58622018-07-18 10:12:20 -07004102 if (what & layer_state_t::eAcquireFenceChanged) {
4103 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4104 }
4105 if (what & layer_state_t::eDataspaceChanged) {
4106 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4107 }
4108 if (what & layer_state_t::eHdrMetadataChanged) {
4109 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4110 }
4111 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4112 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4113 }
4114 if (what & layer_state_t::eApiChanged) {
4115 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4116 }
4117 if (what & layer_state_t::eSidebandStreamChanged) {
4118 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4119 }
Robert Carr720e5062018-07-30 17:45:14 -07004120 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004121 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4122 layer->setInputInfo(s.inputInfo);
4123 flags |= eTraversalNeeded;
4124 } else {
4125 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4126 }
Robert Carr720e5062018-07-30 17:45:14 -07004127 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004128 if (what & layer_state_t::eMetadataChanged) {
4129 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4130 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004131 std::vector<sp<CallbackHandle>> callbackHandles;
4132 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4133 mTransactionCompletedThread.run();
4134 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4135 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4136 }
4137 }
Marissa Wall73411622019-01-25 10:45:41 -08004138
4139 if (what & layer_state_t::eBufferChanged) {
4140 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4141 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4142 s.buffer);
4143 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004144 if (what & layer_state_t::eCachedBufferChanged) {
4145 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004146 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4147 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004148 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4149 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004150 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4151 // Do not put anything that updates layer state or modifies flags after
4152 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004153 return flags;
4154}
4155
chaviw273171b2018-12-26 11:46:30 -08004156uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4157 uint32_t flags = 0;
4158 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4159 flags |= eTraversalNeeded;
4160 }
4161
4162 mInputWindowCommands.merge(inputWindowCommands);
4163 return flags;
4164}
4165
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004166status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4167 uint32_t h, PixelFormat format, uint32_t flags,
4168 LayerMetadata metadata, sp<IBinder>* handle,
4169 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004170 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004171 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004172 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004173 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004174 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004175
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004176 status_t result = NO_ERROR;
4177
4178 sp<Layer> layer;
4179
Cody Northropbc755282017-03-31 12:00:08 -06004180 String8 uniqueName = getUniqueLayerName(name);
4181
Mathias Agopian3165cc22012-08-08 19:42:09 -07004182 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004183 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004184 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4185 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004186
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004188 case ISurfaceComposerClient::eFXSurfaceBufferState:
4189 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4190 break;
chaviw13fdc492017-06-27 12:40:18 -07004191 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004192 // check if buffer size is set for color layer.
4193 if (w > 0 || h > 0) {
4194 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4195 int(w), int(h));
4196 return BAD_VALUE;
4197 }
4198
chaviw13fdc492017-06-27 12:40:18 -07004199 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004200 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004201 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004202 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004203 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004204 // check if buffer size is set for container layer.
4205 if (w > 0 || h > 0) {
4206 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4207 int(w), int(h));
4208 return BAD_VALUE;
4209 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004210 result = createContainerLayer(client,
4211 uniqueName, w, h, flags,
4212 handle, &layer);
4213 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004214 default:
4215 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004216 break;
4217 }
4218
Dan Stoza7d89d062015-04-30 13:29:25 -07004219 if (result != NO_ERROR) {
4220 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004221 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004222
Chia-I Wuab0c3192017-08-01 11:29:00 -07004223 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4224 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004225 if (metadata.has(METADATA_WINDOW_TYPE)) {
4226 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4227 if (windowType == 441731) {
4228 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4229 layer->setPrimaryDisplayOnly();
4230 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004231 }
4232
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004233 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004234
Robert Carrb89ea9d2018-12-10 13:01:14 -08004235 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4236 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4237 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004238 if (result != NO_ERROR) {
4239 return result;
4240 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004241 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004242
4243 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004244 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004245}
4246
Cody Northropbc755282017-03-31 12:00:08 -06004247String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4248{
4249 bool matchFound = true;
4250 uint32_t dupeCounter = 0;
4251
4252 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4253 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4254
Dan Stoza436ccf32018-06-21 12:10:12 -07004255 // Grab the state lock since we're accessing mCurrentState
4256 Mutex::Autolock lock(mStateLock);
4257
Cody Northropbc755282017-03-31 12:00:08 -06004258 // Loop over layers until we're sure there is no matching name
4259 while (matchFound) {
4260 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004261 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004262 if (layer->getName() == uniqueName) {
4263 matchFound = true;
4264 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4265 }
4266 });
4267 }
4268
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004269 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4270 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004271
4272 return uniqueName;
4273}
4274
Marissa Wallfd668622018-05-10 10:21:13 -07004275status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4276 uint32_t w, uint32_t h, uint32_t flags,
4277 PixelFormat& format, sp<IBinder>* handle,
4278 sp<IGraphicBufferProducer>* gbp,
4279 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004281 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004282 case PIXEL_FORMAT_TRANSPARENT:
4283 case PIXEL_FORMAT_TRANSLUCENT:
4284 format = PIXEL_FORMAT_RGBA_8888;
4285 break;
4286 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004287 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288 break;
4289 }
4290
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004291 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004292 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004293 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004294 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004295 *handle = layer->getHandle();
4296 *gbp = layer->getProducer();
4297 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004299
Marissa Wallfd668622018-05-10 10:21:13 -07004300 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004301 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302}
4303
Marissa Wall61c58622018-07-18 10:12:20 -07004304status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4305 uint32_t w, uint32_t h, uint32_t flags,
4306 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004307 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004308 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004309 *handle = layer->getHandle();
4310 *outLayer = layer;
4311
4312 return NO_ERROR;
4313}
4314
chaviw13fdc492017-06-27 12:40:18 -07004315status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004316 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004317 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004318{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004319 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004320 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004321 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004322}
4323
Robert Carr6b3f6c52018-08-13 13:05:17 -07004324status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4325 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4326 sp<IBinder>* handle, sp<Layer>* outLayer)
4327{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004328 *outLayer =
4329 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004330 *handle = (*outLayer)->getHandle();
4331 return NO_ERROR;
4332}
4333
4334
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004335void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004336 mLayersPendingRemoval.add(layer);
4337 mLayersRemoved = true;
4338 setTransactionFlags(eTransactionNeeded);
4339}
4340
Robert Carr695d5282018-12-18 15:27:58 -08004341void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004342{
Robert Carr2e102c92018-10-23 12:11:15 -07004343 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004344 // If a layer has a parent, we allow it to out-live it's handle
4345 // with the idea that the parent holds a reference and will eventually
4346 // be cleaned up. However no one cleans up the top-level so we do so
4347 // here.
4348 if (layer->getParent() == nullptr) {
4349 mCurrentState.layersSortedByZ.remove(layer);
4350 }
4351 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004352 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004353}
4354
Mathias Agopianb60314a2012-04-10 22:09:54 -07004355// ---------------------------------------------------------------------------
4356
Andy McFadden13a082e2012-08-24 10:16:42 -07004357void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004358 const auto display = getDefaultDisplayDeviceLocked();
4359 if (!display) return;
4360
4361 const sp<IBinder> token = display->getDisplayToken().promote();
4362 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004363
Jesse Hall01e29052013-02-19 16:13:35 -08004364 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004365 Vector<ComposerState> state;
4366 Vector<DisplayState> displays;
4367 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004368 d.what = DisplayState::eDisplayProjectionChanged |
4369 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004370 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004371 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004372 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004373 d.frame.makeInvalid();
4374 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004375 d.width = 0;
4376 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004377 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004378 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004379
Dominik Laskowskie9774092018-12-11 10:04:24 -08004380 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004381
Dominik Laskowski83b88212018-12-11 13:34:06 -08004382 const nsecs_t vsyncPeriod = getVsyncPeriod();
4383 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004384
Brian Andersond0010582017-03-07 13:20:31 -08004385 // Use phase of 0 since phase is not known.
4386 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004387 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004388 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004389}
4390
4391void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004392 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004393 postMessageAsync(
4394 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004395}
4396
Dominik Laskowskie9774092018-12-11 10:04:24 -08004397void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004398 if (display->isVirtual()) {
4399 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004400 return;
4401 }
4402
Dominik Laskowski075d3172018-05-24 15:50:06 -07004403 const auto displayId = display->getId();
4404 LOG_ALWAYS_FATAL_IF(!displayId);
4405
Dominik Laskowski34157762018-10-31 13:07:19 -07004406 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004407
4408 int currentMode = display->getPowerMode();
4409 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004410 return;
4411 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004412
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004413 display->setPowerMode(mode);
4414
Lloyd Pique4dccc412018-01-22 17:21:36 -08004415 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004416 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004417 }
4418
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004419 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004420 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004421 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004422 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004423 if (mUseScheduler) {
4424 mScheduler->onScreenAcquired(mAppConnectionHandle);
4425 } else {
4426 mEventThread->onScreenAcquired();
4427 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004428 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004430
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004431 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004432 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004433 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004434
4435 struct sched_param param = {0};
4436 param.sched_priority = 1;
4437 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4438 ALOGW("Couldn't set SCHED_FIFO on display on");
4439 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004440 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004441 // Turn off the display
4442 struct sched_param param = {0};
4443 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4444 ALOGW("Couldn't set SCHED_OTHER on display off");
4445 }
4446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004447 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004448 if (mUseScheduler) {
4449 mScheduler->disableHardwareVsync(true);
4450 } else {
4451 disableHardwareVsync(true); // also cancels any in-progress resync
4452 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004453 if (mUseScheduler) {
4454 mScheduler->onScreenReleased(mAppConnectionHandle);
4455 } else {
4456 mEventThread->onScreenReleased();
4457 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004458 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004459
Dominik Laskowski075d3172018-05-24 15:50:06 -07004460 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004461 mVisibleRegionsDirty = true;
4462 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004463 } else if (mode == HWC_POWER_MODE_DOZE ||
4464 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004465 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004466 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004467 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004468 if (mUseScheduler) {
4469 mScheduler->onScreenAcquired(mAppConnectionHandle);
4470 } else {
4471 mEventThread->onScreenAcquired();
4472 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004473 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004474 }
4475 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4476 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004477 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004478 if (mUseScheduler) {
4479 mScheduler->disableHardwareVsync(true);
4480 } else {
4481 disableHardwareVsync(true); // also cancels any in-progress resync
4482 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004483 if (mUseScheduler) {
4484 mScheduler->onScreenReleased(mAppConnectionHandle);
4485 } else {
4486 mEventThread->onScreenReleased();
4487 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004488 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004489 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004490 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004491 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004492 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004493 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004494
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004495 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004496 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004497 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004498 // Update refresh rate stats.
4499 mRefreshRateStats->setPowerMode(mode);
4500 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004501 }
4502
Dominik Laskowski34157762018-10-31 13:07:19 -07004503 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004504}
4505
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004506void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004507 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004508 const auto display = getDisplayDevice(displayToken);
4509 if (!display) {
4510 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4511 displayToken.get());
4512 } else if (display->isVirtual()) {
4513 ALOGW("Attempt to set power mode %d for virtual display", mode);
4514 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004515 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004516 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004517 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004518}
4519
4520// ---------------------------------------------------------------------------
4521
Dominik Laskowskic2867142019-01-21 11:33:38 -08004522status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4523 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004525
Mathias Agopianbd115332013-04-18 16:41:04 -07004526 IPCThreadState* ipc = IPCThreadState::self();
4527 const int pid = ipc->getCallingPid();
4528 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004529
Mathias Agopianbd115332013-04-18 16:41:04 -07004530 if ((uid != AID_SHELL) &&
4531 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004532 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4533 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004535 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004536 // (this would indicate SF is stuck, but we want to be able to
4537 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004538 status_t err = mStateLock.timedLock(s2ns(1));
4539 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004540 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result,
4542 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4543 "(no locks held)\n",
4544 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004545 }
4546
Dominik Laskowskic2867142019-01-21 11:33:38 -08004547 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004548
Dominik Laskowskic2867142019-01-21 11:33:38 -08004549 static const std::unordered_map<std::string, Dumper> dumpers = {
4550 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4551 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4552 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004553 {"--dispsync"s, dumper([this](std::string& s) {
4554 if (mUseScheduler) {
4555 mScheduler->dumpPrimaryDispSync(s);
4556 } else {
4557 mPrimaryDispSync->dump(s);
4558 }
4559 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004560 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4561 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004562 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4563 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4564 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4565 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4566 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4567 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004568 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004569 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4570 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004571
Dominik Laskowskic2867142019-01-21 11:33:38 -08004572 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004573
Dominik Laskowskic2867142019-01-21 11:33:38 -08004574 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4575 (it->second)(args, asProto, result);
4576 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004577 if (asProto) {
4578 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4579 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4580 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004581 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004582 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004583 }
4584
Mathias Agopian9795c422009-08-26 16:36:26 -07004585 if (locked) {
4586 mStateLock.unlock();
4587 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004588 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004589 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 return NO_ERROR;
4591}
4592
Dominik Laskowskic2867142019-01-21 11:33:38 -08004593void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 mCurrentState.traverseInZOrder(
4595 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004596}
4597
Dominik Laskowskic2867142019-01-21 11:33:38 -08004598void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004599 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004600
Dominik Laskowskic2867142019-01-21 11:33:38 -08004601 if (args.size() > 1) {
4602 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004603 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004604 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004605 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004606 }
Robert Carr2047fae2016-11-28 14:09:09 -08004607 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004608 } else {
4609 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610 }
4611}
4612
Dominik Laskowskic2867142019-01-21 11:33:38 -08004613void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004614 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004615 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004616 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004617 }
Robert Carr2047fae2016-11-28 14:09:09 -08004618 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004619
Svetoslavd85084b2014-03-20 10:28:31 -07004620 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004621}
4622
Dominik Laskowskic2867142019-01-21 11:33:38 -08004623void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4624 mTimeStats->parseArgs(asProto, args, result);
4625}
4626
Jamie Gennis6547ff42013-07-16 20:12:42 -07004627// This should only be called from the main thread. Otherwise it would need
4628// the lock and should use mCurrentState rather than mDrawingState.
4629void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004630 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004631 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004632 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004633
4634 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4635}
4636
Yiwei Zhang5434a782018-12-05 18:06:32 -08004637void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004638 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004639
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004640 if (isLayerTripleBufferingDisabled())
4641 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004642
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4644 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4645 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4646 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4647 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4648 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004649 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004650}
4651
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004652void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004653 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004654 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004655 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004656 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004657
4658 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4659
4660 if (mUseScheduler) {
4661 mScheduler->dump(mAppConnectionHandle, result);
4662 } else {
4663 mEventThread->dump(result);
4664 }
4665}
4666
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4668 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004669 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4670 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004671 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004672 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004674 }
David Sodman4a36e932017-11-07 14:29:47 -08004675 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004676 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004677 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4679 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004680}
4681
Dan Stozae77c7662016-05-13 11:37:28 -07004682void SurfaceFlinger::recordBufferingStats(const char* layerName,
4683 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004684 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4685 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004686 for (const auto& segment : history) {
4687 if (!segment.usedThirdBuffer) {
4688 stats.twoBufferTime += segment.totalTime;
4689 }
4690 if (segment.occupancyAverage < 1.0f) {
4691 stats.doubleBufferedTime += segment.totalTime;
4692 } else if (segment.occupancyAverage < 2.0f) {
4693 stats.tripleBufferedTime += segment.totalTime;
4694 }
4695 ++stats.numSegments;
4696 stats.totalTime += segment.totalTime;
4697 }
4698}
4699
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4701 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004702
4703 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4704 const size_t count = currentLayers.size();
4705 for (size_t i=0 ; i<count ; i++) {
4706 currentLayers[i]->dumpFrameEvents(result);
4707 }
4708}
4709
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004711 result.append("Buffering stats:\n");
4712 result.append(" [Layer name] <Active time> <Two buffer> "
4713 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004714 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004715 typedef std::tuple<std::string, float, float, float> BufferTuple;
4716 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004717 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004718 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004719 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004720 if (stats.numSegments == 0) {
4721 continue;
4722 }
4723 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4724 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4725 stats.totalTime;
4726 float doubleBufferRatio = static_cast<float>(
4727 stats.doubleBufferedTime) / stats.totalTime;
4728 float tripleBufferRatio = static_cast<float>(
4729 stats.tripleBufferedTime) / stats.totalTime;
4730 sorted.insert({activeTime, {name, twoBufferRatio,
4731 doubleBufferRatio, tripleBufferRatio}});
4732 }
4733 for (const auto& sortedPair : sorted) {
4734 float activeTime = sortedPair.first;
4735 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4737 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004738 }
4739 result.append("\n");
4740}
4741
Yiwei Zhang5434a782018-12-05 18:06:32 -08004742void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004743 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004744 const auto displayId = display->getId();
4745 if (!displayId) {
4746 continue;
4747 }
4748 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004749 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004750 continue;
4751 }
4752
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 StringAppendF(&result,
4754 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4755 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004756 uint8_t port;
4757 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004758 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004759 result.append("no identification data\n");
4760 continue;
4761 }
4762
4763 if (!isEdid(data)) {
4764 result.append("unknown identification data: ");
4765 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004766 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004767 }
4768 result.append("\n");
4769 continue;
4770 }
4771
4772 const auto edid = parseEdid(data);
4773 if (!edid) {
4774 result.append("invalid EDID: ");
4775 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004777 }
4778 result.append("\n");
4779 continue;
4780 }
4781
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004783 result.append(edid->displayName.data(), edid->displayName.length());
4784 result.append("\"\n");
4785 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004786}
4787
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4789 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4790 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4791 StringAppendF(&result, "DisplayColorSetting: %s\n",
4792 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004793
4794 // TODO: print out if wide-color mode is active or not
4795
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004796 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004797 const auto displayId = display->getId();
4798 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004799 continue;
4800 }
4801
Yiwei Zhang5434a782018-12-05 18:06:32 -08004802 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004803 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004804 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004806 }
4807
Lloyd Pique32cbe282018-10-19 13:09:22 -07004808 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result, " Current color mode: %s (%d)\n",
4810 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004811 }
4812 result.append("\n");
4813}
4814
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004815LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004816 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004817 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4818 const State& state = useDrawing ? mDrawingState : mCurrentState;
4819 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004820 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004821 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004822 });
4823
4824 return layersProto;
4825}
4826
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004827LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4828 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004829 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004830
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004831 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004832 resolution->set_w(displayDevice->getWidth());
4833 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004834
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004835 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004836 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004837
Lloyd Pique32cbe282018-10-19 13:09:22 -07004838 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4839 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4840 layersProto.set_global_transform(displayState.orientation);
4841
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004842 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004843 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004844 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004845 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004846 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004847 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004848 }
4849 });
4850
4851 return layersProto;
4852}
4853
Dominik Laskowskic2867142019-01-21 11:33:38 -08004854void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4855 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004856 Colorizer colorizer(colorize);
4857
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004858 // figure out if we're stuck somewhere
4859 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004860 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4862
4863 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004864 * Dump library configuration.
4865 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004866
4867 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004868 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004869 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004870 appendSfConfigString(result);
4871 appendUiConfigString(result);
4872 appendGuiConfigString(result);
4873 result.append("\n");
4874
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004875 result.append("\nDisplay identification data:\n");
4876 dumpDisplayIdentificationData(result);
4877
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004878 result.append("\nWide-Color information:\n");
4879 dumpWideColorInfo(result);
4880
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004881 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004882 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004883 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004884 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004885 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004886
Andy McFadden41d67d72014-04-25 16:58:34 -07004887 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004888 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004889 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004890 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004891 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004892
Dan Stozab90cf072015-03-05 11:05:59 -08004893 dumpStaticScreenStats(result);
4894 result.append("\n");
4895
Yiwei Zhang5434a782018-12-05 18:06:32 -08004896 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004897
Dan Stozae77c7662016-05-13 11:37:28 -07004898 dumpBufferingStats(result);
4899
Andy McFadden4803b742012-09-24 19:07:20 -07004900 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004901 * Dump the visible layer list
4902 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004903 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004904 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4905 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4906 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004907 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004908
Chia-I Wu2f884132018-09-13 15:17:58 -07004909 {
4910 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4911 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004912 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004913 result.append("\n");
4914 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004915
4916 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004917 * Dump Display state
4918 */
4919
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004920 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004921 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004922 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004923 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004924 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004925 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004926 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004927
4928 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004929 * Dump SurfaceFlinger global state
4930 */
4931
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004932 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004933 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004934 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004935
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004936 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004937
Dominik Laskowski075d3172018-05-24 15:50:06 -07004938 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004939 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4940 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004941 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4942 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004943 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004944 StringAppendF(&result,
4945 " transaction-flags : %08x\n"
4946 " gpu_to_cpu_unsupported : %d\n",
4947 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004948
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004949 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004950 displayId && getHwComposer().isConnected(*displayId)) {
4951 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004952 StringAppendF(&result,
4953 " refresh-rate : %f fps\n"
4954 " x-dpi : %f\n"
4955 " y-dpi : %f\n",
4956 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4957 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004958 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004959
Yiwei Zhang5434a782018-12-05 18:06:32 -08004960 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004961
Dan Stozae22aec72016-08-01 13:20:59 -07004962 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004963 * Tracing state
4964 */
4965 mTracing.dump(result);
4966 result.append("\n");
4967
4968 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004969 * HWC layer minidump
4970 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004971 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004972 const auto displayId = display->getId();
4973 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004974 continue;
4975 }
4976
Yiwei Zhang5434a782018-12-05 18:06:32 -08004977 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004978 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004979 const sp<DisplayDevice> displayDevice = display;
4980 mCurrentState.traverseInZOrder(
4981 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004982 result.append("\n");
4983 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004984
4985 /*
4986 * Dump HWComposer state
4987 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004988 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004989 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004990 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004991 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004992 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004993 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004994
4995 /*
4996 * Dump gralloc state
4997 */
4998 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4999 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005000
5001 /*
5002 * Dump VrFlinger state if in use.
5003 */
5004 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5005 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005006 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005007 result.append("\n");
5008 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005009
5010 /**
5011 * Scheduler dump state.
5012 */
5013 if (mUseScheduler) {
5014 result.append("\nScheduler state:\n");
5015 result.append(mScheduler->doDump() + "\n");
5016 result.append(mRefreshRateStats->doDump() + "\n");
5017 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005018}
5019
Dominik Laskowski075d3172018-05-24 15:50:06 -07005020const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005021 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005022 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005023 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005024 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005025 }
5026 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005027
Dominik Laskowski34157762018-10-31 13:07:19 -07005028 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005029 static const Vector<sp<Layer>> empty;
5030 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005031}
5032
Chia-I Wu28f320b2018-05-03 11:02:56 -07005033void SurfaceFlinger::updateColorMatrixLocked() {
5034 mat4 colorMatrix;
5035 if (mGlobalSaturationFactor != 1.0f) {
5036 // Rec.709 luma coefficients
5037 float3 luminance{0.213f, 0.715f, 0.072f};
5038 luminance *= 1.0f - mGlobalSaturationFactor;
5039 mat4 saturationMatrix = mat4(
5040 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5041 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5042 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5043 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5044 );
5045 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5046 } else {
5047 colorMatrix = mClientColorMatrix * mDaltonizer();
5048 }
5049
5050 if (mCurrentState.colorMatrix != colorMatrix) {
5051 mCurrentState.colorMatrix = colorMatrix;
5052 mCurrentState.colorMatrixChanged = true;
5053 setTransactionFlags(eTransactionNeeded);
5054 }
5055}
5056
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005057status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005058#pragma clang diagnostic push
5059#pragma clang diagnostic error "-Wswitch-enum"
5060 switch (static_cast<ISurfaceComposerTag>(code)) {
5061 // These methods should at minimum make sure that the client requested
5062 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005063 case BOOT_FINISHED:
5064 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005065 case CREATE_DISPLAY:
5066 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005067 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005068 case GET_ACTIVE_COLOR_MODE:
5069 case GET_ANIMATION_FRAME_STATS:
5070 case GET_HDR_CAPABILITIES:
5071 case SET_ACTIVE_CONFIG:
5072 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005073 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005074 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005075 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005076 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5077 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005078 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5079 IPCThreadState* ipc = IPCThreadState::self();
5080 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5081 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005082 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005083 }
Robert Carr1db73f62016-12-21 12:58:51 -08005084 return OK;
5085 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005086 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005087 IPCThreadState* ipc = IPCThreadState::self();
5088 const int pid = ipc->getCallingPid();
5089 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005090 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5091 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005092 return PERMISSION_DENIED;
5093 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005094 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005096 // Used by apps to hook Choreographer to SurfaceFlinger.
5097 case CREATE_DISPLAY_EVENT_CONNECTION:
5098 // The following calls are currently used by clients that do not
5099 // request necessary permissions. However, they do not expose any secret
5100 // information, so it is OK to pass them.
5101 case AUTHENTICATE_SURFACE:
5102 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005103 case GET_PHYSICAL_DISPLAY_IDS:
5104 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005105 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005106 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005107 case GET_DISPLAY_CONFIGS:
5108 case GET_DISPLAY_STATS:
5109 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5110 // Calling setTransactionState is safe, because you need to have been
5111 // granted a reference to Client* and Handle* to do anything with it.
5112 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005113 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005114 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005115 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005116 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005117 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005118 return OK;
5119 }
5120 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005121 case CAPTURE_SCREEN:
5122 case ADD_REGION_SAMPLING_LISTENER:
5123 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005124 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005125 IPCThreadState* ipc = IPCThreadState::self();
5126 const int pid = ipc->getCallingPid();
5127 const int uid = ipc->getCallingUid();
5128 if ((uid != AID_GRAPHICS) &&
5129 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5130 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5131 return PERMISSION_DENIED;
5132 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005133 return OK;
5134 }
5135 // The following codes are deprecated and should never be allowed to access SF.
5136 case CONNECT_DISPLAY_UNUSED:
5137 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5138 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5139 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005140 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005141 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005142
5143 // These codes are used for the IBinder protocol to either interrogate the recipient
5144 // side of the transaction for its canonical interface descriptor or to dump its state.
5145 // We let them pass by default.
5146 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5147 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5148 code == IBinder::SYSPROPS_TRANSACTION) {
5149 return OK;
5150 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005151 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005152 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005153 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005154 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5155 return OK;
5156 }
5157 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5158 return PERMISSION_DENIED;
5159#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005160}
5161
Ana Krulec13be8ad2018-08-21 02:43:56 +00005162status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5163 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005164 status_t credentialCheck = CheckTransactCodeCredentials(code);
5165 if (credentialCheck != OK) {
5166 return credentialCheck;
5167 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005169 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5170 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005171 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005172 IPCThreadState* ipc = IPCThreadState::self();
5173 const int uid = ipc->getCallingUid();
5174 if (CC_UNLIKELY(uid != AID_SYSTEM
5175 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005176 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005177 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005178 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005179 return PERMISSION_DENIED;
5180 }
5181 int n;
5182 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005183 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005184 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005185 return NO_ERROR;
5186 case 1002: // SHOW_UPDATES
5187 n = data.readInt32();
5188 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005189 invalidateHwcGeometry();
5190 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005191 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005192 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005193 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005194 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005195 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005196 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005197 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005198 setTransactionFlags(
5199 eTransactionNeeded|
5200 eDisplayTransactionNeeded|
5201 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005202 return NO_ERROR;
5203 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005204 case 1006:{ // send empty update
5205 signalRefresh();
5206 return NO_ERROR;
5207 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005208 case 1008: // toggle use of hw composer
5209 n = data.readInt32();
5210 mDebugDisableHWC = n ? 1 : 0;
5211 invalidateHwcGeometry();
5212 repaintEverything();
5213 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005214 case 1009: // toggle use of transform hint
5215 n = data.readInt32();
5216 mDebugDisableTransformHint = n ? 1 : 0;
5217 invalidateHwcGeometry();
5218 repaintEverything();
5219 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005220 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005221 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005222 reply->writeInt32(0);
5223 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005224 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005225 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005226 return NO_ERROR;
5227 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005228 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005229 if (!display) {
5230 return NAME_NOT_FOUND;
5231 }
5232
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005233 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005234 return NO_ERROR;
5235 }
5236 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005237 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005238 // daltonize
5239 n = data.readInt32();
5240 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005241 case 1:
5242 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5243 break;
5244 case 2:
5245 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5246 break;
5247 case 3:
5248 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5249 break;
5250 default:
5251 mDaltonizer.setType(ColorBlindnessType::None);
5252 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005253 }
5254 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005255 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005256 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005257 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005258 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005259
5260 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005261 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005262 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005263 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005264 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005265 // apply a color matrix
5266 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005267 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005268 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005269 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005270 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005271 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005272 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005273 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005274 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005275 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005276 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005277
5278 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5279 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005280 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005281 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5282 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5283 }
5284
Chia-I Wu28f320b2018-05-03 11:02:56 -07005285 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005286 return NO_ERROR;
5287 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005288 // This is an experimental interface
5289 // Needs to be shifted to proper binder interface when we productize
5290 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005291 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005292 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005293 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005294 return NO_ERROR;
5295 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005296 case 1017: {
5297 n = data.readInt32();
5298 mForceFullDamage = static_cast<bool>(n);
5299 return NO_ERROR;
5300 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005301 case 1018: { // Modify Choreographer's phase offset
5302 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005303 if (mUseScheduler) {
5304 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5305 } else {
5306 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5307 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005308 return NO_ERROR;
5309 }
5310 case 1019: { // Modify SurfaceFlinger's phase offset
5311 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005312 if (mUseScheduler) {
5313 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5314 } else {
5315 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5316 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005317 return NO_ERROR;
5318 }
Irvel468051e2016-06-13 16:44:44 -07005319 case 1020: { // Layer updates interceptor
5320 n = data.readInt32();
5321 if (n) {
5322 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005323 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005324 }
5325 else{
5326 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005327 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005328 }
5329 return NO_ERROR;
5330 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005331 case 1021: { // Disable HWC virtual displays
5332 n = data.readInt32();
5333 mUseHwcVirtualDisplays = !n;
5334 return NO_ERROR;
5335 }
Romain Guy0147a172017-06-01 13:53:56 -07005336 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005337 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005338 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005339
Chia-I Wu28f320b2018-05-03 11:02:56 -07005340 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005341 return NO_ERROR;
5342 }
Romain Guy54f154a2017-10-24 21:40:32 +01005343 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005344 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005345 invalidateHwcGeometry();
5346 repaintEverything();
5347 return NO_ERROR;
5348 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005349 // Deprecate, use 1030 to check whether the device is color managed.
5350 case 1024: {
5351 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005352 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005353 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005354 n = data.readInt32();
5355 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005356 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005357 mTracing.enable();
5358 doTracing("tracing.enable");
5359 reply->writeInt32(NO_ERROR);
5360 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005361 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005362 status_t err = mTracing.disable();
5363 reply->writeInt32(err);
5364 }
5365 return NO_ERROR;
5366 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005367 case 1026: { // Get layer tracing status
5368 reply->writeBool(mTracing.isEnabled());
5369 return NO_ERROR;
5370 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005371 // Is a DisplayColorSetting supported?
5372 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005373 const auto display = getDefaultDisplayDevice();
5374 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005375 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005376 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005377
5378 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5379 switch (setting) {
5380 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005381 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005382 break;
5383 case DisplayColorSetting::UNMANAGED:
5384 reply->writeBool(true);
5385 break;
5386 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005387 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005388 break;
5389 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005390 reply->writeBool(
5391 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005392 break;
5393 }
5394 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005395 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005396 // Is VrFlinger active?
5397 case 1028: {
5398 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005399 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005400 return NO_ERROR;
5401 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005402 // Is device color managed?
5403 case 1030: {
5404 reply->writeBool(useColorManagement);
5405 return NO_ERROR;
5406 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005407 // Override default composition data space
5408 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5409 // && adb shell stop zygote && adb shell start zygote
5410 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5411 // adb shell stop zygote && adb shell start zygote
5412 case 1031: {
5413 Mutex::Autolock _l(mStateLock);
5414 n = data.readInt32();
5415 if (n) {
5416 n = data.readInt32();
5417 if (n) {
5418 Dataspace dataspace = static_cast<Dataspace>(n);
5419 if (!validateCompositionDataspace(dataspace)) {
5420 return BAD_VALUE;
5421 }
5422 mDefaultCompositionDataspace = dataspace;
5423 }
5424 n = data.readInt32();
5425 if (n) {
5426 Dataspace dataspace = static_cast<Dataspace>(n);
5427 if (!validateCompositionDataspace(dataspace)) {
5428 return BAD_VALUE;
5429 }
5430 mWideColorGamutCompositionDataspace = dataspace;
5431 }
5432 } else {
5433 // restore composition data space.
5434 mDefaultCompositionDataspace = defaultCompositionDataspace;
5435 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5436 }
5437 return NO_ERROR;
5438 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005439 }
5440 }
5441 return err;
5442}
5443
Steven Thomas6d8110b2017-08-31 18:24:21 -07005444void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005445 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005446 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005447}
5448
Ana Krulec7d1d6832018-12-27 11:10:09 -08005449void SurfaceFlinger::repaintEverythingForHWC() {
5450 mRepaintEverything = true;
5451 mEventQueue->invalidateForHWC();
5452}
5453
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005454// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5455class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005456public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005457 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5458 ~WindowDisconnector() {
5459 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005460 }
5461
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005462private:
5463 ANativeWindow* mWindow;
5464 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005465};
5466
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005467status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005468 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5469 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005470 uint32_t reqWidth, uint32_t reqHeight,
5471 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005472 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005474
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005475 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005476
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005477 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5478
Chia-I Wu20261cb2018-08-23 12:55:44 -07005479 sp<DisplayDevice> display;
5480 {
5481 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005482
Chia-I Wu20261cb2018-08-23 12:55:44 -07005483 display = getDisplayDeviceLocked(displayToken);
5484 if (!display) return BAD_VALUE;
5485
Chia-I Wucb023152018-08-28 12:57:23 -07005486 // set the requested width/height to the logical display viewport size
5487 // by default
5488 if (reqWidth == 0 || reqHeight == 0) {
5489 reqWidth = uint32_t(display->getViewport().width());
5490 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005491 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005492 }
5493
Peiyong Lin0e003c92018-09-17 11:09:51 -07005494 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5495 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005496
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005497 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5498 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005499 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5500 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005501}
5502
5503status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005504 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5505 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005506 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005507 ATRACE_CALL();
5508
5509 class LayerRenderArea : public RenderArea {
5510 public:
Robert Carr578038f2018-03-09 12:25:24 -08005511 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005512 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5513 bool childrenOnly)
5514 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005515 mLayer(layer),
5516 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005517 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005518 mFlinger(flinger),
5519 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005520 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005521 Rect getBounds() const override {
5522 const Layer::State& layerState(mLayer->getDrawingState());
5523 return mLayer->getBufferSize(layerState);
5524 }
Marissa Wall61c58622018-07-18 10:12:20 -07005525 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005526 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005527 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005528 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005529 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005530 }
chaviwa76b2712017-09-20 12:02:26 -07005531 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005532 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005533 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005534 Rect getSourceCrop() const override {
5535 if (mCrop.isEmpty()) {
5536 return getBounds();
5537 } else {
5538 return mCrop;
5539 }
5540 }
Robert Carr578038f2018-03-09 12:25:24 -08005541 class ReparentForDrawing {
5542 public:
5543 const sp<Layer>& oldParent;
5544 const sp<Layer>& newParent;
5545
Vishnu Nair4351ad52019-02-11 14:13:02 -08005546 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5547 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005548 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005549 // Compute and cache the bounds for the new parent layer.
5550 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005551 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005552 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005553 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005554 };
5555
5556 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005557 const Rect sourceCrop = getSourceCrop();
5558 // no need to check rotation because there is none
5559 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5560 sourceCrop.height() != getReqHeight();
5561
Robert Carr578038f2018-03-09 12:25:24 -08005562 if (!mChildrenOnly) {
5563 mTransform = mLayer->getTransform().inverse();
5564 drawLayers();
5565 } else {
5566 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005567 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005568 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5569 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005570
Vishnu Nair4351ad52019-02-11 14:13:02 -08005571 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005572 drawLayers();
5573 }
5574 }
chaviwa76b2712017-09-20 12:02:26 -07005575
chaviwa76b2712017-09-20 12:02:26 -07005576 private:
chaviw7206d492017-11-10 16:16:12 -08005577 const sp<Layer> mLayer;
5578 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005579
5580 // In the "childrenOnly" case we reparent the children to a screenshot
5581 // layer which has no properties set and which does not draw.
5582 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005583 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005584 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005585
5586 SurfaceFlinger* mFlinger;
5587 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005588 };
5589
5590 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5591 auto parent = layerHandle->owner.promote();
5592
Robert Carr2e102c92018-10-23 12:11:15 -07005593 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005594 ALOGE("captureLayers called with a removed parent");
5595 return NAME_NOT_FOUND;
5596 }
5597
Robert Carr578038f2018-03-09 12:25:24 -08005598 const int uid = IPCThreadState::self()->getCallingUid();
5599 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005600 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005601 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5602 return PERMISSION_DENIED;
5603 }
5604
chaviw7206d492017-11-10 16:16:12 -08005605 Rect crop(sourceCrop);
5606 if (sourceCrop.width() <= 0) {
5607 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005608 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005609 }
5610
5611 if (sourceCrop.height() <= 0) {
5612 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005613 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005614 }
5615
5616 int32_t reqWidth = crop.width() * frameScale;
5617 int32_t reqHeight = crop.height() * frameScale;
5618
Chia-I Wu20261cb2018-08-23 12:55:44 -07005619 // really small crop or frameScale
5620 if (reqWidth <= 0) {
5621 reqWidth = 1;
5622 }
5623 if (reqHeight <= 0) {
5624 reqHeight = 1;
5625 }
5626
Peiyong Lin0e003c92018-09-17 11:09:51 -07005627 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005628
Robert Carr578038f2018-03-09 12:25:24 -08005629 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005630 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5631 if (!layer->isVisible()) {
5632 return;
Robert Carr578038f2018-03-09 12:25:24 -08005633 } else if (childrenOnly && layer == parent.get()) {
5634 return;
chaviwa76b2712017-09-20 12:02:26 -07005635 }
5636 visitor(layer);
5637 });
5638 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005639 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005640}
5641
5642status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5643 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005644 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005645 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005646 bool useIdentityTransform) {
5647 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005648
Peiyong Lin0e003c92018-09-17 11:09:51 -07005649 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005650 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5651 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005652 *outBuffer =
5653 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5654 static_cast<android_pixel_format>(reqPixelFormat), 1,
5655 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656
5657 // This mutex protects syncFd and captureResult for communication of the return values from the
5658 // main thread back to this Binder thread
5659 std::mutex captureMutex;
5660 std::condition_variable captureCondition;
5661 std::unique_lock<std::mutex> captureLock(captureMutex);
5662 int syncFd = -1;
5663 std::optional<status_t> captureResult;
5664
Robert Carr03480e22018-01-04 16:02:06 -08005665 const int uid = IPCThreadState::self()->getCallingUid();
5666 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5667
Dominik Laskowski8c001672018-05-30 16:52:06 -07005668 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005669 // If there is a refresh pending, bug out early and tell the binder thread to try again
5670 // after the refresh.
5671 if (mRefreshPending) {
5672 ATRACE_NAME("Skipping screenshot for now");
5673 std::unique_lock<std::mutex> captureLock(captureMutex);
5674 captureResult = std::make_optional<status_t>(EAGAIN);
5675 captureCondition.notify_one();
5676 return;
5677 }
5678
5679 status_t result = NO_ERROR;
5680 int fd = -1;
5681 {
5682 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005683 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005684 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5685 useIdentityTransform, forSystem, &fd);
5686 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005687 }
5688
5689 {
5690 std::unique_lock<std::mutex> captureLock(captureMutex);
5691 syncFd = fd;
5692 captureResult = std::make_optional<status_t>(result);
5693 captureCondition.notify_one();
5694 }
5695 });
5696
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005697 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005698 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005699 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005700 while (*captureResult == EAGAIN) {
5701 captureResult.reset();
5702 result = postMessageAsync(message);
5703 if (result != NO_ERROR) {
5704 return result;
5705 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005706 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005707 }
5708 result = *captureResult;
5709 }
5710
5711 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005712 sync_wait(syncFd, -1);
5713 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005714 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005715
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005716 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005717}
5718
chaviwa76b2712017-09-20 12:02:26 -07005719void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005720 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005721 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5722 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005723 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005724
chaviwa76b2712017-09-20 12:02:26 -07005725 const auto reqWidth = renderArea.getReqWidth();
5726 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005727 const auto sourceCrop = renderArea.getSourceCrop();
5728 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005729
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005730 renderengine::DisplaySettings clientCompositionDisplay;
5731 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005732
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005733 // assume that bounds are never offset, and that they are the same as the
5734 // buffer bounds.
5735 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5736 ui::Transform transform = renderArea.getTransform();
5737 mat4 m;
5738 m[0][0] = transform[0][0];
5739 m[0][1] = transform[0][1];
5740 m[0][3] = transform[0][2];
5741 m[1][0] = transform[1][0];
5742 m[1][1] = transform[1][1];
5743 m[1][3] = transform[1][2];
5744 m[3][0] = transform[2][0];
5745 m[3][1] = transform[2][1];
5746 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005747
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005748 clientCompositionDisplay.globalTransform = m;
5749 mat4 rotMatrix;
5750 // Displacement for repositioning the clipping rectangle after rotating it
5751 // with the rotation hint.
5752 int displacementX = 0;
5753 int displacementY = 0;
5754 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5755 switch (rotation) {
5756 case ui::Transform::ROT_90:
5757 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5758 displacementX = reqWidth;
5759 break;
5760 case ui::Transform::ROT_180:
5761 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5762 displacementX = reqWidth;
5763 displacementY = reqHeight;
5764 break;
5765 case ui::Transform::ROT_270:
5766 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5767 displacementY = reqHeight;
5768 break;
5769 default:
5770 break;
5771 }
5772 // We need to transform the clipping window into the right spot.
5773 // First, rotate the clipping rectangle by the rotation hint to get the
5774 // right orientation
5775 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5776 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5777 const vec4 rotClipTL = rotMatrix * clipTL;
5778 const vec4 rotClipBR = rotMatrix * clipBR;
5779 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5780 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5781 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5782 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5783
5784 // Now reposition the clipping rectangle with the displacement vector
5785 // computed above.
5786 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5787
5788 clientCompositionDisplay.clip =
5789 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5790 newClipRight + displacementX, newClipBottom + displacementY);
5791
5792 // We need to perform the same transformation in layer space, so propagate
5793 // it to the global transform.
5794 mat4 clipTransform = displacementMat * rotMatrix;
5795 clientCompositionDisplay.globalTransform *= clipTransform;
5796 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5797 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005798
chaviw50da5042018-04-09 13:49:37 -07005799 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005800
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005801 renderengine::LayerSettings fillLayer;
5802 fillLayer.source.buffer.buffer = nullptr;
5803 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5804 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5805 fillLayer.alpha = half(alpha);
5806 clientCompositionLayers.push_back(fillLayer);
5807
5808 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005809 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005810 renderengine::LayerSettings layerSettings;
5811 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5812 layerSettings);
5813 if (prepared) {
5814 clientCompositionLayers.push_back(layerSettings);
5815 }
chaviwa76b2712017-09-20 12:02:26 -07005816 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005817
5818 clientCompositionDisplay.clearRegion = clearRegion;
5819 base::unique_fd drawFence;
5820 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5821 &drawFence);
5822
5823 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005824}
5825
chaviwa76b2712017-09-20 12:02:26 -07005826status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5827 TraverseLayersFunction traverseLayers,
5828 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005829 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005830 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005831 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005832 ATRACE_CALL();
5833
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005834 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005835
5836 traverseLayers([&](Layer* layer) {
5837 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5838 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005839
Robert Carr03480e22018-01-04 16:02:06 -08005840 // We allow the system server to take screenshots of secure layers for
5841 // use in situations like the Screen-rotation animation and place
5842 // the impetus on WindowManager to not persist them.
5843 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005844 ALOGW("FB is protected: PERMISSION_DENIED");
5845 return PERMISSION_DENIED;
5846 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005847 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005848 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005849}
5850
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005851// ---------------------------------------------------------------------------
5852
Dan Stoza412903f2017-04-27 13:42:17 -07005853void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5854 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005855}
5856
Dan Stoza412903f2017-04-27 13:42:17 -07005857void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5858 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005859}
5860
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005861void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005862 const LayerVector::Visitor& visitor) {
5863 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005864 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005865 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005866 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005867 continue;
5868 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005869 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005870 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005871 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005872 return;
5873 }
chaviwa76b2712017-09-20 12:02:26 -07005874 if (!layer->isVisible()) {
5875 return;
5876 }
5877 visitor(layer);
5878 });
5879 }
5880}
5881
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005882}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005883
Lloyd Pique074e8122018-07-26 12:57:23 -07005884
Mathias Agopian3f844832013-08-07 21:24:32 -07005885#if defined(__gl_h_)
5886#error "don't include gl/gl.h in this file"
5887#endif
5888
5889#if defined(__gl2_h_)
5890#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005891#endif