blob: 8530309dd20df22c3dac2d06d237607fb1346e17 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080065#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700113#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900115#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
chaviw1d044282017-09-27 12:19:28 -0700117#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900118#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700121
Jaesoo Lee43518572017-01-23 19:03:16 +0900122using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800125
Yiwei Zhang5434a782018-12-05 18:06:32 -0800126using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700127using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700128using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800129using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700130using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700131using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
134
Steven Thomasb02664d2017-07-26 18:48:28 -0700135namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700136
137#pragma clang diagnostic push
138#pragma clang diagnostic error "-Wswitch-enum"
139
140bool isWideColorMode(const ColorMode colorMode) {
141 switch (colorMode) {
142 case ColorMode::DISPLAY_P3:
143 case ColorMode::ADOBE_RGB:
144 case ColorMode::DCI_P3:
145 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700146 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700147 case ColorMode::BT2100_PQ:
148 case ColorMode::BT2100_HLG:
149 return true;
150 case ColorMode::NATIVE:
151 case ColorMode::STANDARD_BT601_625:
152 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
153 case ColorMode::STANDARD_BT601_525:
154 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
155 case ColorMode::STANDARD_BT709:
156 case ColorMode::SRGB:
157 return false;
158 }
159 return false;
160}
161
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700162ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
163 switch (rotation) {
164 case ISurfaceComposer::eRotateNone:
165 return ui::Transform::ROT_0;
166 case ISurfaceComposer::eRotate90:
167 return ui::Transform::ROT_90;
168 case ISurfaceComposer::eRotate180:
169 return ui::Transform::ROT_180;
170 case ISurfaceComposer::eRotate270:
171 return ui::Transform::ROT_270;
172 }
173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
174 return ui::Transform::ROT_0;
175}
176
Peiyong Linfca547f2018-07-09 13:03:33 -0700177#pragma clang diagnostic pop
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179class ConditionalLock {
180public:
181 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
182 if (lock) {
183 mMutex.lock();
184 }
185 }
186 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
187private:
188 Mutex& mMutex;
189 bool mLocked;
190};
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
Peiyong Lin9d846a52018-11-05 13:18:20 -0800192// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
193bool validateCompositionDataspace(Dataspace dataspace) {
194 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
195}
196
Steven Thomasb02664d2017-07-26 18:48:28 -0700197} // namespace anonymous
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Mathias Agopian99b49842011-06-27 16:05:52 -0700201const String16 sHardwareTest("android.permission.HARDWARE_TEST");
202const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
203const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
204const String16 sDump("android.permission.DUMP");
205
Daniel Solomon42d04562019-01-20 21:03:19 -0800206constexpr float kSrgbRedX = 0.4123f;
207constexpr float kSrgbRedY = 0.2126f;
208constexpr float kSrgbRedZ = 0.0193f;
209constexpr float kSrgbGreenX = 0.3576f;
210constexpr float kSrgbGreenY = 0.7152f;
211constexpr float kSrgbGreenZ = 0.1192f;
212constexpr float kSrgbBlueX = 0.1805f;
213constexpr float kSrgbBlueY = 0.0722f;
214constexpr float kSrgbBlueZ = 0.9506f;
215constexpr float kSrgbWhiteX = 0.9505f;
216constexpr float kSrgbWhiteY = 1.0000f;
217constexpr float kSrgbWhiteZ = 1.0891f;
218
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800219constexpr float kDefaultRefreshRate = 60.f;
220constexpr float kPerformanceRefreshRate = 90.f;
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700230int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700231bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700232bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700233Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
235Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
254 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
David Sodmanbc815282017-11-05 18:57:52 -0800266SurfaceFlingerBE::SurfaceFlingerBE()
267 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800268 mFrameBuckets(),
269 mTotalTime(0),
270 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800271 mComposerSequenceId(0) {
272}
273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
275 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800276 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700278 mTransactionPending(false),
279 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700280 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700281 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800283 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800285 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800286 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800287 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700289 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700290 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700291 mDebugInTransaction(0),
292 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700293 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800294 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800300 mCompositionEngine{getFactory().createCompositionEngine()} {
301 mSetInputWindowsListener = new SetInputWindowsListener(this);
302}
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 Krulecc2870422019-01-29 19:00:58 -0800398 property_get("debug.sf.use_90Hz", value, "0");
399 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800400
Ana Krulecba13ab32019-02-20 14:14:12 -0800401 property_get("debug.sf.use_smart_90_for_video", value, "0");
402 mUseSmart90ForVideo = atoi(value);
403
Ana Krulec757f63a2019-01-25 10:46:18 -0800404 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
405 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700406
Romain Guy11d63f42017-07-20 12:47:14 -0700407 // We should be reading 'persist.sys.sf.color_saturation' here
408 // but since /data may be encrypted, we need to wait until after vold
409 // comes online to attempt to read the property. The property is
410 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800411
412 if (useTrebleTestingOverride()) {
413 // Without the override SurfaceFlinger cannot connect to HIDL
414 // services that are not listed in the manifests. Considered
415 // deriving the setting from the set service name, but it
416 // would be brittle if the name that's not 'default' is used
417 // for production purposes later on.
418 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
419 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420}
421
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422void SurfaceFlinger::onFirstRef()
423{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800424 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427SurfaceFlinger::~SurfaceFlinger()
428{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429}
430
Dan Stozac7014012014-02-14 15:03:43 -0800431void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432{
433 // the window manager died on us. prepare its eulogy.
434
Andy McFadden13a082e2012-08-24 10:16:42 -0700435 // restore initial conditions (default device unblank, etc)
436 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437
438 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700439 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440}
441
Robert Carr1db73f62016-12-21 12:58:51 -0800442static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700443 status_t err = client->initCheck();
444 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 }
Robert Carr1db73f62016-12-21 12:58:51 -0800447 return nullptr;
448}
449
450sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
451 return initClient(new Client(this));
452}
453
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700454sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
455 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456{
457 class DisplayToken : public BBinder {
458 sp<SurfaceFlinger> flinger;
459 virtual ~DisplayToken() {
460 // no more references, this display must be terminated
461 Mutex::Autolock _l(flinger->mStateLock);
462 flinger->mCurrentState.displays.removeItem(this);
463 flinger->setTransactionFlags(eDisplayTransactionNeeded);
464 }
465 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700466 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467 : flinger(flinger) {
468 }
469 };
470
471 sp<BBinder> token = new DisplayToken(this);
472
473 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700474 // Display ID is assigned when virtual display is allocated by HWC.
475 DisplayDeviceState state;
476 state.isSecure = secure;
477 state.displayName = displayName;
478 mCurrentState.displays.add(token, state);
479 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480 return token;
481}
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 Mutex::Autolock _l(mStateLock);
485
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
487 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 return;
490 }
491
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
493 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 ALOGE("destroyDisplay called for non-virtual display");
495 return;
496 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 mInterceptor->saveDisplayDeletion(state.sequenceId);
498 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 setTransactionFlags(eDisplayTransactionNeeded);
500}
501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
503 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 const auto internalDisplayId = getInternalDisplayIdLocked();
506 if (!internalDisplayId) {
507 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 }
509
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800510 std::vector<PhysicalDisplayId> displayIds;
511 displayIds.reserve(mPhysicalDisplayTokens.size());
512 displayIds.push_back(internalDisplayId->value);
513
514 for (const auto& [id, token] : mPhysicalDisplayTokens) {
515 if (id != *internalDisplayId) {
516 displayIds.push_back(id.value);
517 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800520 return displayIds;
521}
522
523sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
524 Mutex::Autolock lock(mStateLock);
525 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700526}
527
Ady Abraham37965d42018-11-01 13:43:32 -0700528status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
529 if (!outGetColorManagement) {
530 return BAD_VALUE;
531 }
532 *outGetColorManagement = useColorManagement;
533 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700534}
535
Lloyd Pique441d5042018-10-18 16:49:51 -0700536HWComposer& SurfaceFlinger::getHwComposer() const {
537 return mCompositionEngine->getHwComposer();
538}
539
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700540renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
541 return mCompositionEngine->getRenderEngine();
542}
543
Lloyd Pique70d91362018-10-18 16:02:55 -0700544compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
545 return *mCompositionEngine.get();
546}
547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548void SurfaceFlinger::bootFinished()
549{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700550 if (mStartPropertySetThread->join() != NO_ERROR) {
551 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 const nsecs_t now = systemTime();
554 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000555 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
557 // wait patiently for the window manager death
558 const String16 name("window");
559 sp<IBinder> window(defaultServiceManager()->getService(name));
560 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700561 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
Robert Carr720e5062018-07-30 17:45:14 -0700563 sp<IBinder> input(defaultServiceManager()->getService(
564 String16("inputflinger")));
565 if (input == nullptr) {
566 ALOGE("Failed to link to input service");
567 } else {
568 mInputFlinger = interface_cast<IInputFlinger>(input);
569 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570
Steven Thomas050b2c82017-03-06 11:45:16 -0800571 if (mVrFlinger) {
572 mVrFlinger->OnBootFinished();
573 }
574
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700576 // formerly we would just kill the process, but we now ask it to exit so it
577 // can choose where to stop the animation.
578 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700579
580 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
581 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
582 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700583
Ana Krulecbd6654b2019-02-15 15:18:15 -0800584 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 readPersistentProperties();
586 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587
588 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
589 // away and it should be controlled by flipping the switch in setting. The switch in
590 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
591 // The boot must be complete before we can set the active config.
592
593 if (mUse90Hz) {
594 mPhaseOffsets->setRefreshRateType(
595 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
596 setRefreshRateTo(RefreshRateType::PERFORMANCE);
597 } else {
598 mPhaseOffsets->setRefreshRateType(
599 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
600 setRefreshRateTo(RefreshRateType::DEFAULT);
601 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800602 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800603}
604
Dan Stoza436ccf32018-06-21 12:10:12 -0700605uint32_t SurfaceFlinger::getNewTexture() {
606 {
607 std::lock_guard lock(mTexturePoolMutex);
608 if (!mTexturePool.empty()) {
609 uint32_t name = mTexturePool.back();
610 mTexturePool.pop_back();
611 ATRACE_INT("TexturePoolSize", mTexturePool.size());
612 return name;
613 }
614
615 // The pool was too small, so increase it for the future
616 ++mTexturePoolSize;
617 }
618
619 // The pool was empty, so we need to get a new texture name directly using a
620 // blocking call to the main thread
621 uint32_t name = 0;
622 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
623 return name;
624}
625
Mathias Agopian3f844832013-08-07 21:24:32 -0700626void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700627 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700628}
629
Wei Wangf9b05ee2017-07-19 20:59:39 -0700630// Do not call property_set on main thread which will be blocked by init
631// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700633 ALOGI( "SurfaceFlinger's main thread ready to run. "
634 "Initializing graphics H/W...");
635
Ana Krulec757f63a2019-01-25 10:46:18 -0800636 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700639 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800640 mScheduler =
641 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
642 auto resyncCallback =
643 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800644
Ana Krulecc2870422019-01-29 19:00:58 -0800645 mAppConnectionHandle =
646 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
647 resyncCallback,
648 impl::EventThread::InterceptVSyncsCallback());
649 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
650 resyncCallback, [this](nsecs_t timestamp) {
651 mInterceptor->saveVSyncEvent(timestamp);
652 });
653
654 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
655 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
656 mSfConnectionHandle.get());
657
Steven Thomasb02664d2017-07-26 18:48:28 -0700658 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700659 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700660 renderEngineFeature |= (useColorManagement ?
661 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700662 renderEngineFeature |= (useContextPriority ?
663 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700664
665 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700666 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700667 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700668 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700669
670 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
671 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700672 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
673 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800674 // Process any initial hotplug and resulting display changes.
675 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 const auto display = getDefaultDisplayDeviceLocked();
677 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700678 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800680
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700682 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700683 // This callback is called from the vr flinger dispatch thread. We
684 // need to call signalTransaction(), which requires holding
685 // mStateLock when we're not on the main thread. Acquiring
686 // mStateLock from the vr flinger dispatch thread might trigger a
687 // deadlock in surface flinger (see b/66916578), so post a message
688 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
691 mVrFlingerRequestsDisplay = requestDisplay;
692 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800694 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700695 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
696 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700697 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 .value_or(0),
699 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 if (!mVrFlinger) {
701 ALOGE("Failed to start vrflinger");
702 }
703 }
704
Mathias Agopian92a979a2012-08-02 18:32:23 -0700705 // initialize our drawing state
706 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700707
Andy McFadden13a082e2012-08-24 10:16:42 -0700708 // set initial conditions (e.g. unblank default device)
709 initializeDisplays();
710
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700711 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700712
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700714
715 const bool presentFenceReliable =
716 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
717 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718
719 if (mStartPropertySetThread->Start() != NO_ERROR) {
720 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800721 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800722
Kevin DuBois36233132019-02-19 14:08:55 -0800723 if (mUse90Hz) {
724 mScheduler->setExpiredIdleTimerCallback([this] {
725 Mutex::Autolock lock(mStateLock);
726 setRefreshRateTo(RefreshRateType::DEFAULT);
727 });
728 mScheduler->setResetIdleTimerCallback([this] {
729 Mutex::Autolock lock(mStateLock);
730 setRefreshRateTo(RefreshRateType::PERFORMANCE);
731 });
732 }
Ana Krulecc2870422019-01-29 19:00:58 -0800733 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
734 *display->getId()),
735 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800736
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800752
753 property_get("persist.sys.sf.color_mode", value, "0");
754 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700755}
756
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Start boot animation service by setting a property mailbox
759 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700762 if (mStartPropertySetThread->join() != NO_ERROR) {
763 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800764 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700765}
766
Mathias Agopian875d8e12013-06-07 15:35:48 -0700767size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700768 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700769}
770
Mathias Agopian875d8e12013-06-07 15:35:48 -0700771size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700772 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700773}
774
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800775// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800776
Jamie Gennis582270d2011-08-17 18:19:00 -0700777bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800779 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800780 return authenticateSurfaceTextureLocked(bufferProducer);
781}
782
783bool SurfaceFlinger::authenticateSurfaceTextureLocked(
784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800785 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800786 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800787}
788
Brian Anderson6b376712017-04-04 10:51:39 -0700789status_t SurfaceFlinger::getSupportedFrameTimestamps(
790 std::vector<FrameEvent>* outSupported) const {
791 *outSupported = {
792 FrameEvent::REQUESTED_PRESENT,
793 FrameEvent::ACQUIRE,
794 FrameEvent::LATCH,
795 FrameEvent::FIRST_REFRESH_START,
796 FrameEvent::LAST_REFRESH_START,
797 FrameEvent::GPU_COMPOSITION_DONE,
798 FrameEvent::DEQUEUE_READY,
799 FrameEvent::RELEASE,
800 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700801 ConditionalLock _l(mStateLock,
802 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700803 if (!getHwComposer().hasCapability(
804 HWC2::Capability::PresentFenceIsNotReliable)) {
805 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
806 }
807 return NO_ERROR;
808}
809
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800810status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
811 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700812 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 return BAD_VALUE;
814 }
815
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800816 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 if (!displayId) {
818 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 // TODO: Not sure if display density should handled by SF any longer
822 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700825 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800826 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700827 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 }
829 return density;
830 }
831 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 return getDensityFromProperty("ro.sf.lcd_density"); }
836 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Dominik Laskowski075d3172018-05-24 15:50:06 -0700840 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 DisplayInfo info = DisplayInfo();
842
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 float xdpi = hwConfig->getDpiX();
844 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700846 info.w = hwConfig->getWidth();
847 info.h = hwConfig->getHeight();
848 // Default display viewport to display width and height
849 info.viewportW = info.w;
850 info.viewportH = info.h;
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 // The density of the device is provided by a build property
854 float density = Density::getBuildDensity() / 160.0f;
855 if (density == 0) {
856 // the build doesn't provide a density -- this is wrong!
857 // use xdpi instead
858 ALOGE("ro.sf.lcd_density must be defined as a build property");
859 density = xdpi / 160.0f;
860 }
861 if (Density::getEmuDensity()) {
862 // if "qemu.sf.lcd_density" is specified, it overrides everything
863 xdpi = ydpi = density = Density::getEmuDensity();
864 density /= 160.0f;
865 }
866 info.density = density;
867
868 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869 const auto display = getDefaultDisplayDeviceLocked();
870 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700871
872 // This is for screenrecord
873 const Rect viewport = display->getViewport();
874 if (viewport.isValid()) {
875 info.viewportW = uint32_t(viewport.getWidth());
876 info.viewportH = uint32_t(viewport.getHeight());
877 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 } else {
879 // TODO: where should this value come from?
880 static const int TV_DENSITY = 213;
881 info.density = TV_DENSITY / 160.0f;
882 info.orientation = 0;
883 }
884
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 info.xdpi = xdpi;
886 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800888 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800902 info.presentationDeadline =
903 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700904
905 // All non-virtual displays are currently considered secure.
906 info.secure = true;
907
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800908 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700909 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800910 std::swap(info.w, info.h);
911 }
912
Michael Wright28f24d02016-07-12 13:30:53 -0700913 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 }
915
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 return NO_ERROR;
917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
920 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
Ana Krulecc2870422019-01-29 19:00:58 -0800924 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700925 return NO_ERROR;
926}
927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
929 const auto display = getDisplayDevice(displayToken);
930 if (!display) {
931 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800932 return BAD_VALUE;
933 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700936}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700937
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
939 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800940
Ana Krulec7d1d6832018-12-27 11:10:09 -0800941 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942 // Lock is acquired by setRefreshRateTo.
943 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
945 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
946 return;
947 }
948
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 // Lock is acquired by setRefreshRateTo.
950 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800951 if (!display) {
952 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
953 displayToken.get());
954 return;
955 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700956 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800957 ALOGW("Attempt to set active config %d for virtual display", mode);
958 return;
959 }
960 int currentDisplayPowerMode = display->getPowerMode();
961 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
962 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700963 return;
964 }
965
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966 // Don't check against the current mode yet. Worst case we set the desired
967 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 std::lock_guard<std::mutex> lock(mActiveConfigLock);
969 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
970
971 if (!mDesiredActiveConfigChanged) {
972 // This is the first time we set the desired
973 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
974
975 // This will trigger HWC refresh without resetting the idle timer.
976 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 mDesiredActiveConfigChanged = true;
979 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980}
981
982status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
983 ATRACE_CALL();
984 postMessageSync(new LambdaMessage(
985 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
986 return NO_ERROR;
987}
988
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989void SurfaceFlinger::setActiveConfigInternal() {
990 ATRACE_CALL();
991
992 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800993 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994
995 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
996 display->setActiveConfig(mUpcomingActiveConfig.configId);
997
Ana Krulecc2870422019-01-29 19:00:58 -0800998 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1000}
1001
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001003 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001004 // we may be in the process of changing the active state
1005 if (mWaitForNextInvalidate) {
1006 mWaitForNextInvalidate = false;
1007
1008 repaintEverythingForHWC();
1009 // We do not want to give another frame to HWC while we are transitioning.
1010 return true;
1011 }
1012
1013 if (mCheckPendingFence) {
1014 if (mPreviousPresentFence != Fence::NO_FENCE &&
1015 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1016 // fence has not signaled yet. wait for the next invalidate
1017 repaintEverythingForHWC();
1018 return true;
1019 }
1020
1021 // We received the present fence from the HWC, so we assume it successfully updated
1022 // the config, hence we update SF.
1023 mCheckPendingFence = false;
1024 setActiveConfigInternal();
1025 }
1026
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 // Store the local variable to release the lock.
1028 ActiveConfigInfo desiredActiveConfig;
1029 {
1030 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 if (!mDesiredActiveConfigChanged) {
1032 return false;
1033 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001034 desiredActiveConfig = mDesiredActiveConfig;
1035 }
1036
1037 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1039 // display is not valid or we are already in the requested mode
1040 // on both cases there is nothing left to do
1041 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1042 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1043 mDesiredActiveConfigChanged = false;
1044 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1045 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001046 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001047
1048 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1049 mUpcomingActiveConfig = desiredActiveConfig;
1050 const auto displayId = display->getId();
1051 LOG_ALWAYS_FATAL_IF(!displayId);
1052
1053 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1054 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1055
1056 // we need to submit an empty frame to HWC to start the process
1057 mWaitForNextInvalidate = true;
1058 mCheckPendingFence = true;
1059
1060 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001061}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1064 Vector<ColorMode>* outColorModes) {
1065 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001066 return BAD_VALUE;
1067 }
1068
Peiyong Lina52f0292018-03-14 17:26:31 -07001069 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001070 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001071 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1072
1073 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1074 if (!displayId) {
1075 return NAME_NOT_FOUND;
1076 }
1077
Dominik Laskowski075d3172018-05-24 15:50:06 -07001078 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080 outColorModes->clear();
1081 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1082
1083 return NO_ERROR;
1084}
1085
Daniel Solomon42d04562019-01-20 21:03:19 -08001086status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1087 ui::DisplayPrimaries &primaries) {
1088 if (!displayToken) {
1089 return BAD_VALUE;
1090 }
1091
1092 // Currently we only support this API for a single internal display.
1093 if (getInternalDisplayToken() != displayToken) {
1094 return BAD_VALUE;
1095 }
1096
1097 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1098 return NO_ERROR;
1099}
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1102 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001103 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001104 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001105 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001106}
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001109 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 Vector<ColorMode> modes;
1111 getDisplayColorModes(displayToken, &modes);
1112 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1113 if (mode < ColorMode::NATIVE || !exists) {
1114 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1115 decodeColorMode(mode).c_str(), mode, displayToken.get());
1116 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001117 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118 const auto display = getDisplayDevice(displayToken);
1119 if (!display) {
1120 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1121 decodeColorMode(mode).c_str(), mode, displayToken.get());
1122 } else if (display->isVirtual()) {
1123 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1124 decodeColorMode(mode).c_str(), mode);
1125 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001126 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1127 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 }
1129 }));
1130
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return NO_ERROR;
1132}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001133
Svetoslavd85084b2014-03-20 10:28:31 -07001134status_t SurfaceFlinger::clearAnimationFrameStats() {
1135 Mutex::Autolock _l(mStateLock);
1136 mAnimFrameTracker.clearStats();
1137 return NO_ERROR;
1138}
1139
1140status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1141 Mutex::Autolock _l(mStateLock);
1142 mAnimFrameTracker.getStats(outStats);
1143 return NO_ERROR;
1144}
1145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1147 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001148 Mutex::Autolock _l(mStateLock);
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150 const auto display = getDisplayDeviceLocked(displayToken);
1151 if (!display) {
1152 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001153 return BAD_VALUE;
1154 }
1155
Peiyong Linfb069302018-04-25 14:34:31 -07001156 // At this point the DisplayDeivce should already be set up,
1157 // meaning the luminance information is already queried from
1158 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001160 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1161 capabilities.getDesiredMaxLuminance(),
1162 capabilities.getDesiredMaxAverageLuminance(),
1163 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001164
1165 return NO_ERROR;
1166}
1167
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001168status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1169 ui::PixelFormat* outFormat,
1170 ui::Dataspace* outDataspace,
1171 uint8_t* outComponentMask) const {
1172 if (!outFormat || !outDataspace || !outComponentMask) {
1173 return BAD_VALUE;
1174 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001175 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001176 if (!display || !display->getId()) {
1177 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1178 return BAD_VALUE;
1179 }
1180 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1181 outDataspace, outComponentMask);
1182}
1183
Kevin DuBois74e53772018-11-19 10:52:38 -08001184status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1185 bool enable, uint8_t componentMask,
1186 uint64_t maxFrames) const {
1187 const auto display = getDisplayDevice(displayToken);
1188 if (!display || !display->getId()) {
1189 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1190 return BAD_VALUE;
1191 }
1192
1193 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1194 componentMask, maxFrames);
1195}
1196
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001197status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1198 uint64_t maxFrames, uint64_t timestamp,
1199 DisplayedFrameStats* outStats) const {
1200 const auto display = getDisplayDevice(displayToken);
1201 if (!display || !display->getId()) {
1202 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1203 return BAD_VALUE;
1204 }
1205
1206 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1207 outStats);
1208}
1209
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001210status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1211 if (!outSupported) {
1212 return BAD_VALUE;
1213 }
1214 *outSupported = getRenderEngine().supportsProtectedContent();
1215 return NO_ERROR;
1216}
1217
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001218status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1219 bool* outIsWideColorDisplay) const {
1220 if (!displayToken || !outIsWideColorDisplay) {
1221 return BAD_VALUE;
1222 }
1223 Mutex::Autolock _l(mStateLock);
1224 const auto display = getDisplayDeviceLocked(displayToken);
1225 if (!display) {
1226 return BAD_VALUE;
1227 }
1228 *outIsWideColorDisplay = display->hasWideColorGamut();
1229 return NO_ERROR;
1230}
1231
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001233 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001234 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236 if (mInjectVSyncs == enable) {
1237 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001239
Ana Krulecc2870422019-01-29 19:00:58 -08001240 auto resyncCallback =
1241 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001242
Ana Krulec98b5b242018-08-10 15:03:23 -07001243 // TODO(akrulec): Part of the Injector should be refactored, so that it
1244 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001245 if (enable) {
1246 ALOGV("VSync Injections enabled");
1247 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001248 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001249 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001251 impl::EventThread::InterceptVSyncsCallback(),
1252 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 } else {
1256 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001257 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1258 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001259 }
1260
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001261 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001262 }));
1263
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001264 return NO_ERROR;
1265}
1266
1267status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001268 Mutex::Autolock _l(mStateLock);
1269
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001270 if (!mInjectVSyncs) {
1271 ALOGE("VSync Injections not enabled");
1272 return BAD_VALUE;
1273 }
1274 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1275 ALOGV("Injecting VSync inside SurfaceFlinger");
1276 mVSyncInjector->onInjectSyncEvent(when);
1277 }
1278 return NO_ERROR;
1279}
1280
Lloyd Pique755e3192018-01-31 16:46:15 -08001281status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1282 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001283 // Try to acquire a lock for 1s, fail gracefully
1284 const status_t err = mStateLock.timedLock(s2ns(1));
1285 const bool locked = (err == NO_ERROR);
1286 if (!locked) {
1287 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1288 return TIMED_OUT;
1289 }
1290
1291 outLayers->clear();
1292 mCurrentState.traverseInZOrder([&](Layer* layer) {
1293 outLayers->push_back(layer->getLayerDebugInfo());
1294 });
1295
1296 mStateLock.unlock();
1297 return NO_ERROR;
1298}
1299
Peiyong Linc6780972018-10-28 15:24:08 -07001300status_t SurfaceFlinger::getCompositionPreference(
1301 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1302 Dataspace* outWideColorGamutDataspace,
1303 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001304 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001305 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001306 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001307 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001308 return NO_ERROR;
1309}
1310
Dan Stoza84ab9372018-12-17 15:27:57 -08001311status_t SurfaceFlinger::addRegionSamplingListener(
1312 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1313 const sp<IRegionSamplingListener>& /*listener*/) {
1314 return NO_ERROR;
1315}
1316
1317status_t SurfaceFlinger::removeRegionSamplingListener(
1318 const sp<IRegionSamplingListener>& /*listener*/) {
1319 return NO_ERROR;
1320}
1321
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001322// ----------------------------------------------------------------------------
1323
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001324sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1325 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001326 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001327 Mutex::Autolock lock(mStateLock);
1328 return getVsyncPeriod();
1329 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001330
Ana Krulecc2870422019-01-29 19:00:58 -08001331 const auto& handle =
1332 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001333
Ana Krulecc2870422019-01-29 19:00:58 -08001334 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001335}
1336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001337// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338
1339void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001340 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001341}
1342
1343void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001344 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345}
1346
1347void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349}
1350
1351void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001352 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001357 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001358 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001359}
1360
1361status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001362 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001363 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001364 if (res == NO_ERROR) {
1365 msg->wait();
1366 }
1367 return res;
1368}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001369
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001370void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001371 do {
1372 waitForEvent();
1373 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001374}
1375
Dominik Laskowski83b88212018-12-11 13:34:06 -08001376nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001377 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001378 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1379 return 0;
1380 }
1381
1382 const auto config = getHwComposer().getActiveConfig(*displayId);
1383 return config ? config->getVsyncPeriod() : 0;
1384}
1385
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001386void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1387 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001388 ATRACE_NAME("SF onVsync");
1389
Steven Thomas3cfac282017-02-06 12:29:30 -08001390 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001391 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001392 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001393 return;
1394 }
1395
Dominik Laskowski075d3172018-05-24 15:50:06 -07001396 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001397 return;
1398 }
1399
Dominik Laskowski075d3172018-05-24 15:50:06 -07001400 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001401 // For now, we don't do anything with external display vsyncs.
1402 return;
1403 }
1404
Ana Krulecc2870422019-01-29 19:00:58 -08001405 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001406}
1407
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001409 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1410 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411}
1412
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001413void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1414 mPhaseOffsets->setRefreshRateType(refreshRate);
1415
1416 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1417 mVsyncModulator.setPhaseOffsets(early, gl, late);
1418
1419 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001420 return;
1421 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001422
Ana Krulec7d1d6832018-12-27 11:10:09 -08001423 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1424 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1425 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1426 // refresh cycle.
1427
1428 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001429 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001430 if (currentVsyncPeriod == 0) {
1431 return;
1432 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001433
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1435 // floating numbers.
1436 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001437 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1438 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001439 if (std::abs(currentFps - newFps) <= 1) {
1440 return;
1441 }
1442
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001443 const auto displayId = getInternalDisplayIdLocked();
1444 LOG_ALWAYS_FATAL_IF(!displayId);
1445
1446 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001447 for (int i = 0; i < configs.size(); i++) {
1448 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1449 if (vsyncPeriod == 0) {
1450 continue;
1451 }
1452 const float fps = 1e9 / vsyncPeriod;
1453 // TODO(b/113612090): There should be a better way at determining which config
1454 // has the right refresh rate.
1455 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001456 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001457 }
1458 }
1459}
1460
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001461void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001462 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001463 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001464 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001465
Lloyd Piqueba04e622017-12-14 17:11:26 -08001466 // Ignore events that do not have the right sequenceId.
1467 if (sequenceId != getBE().mComposerSequenceId) {
1468 return;
1469 }
1470
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Only lock if we're not on the main thread. This function is normally
1472 // called on a hwbinder thread, but for the primary display it's called on
1473 // the main thread with the state lock already held, so don't attempt to
1474 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001475 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001476
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001477 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001478
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001479 if (std::this_thread::get_id() == mMainThreadId) {
1480 // Process all pending hot plug events immediately if we are on the main thread.
1481 processDisplayHotplugEventsLocked();
1482 }
1483
Lloyd Piqueba04e622017-12-14 17:11:26 -08001484 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001485}
1486
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001487void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001489 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001490 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001491 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001492 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001493}
1494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001495void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001496 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001498 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001499 getHwComposer().setVsyncEnabled(*displayId,
1500 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1501 }
Mathias Agopian86303202012-07-24 22:46:10 -07001502}
1503
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001505void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001506 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001507 // Clear the drawing state so that the logic inside of
1508 // handleTransactionLocked will fire. It will determine the delta between
1509 // mCurrentState and mDrawingState and re-apply all changes when we make the
1510 // transition.
1511 mDrawingState.displays.clear();
1512 mDisplays.clear();
1513}
1514
Steven Thomas050b2c82017-03-06 11:45:16 -08001515void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001516 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001517 if (!mVrFlinger)
1518 return;
1519 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001520 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001521 return;
1522 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001523
Lloyd Pique441d5042018-10-18 16:49:51 -07001524 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001525 ALOGE("Vr flinger is only supported for remote hardware composer"
1526 " service connections. Ignoring request to transition to vr"
1527 " flinger.");
1528 mVrFlingerRequestsDisplay = false;
1529 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001530 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001532 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001533
Steven Thomas0123ac62018-07-12 11:32:34 -07001534 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001535 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001536
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001537 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001538
1539 // Clear out all the output layers from the composition engine for all
1540 // displays before destroying the hardware composer interface. This ensures
1541 // any HWC layers are destroyed through that interface before it becomes
1542 // invalid.
1543 for (const auto& [token, displayDevice] : mDisplays) {
1544 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1545 compositionengine::Output::OutputLayers());
1546 }
1547
Steven Thomas0123ac62018-07-12 11:32:34 -07001548 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1549 // called below. Clear the reference now so we don't accidentally use it
1550 // later.
1551 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001552
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001554 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001556
Steven Thomasb02664d2017-07-26 18:48:28 -07001557 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001558 // Delete the current instance before creating the new one
1559 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1560 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1561 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1562 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563
Lloyd Pique441d5042018-10-18 16:49:51 -07001564 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001565 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001566
1567 if (vrFlingerRequestsDisplay) {
1568 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570
1571 mVisibleRegionsDirty = true;
1572 invalidateHwcGeometry();
1573
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001574 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001575 display = getDefaultDisplayDeviceLocked();
1576 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001577 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001578
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001580 const nsecs_t vsyncPeriod = getVsyncPeriod();
1581 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001582
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583 // The present fences returned from vr_hwc are not an accurate
1584 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001585 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001586
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 // Use phase of 0 since phase is not known.
1588 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001589 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001590 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001591
Ana Krulecc2870422019-01-29 19:00:58 -08001592 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001593
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001594 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001595 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001596}
1597
Mathias Agopian4fec8732012-06-29 14:12:52 -07001598void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001599 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001600 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001601 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001602 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001603 break;
1604 }
1605
Ana Krulecba13ab32019-02-20 14:14:12 -08001606 if (mUse90Hz && mUseSmart90ForVideo) {
1607 // This call is made each time SF wakes up and creates a new frame. It is part
1608 // of video detection feature.
1609 mScheduler->incrementFrameCounter();
1610 }
Alec Mourife3dc942019-02-12 14:19:18 -08001611 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001612 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001613 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001614 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001615 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1616 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001617 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001618 }
1619 // For now, only propagate backpressure when missing a hwc frame.
1620 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001621 if (mPropagateBackpressure) {
1622 signalLayerUpdate();
1623 break;
1624 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001625 }
Dan Stoza50182882016-07-08 12:02:20 -07001626
Steven Thomas050b2c82017-03-06 11:45:16 -08001627 // Now that we're going to make it to the handleMessageTransaction()
1628 // call below it's safe to call updateVrFlinger(), which will
1629 // potentially trigger a display handoff.
1630 updateVrFlinger();
1631
Dan Stoza6b9454d2014-11-07 16:00:59 -08001632 bool refreshNeeded = handleMessageTransaction();
1633 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001634
1635 updateCursorAsync();
1636 updateInputFlinger();
1637
Dan Stoza58784442014-12-02 16:58:17 -08001638 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001639 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001640 // Signal a refresh if a transaction modified the window state,
1641 // a new buffer was latched, or if HWC has requested a full
1642 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001643 signalRefresh();
1644 }
1645 break;
1646 }
1647 case MessageQueue::REFRESH: {
1648 handleMessageRefresh();
1649 break;
1650 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001651 }
1652}
1653
Dan Stoza6b9454d2014-11-07 16:00:59 -08001654bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001655 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001656 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001657
1658 // Apply any ready transactions in the queues if there are still transactions that have not been
1659 // applied, wake up during the next vsync period and check again
1660 bool transactionNeeded = false;
1661 if (!flushTransactionQueues()) {
1662 transactionNeeded = true;
1663 }
1664
Mathias Agopian4fec8732012-06-29 14:12:52 -07001665 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001666 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001667 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001668
1669 if (transactionNeeded) {
1670 setTransactionFlags(eTransactionNeeded);
1671 }
1672
1673 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001674}
1675
Mathias Agopian4fec8732012-06-29 14:12:52 -07001676void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001678
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001679 mRefreshPending = false;
1680
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001681 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001682 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001683 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001684 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685 for (const auto& [token, display] : mDisplays) {
1686 beginFrame(display);
1687 prepareFrame(display);
1688 doDebugFlashRegions(display, repaintEverything);
1689 doComposition(display, repaintEverything);
1690 }
1691
Adrian Roos1e1a1282017-11-01 19:05:31 +01001692 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001693 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001694
1695 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001696 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001697
Dan Stozabfbffeb2016-07-21 14:49:33 -07001698 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001699 for (const auto& [token, displayDevice] : mDisplays) {
1700 auto display = displayDevice->getCompositionDisplay();
1701 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001702 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001703 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001704 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705
Jorim Jaggi90535212018-05-23 23:44:06 +02001706 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001707
David Sodman7e4ae112018-02-09 15:02:28 -08001708 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001709
1710 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712
David Sodmanfa9b2af2017-12-24 13:28:59 -08001713
1714bool SurfaceFlinger::handleMessageInvalidate() {
1715 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001716 bool refreshNeeded = handlePageFlip();
1717
Vishnu Nair4351ad52019-02-11 14:13:02 -08001718 if (mVisibleRegionsDirty) {
1719 computeLayerBounds();
1720 }
1721
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001722 for (auto& layer : mLayersPendingRefresh) {
1723 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001724 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001725 invalidateLayerStack(layer, visibleReg);
1726 }
1727 mLayersPendingRefresh.clear();
1728 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001729}
1730
David Sodman79bba0e2018-08-05 18:07:49 -07001731void SurfaceFlinger::calculateWorkingSet() {
1732 ATRACE_CALL();
1733 ALOGV(__FUNCTION__);
1734
David Sodman79bba0e2018-08-05 18:07:49 -07001735 // build the h/w work list
1736 if (CC_UNLIKELY(mGeometryInvalid)) {
1737 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001738 for (const auto& [token, displayDevice] : mDisplays) {
1739 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001740 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001741 if (!displayId) {
1742 continue;
1743 }
David Sodman79bba0e2018-08-05 18:07:49 -07001744
Lloyd Pique32cbe282018-10-19 13:09:22 -07001745 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746 for (size_t i = 0; i < currentLayers.size(); i++) {
1747 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001748
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001749 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001750 layer->forceClientComposition(displayDevice);
1751 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001752 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001753
Lloyd Pique32cbe282018-10-19 13:09:22 -07001754 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001755 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001756 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001757 }
David Sodman79bba0e2018-08-05 18:07:49 -07001758 }
1759 }
1760 }
1761
1762 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001763 for (const auto& [token, displayDevice] : mDisplays) {
1764 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001765 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001766 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001767 continue;
1768 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001769 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001770
1771 if (mDrawingState.colorMatrixChanged) {
1772 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001773 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001774 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001775 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001776 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001777 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1778 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001779 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001780 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001781 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1782 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001783 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001784 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001785 }
1786
Peiyong Lind3788632018-09-18 16:01:31 -07001787 // TODO(b/111562338) remove when composer 2.3 is shipped.
1788 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001789 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001790 }
1791
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001792 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001793 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001794 }
1795
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001796 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001797 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001798 layer->setCompositionType(displayDevice,
1799 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001800 continue;
1801 }
1802
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001804 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001806 }
1807
Peiyong Lin13effd12018-07-24 17:01:47 -07001808 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001809 ColorMode colorMode;
1810 Dataspace dataSpace;
1811 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001812 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001813 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001814 }
1815 }
1816
1817 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001818
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001819 for (const auto& [token, displayDevice] : mDisplays) {
1820 auto display = displayDevice->getCompositionDisplay();
1821 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001822 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001823 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1824 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1825 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001826 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001827 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001828 }
1829 }
David Sodman79bba0e2018-08-05 18:07:49 -07001830}
1831
Lloyd Pique32cbe282018-10-19 13:09:22 -07001832void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1833 bool repaintEverything) {
1834 auto display = displayDevice->getCompositionDisplay();
1835 const auto& displayState = display->getState();
1836
Mathias Agopiancd60f992012-08-16 16:28:27 -07001837 // is debugging enabled
1838 if (CC_LIKELY(!mDebugRegion))
1839 return;
1840
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001842 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001843 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001844 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001845 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001846 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001847 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001848
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001849 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001850 }
1851 }
1852
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854
1855 if (mDebugRegion > 1) {
1856 usleep(mDebugRegion * 1000);
1857 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001858
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860}
1861
Adrian Roos1e1a1282017-11-01 19:05:31 +01001862void SurfaceFlinger::doTracing(const char* where) {
1863 ATRACE_CALL();
1864 ATRACE_NAME(where);
1865 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001866 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001867 }
1868}
1869
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001870void SurfaceFlinger::logLayerStats() {
1871 ATRACE_CALL();
1872 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001873 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001875 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001876 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001877 }
1878 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001879
1880 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001881 }
1882}
1883
David Sodman2b406362017-12-15 13:33:47 -08001884void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001886 ATRACE_CALL();
1887 ALOGV("preComposition");
1888
David Sodman2b406362017-12-15 13:33:47 -08001889 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001892 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001893 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894 needExtraInvalidate = true;
1895 }
Robert Carr2047fae2016-11-28 14:09:09 -08001896 });
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 if (needExtraInvalidate) {
1899 signalLayerUpdate();
1900 }
1901}
1902
Ana Krulece588e312018-09-18 12:32:24 -07001903void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1904 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 // Update queue of past composite+present times and determine the
1906 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001907 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001909 while (!getBE().mCompositePresentTimes.empty()) {
1910 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // Cached values should have been updated before calling this method,
1912 // which helps avoid duplicate syscalls.
1913 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1914 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1915 break;
1916 }
1917 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001918 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 }
1920
1921 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001922 while (getBE().mCompositePresentTimes.size() > 16) {
1923 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 }
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001927}
1928
Ana Krulece588e312018-09-18 12:32:24 -07001929void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1930 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 // Integer division and modulo round toward 0 not -inf, so we need to
1932 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001933 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1934 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1935 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936
Ana Krulec757f63a2019-01-25 10:46:18 -08001937 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001938 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001939 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001940 }
1941
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 // Snap the latency to a value that removes scheduling jitter from the
1943 // composition and present times, which often have >1ms of jitter.
1944 // Reducing jitter is important if an app attempts to extrapolate
1945 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001946 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001948 nsecs_t bias = stats.vsyncPeriod / 2;
1949 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1950 nsecs_t snappedCompositeToPresentLatency =
1951 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952
David Sodman99974d22017-11-28 12:04:33 -08001953 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001954 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1955 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001956 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957}
1958
Ady Abraham8164d482019-01-11 14:47:59 -08001959// debug patch for b/119477596 - add stack guards to catch stack
1960// corruptions and disable clang optimizations.
1961// The code below is temporary and planned to be removed once stack
1962// corruptions are found.
1963#pragma clang optimize off
1964class StackGuard {
1965public:
1966 StackGuard(const char* name, const char* func, int line) {
1967 guarders.reserve(MIN_CAPACITY);
1968 guarders.push_back({this, name, func, line});
1969 validate();
1970 }
1971 ~StackGuard() {
1972 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1973 if (i->guard == this) {
1974 guarders.erase(i);
1975 break;
1976 }
1977 }
1978 }
1979
1980 static void validate() {
1981 for (const auto& guard : guarders) {
1982 if (guard.guard->cookie != COOKIE_VALUE) {
1983 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1984 CallStack stack(LOG_TAG);
1985 abort();
1986 }
1987 }
1988 }
1989
1990private:
1991 uint64_t cookie = COOKIE_VALUE;
1992 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1993 static constexpr size_t MIN_CAPACITY = 16;
1994
1995 struct GuarderElement {
1996 StackGuard* guard;
1997 const char* name;
1998 const char* func;
1999 int line;
2000 };
2001
2002 static std::vector<GuarderElement> guarders;
2003};
2004std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2005
2006#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2007
2008#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002009void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002010{
Ady Abraham8164d482019-01-11 14:47:59 -08002011 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ATRACE_CALL();
2013 ALOGV("postComposition");
2014
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002016 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002017 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002018 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002019 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002020 }
Ady Abraham8164d482019-01-11 14:47:59 -08002021 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002022
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002023 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002024 const auto displayDevice = getDefaultDisplayDeviceLocked();
2025 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002029 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2030
Lloyd Pique32cbe282018-10-19 13:09:22 -07002031 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002033 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2034 ->getRenderSurface()
2035 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002036 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037 } else {
2038 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2039 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040
Ady Abraham8164d482019-01-11 14:47:59 -08002041 ASSERT_ON_STACK_GUARD();
2042
David Sodman73beded2017-11-15 11:56:06 -08002043 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2045 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002046 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002048 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002049
Ana Krulece588e312018-09-18 12:32:24 -07002050 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002051 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002052 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053
Ady Abraham8164d482019-01-11 14:47:59 -08002054 ASSERT_ON_STACK_GUARD();
2055
David Sodman2b406362017-12-15 13:33:47 -08002056 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002057 // when we started doing work for this frame, but that should be okay
2058 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002059 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002060 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002061 DEFINE_STACK_GUARD(compositorTiming);
2062
Brian Andersond0010582017-03-07 13:20:31 -08002063 {
David Sodman99974d22017-11-28 12:04:33 -08002064 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002066 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002067
2068 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002069 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002070
Robert Carr2047fae2016-11-28 14:09:09 -08002071 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002072 bool frameLatched =
2073 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2074 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002075 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002076 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002077 recordBufferingStats(layer->getName().string(),
2078 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002079 }
Ady Abraham8164d482019-01-11 14:47:59 -08002080 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002081 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002083 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002084 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002085 mScheduler->addPresentFence(presentFenceTime);
2086 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002087 }
2088
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002089 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002090 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2091 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002092 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002093 }
2094 }
2095
Ady Abraham8164d482019-01-11 14:47:59 -08002096 ASSERT_ON_STACK_GUARD();
2097
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002098 if (mAnimCompositionPending) {
2099 mAnimCompositionPending = false;
2100
Brian Anderson4e606e32017-03-16 15:34:57 -07002101 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002102 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002103 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002104
2105 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002106 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002107 // The HWC doesn't support present fences, so use the refresh
2108 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002109 const nsecs_t presentTime =
2110 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002111 DEFINE_STACK_GUARD(presentTime);
2112
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002114 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002115 }
2116 mAnimFrameTracker.advanceFrame();
2117 }
Dan Stozab90cf072015-03-05 11:05:59 -08002118
Ady Abraham8164d482019-01-11 14:47:59 -08002119 ASSERT_ON_STACK_GUARD();
2120
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002121 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002122 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002123 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002124 }
2125
Ady Abraham8164d482019-01-11 14:47:59 -08002126 ASSERT_ON_STACK_GUARD();
2127
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002128 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002129
Ady Abraham8164d482019-01-11 14:47:59 -08002130 ASSERT_ON_STACK_GUARD();
2131
Lloyd Pique32cbe282018-10-19 13:09:22 -07002132 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2133 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002134 return;
2135 }
2136
2137 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002138 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002139 if (mHasPoweredOff) {
2140 mHasPoweredOff = false;
2141 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002142 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002143 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002144 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002146 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2147 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002148 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002149 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002150 }
David Sodman4a36e932017-11-07 14:29:47 -08002151 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002152
2153 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002154 }
David Sodman4a36e932017-11-07 14:29:47 -08002155 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002156 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002157
2158 {
2159 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002160 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002161 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002162 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002163 if (refillCount > 0) {
2164 const size_t offset = mTexturePool.size();
2165 mTexturePool.resize(mTexturePoolSize);
2166 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2167 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2168 }
Ady Abraham8164d482019-01-11 14:47:59 -08002169 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002170 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002171
Marissa Wallfda30bb2018-10-12 11:34:28 -07002172 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002173 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002174
2175 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002176}
Ady Abraham8164d482019-01-11 14:47:59 -08002177#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002178
Vishnu Nair4351ad52019-02-11 14:13:02 -08002179void SurfaceFlinger::computeLayerBounds() {
2180 for (const auto& pair : mDisplays) {
2181 const auto& displayDevice = pair.second;
2182 const auto display = displayDevice->getCompositionDisplay();
2183 for (const auto& layer : mDrawingState.layersSortedByZ) {
2184 // only consider the layers on the given layer stack
2185 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002186 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002187 }
2188
2189 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2190 }
2191 }
2192}
2193
Mathias Agopiancd60f992012-08-16 16:28:27 -07002194void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 ATRACE_CALL();
2196 ALOGV("rebuildLayerStacks");
2197
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002198 // We need to clear these out now as these may be holding on to a
2199 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2200 // also holds a reference. When the set of visible layers is recomputed,
2201 // some layers may be destroyed if the only thing keeping them alive was
2202 // that list of visible layers associated with each display. The layer
2203 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2204 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2205 for (const auto& [token, display] : mDisplays) {
2206 getBE().mCompositionInfo[token].clear();
2207 }
2208
Mathias Agopiancd60f992012-08-16 16:28:27 -07002209 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002211 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002212 mVisibleRegionsDirty = false;
2213 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002214
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002215 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002216 const auto& displayDevice = pair.second;
2217 auto display = displayDevice->getCompositionDisplay();
2218 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002219 Region opaqueRegion;
2220 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002221 compositionengine::Output::OutputLayers layersSortedByZ;
2222 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002223 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002224 const ui::Transform& tr = displayState.transform;
2225 const Rect bounds = displayState.bounds;
2226 if (displayState.isEnabled) {
2227 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002228
Jeff Sharkey76488112017-02-27 14:15:18 -07002229 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002230 auto compositionLayer = layer->getCompositionLayer();
2231 if (compositionLayer == nullptr) {
2232 return;
2233 }
2234
Lloyd Pique32cbe282018-10-19 13:09:22 -07002235 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002236 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2237 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2238
Lloyd Pique07e33212018-12-18 16:33:37 -08002239 bool needsOutputLayer = false;
2240
Lloyd Piqueef36b002019-01-23 17:52:04 -08002241 if (display->belongsInOutput(layer->getLayerStack(),
2242 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002243 Region drawRegion(tr.transform(
2244 layer->visibleNonTransparentRegion));
2245 drawRegion.andSelf(bounds);
2246 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002247 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002248 }
Chia-I Wu83806892017-11-16 10:50:20 -08002249 }
2250
Lloyd Pique07e33212018-12-18 16:33:37 -08002251 if (needsOutputLayer) {
2252 layersSortedByZ.emplace_back(
2253 display->getOrCreateOutputLayer(displayId, compositionLayer,
2254 layerFE));
2255 deprecated_layersSortedByZ.add(layer);
2256
2257 auto& outputLayerState = layersSortedByZ.back()->editState();
2258 outputLayerState.visibleRegion =
2259 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2260 } else if (displayId) {
2261 // For layers that are being removed from a HWC display,
2262 // and that have queued frames, add them to a a list of
2263 // released layers so we can properly set a fence.
2264 bool hasExistingOutputLayer =
2265 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2266 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2267 mLayersWithQueuedFrames.cend(),
2268 layer) != mLayersWithQueuedFrames.cend();
2269
2270 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002271 layersNeedingFences.add(layer);
2272 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002273 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002274 });
2275 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002276
2277 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2278
2279 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002280 displayDevice->setLayersNeedingFences(layersNeedingFences);
2281
2282 Region undefinedRegion{bounds};
2283 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2284
2285 display->editState().undefinedRegion = undefinedRegion;
2286 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002287 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002288 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002289}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002290
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002291// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002292// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002293// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002295// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296// The returned HDR data space is one of
2297// - Dataspace::UNKNOWN
2298// - Dataspace::BT2020_HLG
2299// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2301 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002302 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 *outHdrDataSpace = Dataspace::UNKNOWN;
2304
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002306 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 case Dataspace::V0_SCRGB:
2308 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002309 case Dataspace::BT2020:
2310 case Dataspace::BT2020_ITU:
2311 case Dataspace::BT2020_LINEAR:
2312 case Dataspace::DISPLAY_BT2020:
2313 bestDataSpace = Dataspace::DISPLAY_BT2020;
2314 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002316 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318 case Dataspace::BT2020_PQ:
2319 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002320 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002321 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002323 case Dataspace::BT2020_HLG:
2324 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002325 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326 // When there's mixed PQ content and HLG content, we set the HDR
2327 // data space to be BT2020_PQ and convert HLG to PQ.
2328 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2329 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002330 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331 break;
2332 default:
2333 break;
2334 }
Romain Guy54f154a2017-10-24 21:40:32 +01002335 }
2336
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002338}
2339
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2342 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002343 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2344 *outMode = ColorMode::NATIVE;
2345 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002347 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002348 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002349
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002350 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002351 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002352
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002353 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2354
Peiyong Lina3ea5592019-02-10 14:45:00 -08002355 switch (mForceColorMode) {
2356 case ColorMode::SRGB:
2357 bestDataSpace = Dataspace::V0_SRGB;
2358 break;
2359 case ColorMode::DISPLAY_P3:
2360 bestDataSpace = Dataspace::DISPLAY_P3;
2361 break;
2362 default:
2363 break;
2364 }
2365
Peiyong Lindfde5112018-06-05 10:58:41 -07002366 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002367 const bool isHdr =
2368 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002369 if (isHdr) {
2370 bestDataSpace = hdrDataSpace;
2371 }
2372
Chia-I Wu0d711262018-05-21 15:19:35 -07002373 RenderIntent intent;
2374 switch (mDisplayColorSetting) {
2375 case DisplayColorSetting::MANAGED:
2376 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002377 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002378 break;
2379 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002380 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002381 break;
2382 default: // vendor display color setting
2383 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2384 break;
2385 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002386
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002387 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002388}
2389
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2391 auto display = displayDevice->getCompositionDisplay();
2392 const auto& displayState = display->getState();
2393
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002394 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002395 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2396 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002397
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398 // If nothing has changed (!dirty), don't recompose.
2399 // If something changed, but we don't currently have any visible layers,
2400 // and didn't when we last did a composition, then skip it this time.
2401 // The second rule does two things:
2402 // - When all layers are removed from a display, we'll emit one black
2403 // frame, then nothing more until we get new layers.
2404 // - When a display is created with a private layer stack, we won't
2405 // emit any black frames until a layer is added to the layer stack.
2406 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002407
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 const char flagPrefix[] = {'-', '+'};
2409 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2411 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2412 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2413 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002414
Lloyd Pique31cb2942018-10-19 17:23:03 -07002415 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002416
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002419 }
2420}
2421
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2423 auto display = displayDevice->getCompositionDisplay();
2424 const auto& displayState = display->getState();
2425
2426 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002427 return;
David Sodman2b406362017-12-15 13:33:47 -08002428 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002430 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002433}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002436 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("doComposition");
2438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 auto display = displayDevice->getCompositionDisplay();
2440 const auto& displayState = display->getState();
2441
2442 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002444 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002445
David Sodmanfa9b2af2017-12-24 13:28:59 -08002446 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002450 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002453}
2454
David Sodmanfa9b2af2017-12-24 13:28:59 -08002455void SurfaceFlinger::postFrame()
2456{
2457 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 const auto display = getDefaultDisplayDeviceLocked();
2459 if (display && getHwComposer().isConnected(*display->getId())) {
2460 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002461 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2462 logFrameStats();
2463 }
2464 }
2465}
2466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002468 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 auto display = displayDevice->getCompositionDisplay();
2472 const auto& displayState = display->getState();
2473 const auto displayId = display->getId();
2474
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002476
Lloyd Pique32cbe282018-10-19 13:09:22 -07002477 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002478 if (displayId) {
2479 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002480 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002481 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002482 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002483 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002484
Chia-I Wu7b549592017-11-15 09:14:57 -08002485 // The layer buffer from the previous frame (if any) is released
2486 // by HWC only when the release fence from this frame (if any) is
2487 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002488 if (displayId && layer->hasHwcLayer(displayDevice)) {
2489 releaseFence =
2490 getHwComposer().getLayerReleaseFence(*displayId,
2491 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002492 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002493
2494 // If the layer was client composited in the previous frame, we
2495 // need to merge with the previous client target acquire fence.
2496 // Since we do not track that, always merge with the current
2497 // client target acquire fence when it is available, even though
2498 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002499 if (layer->getCompositionType(displayDevice) ==
2500 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002501 releaseFence =
2502 Fence::merge("LayerRelease", releaseFence,
2503 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002504 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002505
David Sodman15094112018-10-11 09:39:37 -07002506 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002507 }
Chia-I Wu83806892017-11-16 10:50:20 -08002508
2509 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002511 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002512 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002514 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002515 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002516 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002517 }
2518 }
2519
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 if (displayId) {
2521 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002522 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524}
2525
Mathias Agopian87baae12012-07-31 12:38:26 -07002526void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527{
Mathias Agopian841cde52012-03-01 15:44:37 -08002528 ATRACE_CALL();
2529
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002530 // here we keep a copy of the drawing state (that is the state that's
2531 // going to be overwritten by handleTransactionLocked()) outside of
2532 // mStateLock so that the side-effects of the State assignment
2533 // don't happen with mStateLock held (which can cause deadlocks).
2534 State drawingState(mDrawingState);
2535
Mathias Agopianca4d3602011-05-19 15:38:14 -07002536 Mutex::Autolock _l(mStateLock);
2537 const nsecs_t now = systemTime();
2538 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539
Mathias Agopianca4d3602011-05-19 15:38:14 -07002540 // Here we're guaranteed that some transaction flags are set
2541 // so we can call handleTransactionLocked() unconditionally.
2542 // We call getTransactionFlags(), which will also clear the flags,
2543 // with mStateLock held to guarantee that mCurrentState won't change
2544 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002545
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002546 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002547 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002548 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002549
Mathias Agopianca4d3602011-05-19 15:38:14 -07002550 mLastTransactionTime = systemTime() - now;
2551 mDebugInTransaction = 0;
2552 invalidateHwcGeometry();
2553 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002554}
2555
Lloyd Piqueba04e622017-12-14 17:11:26 -08002556void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2557 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 const std::optional<DisplayIdentificationInfo> info =
2559 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560
Dominik Laskowski075d3172018-05-24 15:50:06 -07002561 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002562 continue;
2563 }
2564
Lloyd Piqueba04e622017-12-14 17:11:26 -08002565 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002566 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002567 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 mPhysicalDisplayTokens[info->id] = new BBinder();
2569 DisplayDeviceState state;
2570 state.displayId = info->id;
2571 state.isSecure = true; // All physical displays are currently considered secure.
2572 state.displayName = info->name;
2573 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2574 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002575 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002577 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002578
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2580 if (index >= 0) {
2581 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2582 mInterceptor->saveDisplayDeletion(state.sequenceId);
2583 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002584 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586 }
2587
2588 processDisplayChangesLocked();
2589 }
2590
2591 mPendingHotplugEvents.clear();
2592}
2593
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002594void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002595 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2596 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002597}
2598
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002600 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002601 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 const sp<IGraphicBufferProducer>& producer) {
2603 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002604 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.isSecure = state.isSecure;
2607 creationArgs.displaySurface = dispSurface;
2608 creationArgs.hasWideColorGamut = false;
2609 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002610
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002611 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612 creationArgs.isPrimary = isInternalDisplay;
2613
2614 if (useColorManagement && displayId) {
2615 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002617 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002618 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002620
Dominik Laskowski7e045462018-05-30 13:02:02 -07002621 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002623 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 }
tangrobin6753a022018-08-10 10:58:54 +08002625 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 if (displayId) {
2628 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002629 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002631 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632
Lloyd Pique90c115d2018-09-18 21:39:42 -07002633 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002635 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637 // Make sure that composition can never be stalled by a virtual display
2638 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002639 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002640 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2642 }
2643
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644 creationArgs.displayInstallOrientation =
2645 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002646
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002648 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649
Lloyd Pique90c115d2018-09-18 21:39:42 -07002650 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
2652 if (maxFrameBufferAcquiredBuffers >= 3) {
2653 nativeWindowSurface->preallocateBuffers();
2654 }
2655
2656 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002657 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002658 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002660 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002662 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2663 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 if (!state.isVirtual()) {
2665 LOG_ALWAYS_FATAL_IF(!displayId);
2666 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002667 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002668
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002669 display->setLayerStack(state.layerStack);
2670 display->setProjection(state.orientation, state.viewport, state.frame);
2671 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002673 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674}
2675
Lloyd Pique347200f2017-12-14 17:00:15 -08002676void SurfaceFlinger::processDisplayChangesLocked() {
2677 // here we take advantage of Vector's copy-on-write semantics to
2678 // improve performance by skipping the transaction entirely when
2679 // know that the lists are identical
2680 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2681 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2682 if (!curr.isIdenticalTo(draw)) {
2683 mVisibleRegionsDirty = true;
2684 const size_t cc = curr.size();
2685 size_t dc = draw.size();
2686
2687 // find the displays that were removed
2688 // (ie: in drawing state but not in current state)
2689 // also handle displays that changed
2690 // (ie: displays that are in both lists)
2691 for (size_t i = 0; i < dc;) {
2692 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2693 if (j < 0) {
2694 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002696 // Save display ID before disconnecting.
2697 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002698 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002699
2700 if (!display->isVirtual()) {
2701 LOG_ALWAYS_FATAL_IF(!displayId);
2702 dispatchDisplayHotplugEvent(displayId->value, false);
2703 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002705
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 } else {
2708 // this display is in both lists. see if something changed.
2709 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2712 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2713 if (state_binder != draw_binder) {
2714 // changing the surface is like destroying and
2715 // recreating the DisplayDevice, so we just remove it
2716 // from the drawing state, so that it get re-added
2717 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002718 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002719 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002720 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002721 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 mDrawingState.displays.removeItemsAt(i);
2723 dc--;
2724 // at this point we must loop to the next item
2725 continue;
2726 }
2727
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002730 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 }
2732 if ((state.orientation != draw[i].orientation) ||
2733 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 }
2739 }
2740 }
2741 ++i;
2742 }
2743
2744 // find displays that were added
2745 // (ie: in current state but not in drawing state)
2746 for (size_t i = 0; i < cc; i++) {
2747 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2748 const DisplayDeviceState& state(curr[i]);
2749
Lloyd Pique542307f2018-10-19 13:24:08 -07002750 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 sp<IGraphicBufferProducer> producer;
2752 sp<IGraphicBufferProducer> bqProducer;
2753 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002754 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002755
Dominik Laskowski075d3172018-05-24 15:50:06 -07002756 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002757 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 // Virtual displays without a surface are dormant:
2759 // they have external state (layer stack, projection,
2760 // etc.) but no internal state (i.e. a DisplayDevice).
2761 if (state.surface != nullptr) {
2762 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002763 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 int width = 0;
2765 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2766 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2767 int height = 0;
2768 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2769 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2770 int intFormat = 0;
2771 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2772 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002773 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 displayId =
2776 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 }
2778
2779 // TODO: Plumb requested format back up to consumer
2780
2781 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 bqProducer, bqConsumer,
2784 state.displayName);
2785
2786 dispSurface = vds;
2787 producer = vds;
2788 }
2789 } else {
2790 ALOGE_IF(state.surface != nullptr,
2791 "adding a supported display, but rendering "
2792 "surface is provided (%p), ignoring it",
2793 state.surface.get());
2794
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 displayId = state.displayId;
2796 LOG_ALWAYS_FATAL_IF(!displayId);
2797 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002798 producer = bqProducer;
2799 }
2800
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002801 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002802 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002803 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002804 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002805 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002806 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002807 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002808 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002809 }
2810 }
2811 }
2812 }
2813 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002814
2815 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002816}
2817
Mathias Agopian87baae12012-07-31 12:38:26 -07002818void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002819{
Dan Stoza7dde5992015-05-22 09:51:44 -07002820 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002821 mCurrentState.traverseInZOrder([](Layer* layer) {
2822 layer->notifyAvailableFrames();
2823 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002824
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 /*
2826 * Traversal of the children
2827 * (perform the transaction for each of them if needed)
2828 */
2829
Mathias Agopian3559b072012-08-15 13:46:03 -07002830 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002833 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834
2835 const uint32_t flags = layer->doTransaction(0);
2836 if (flags & Layer::eVisibleRegion)
2837 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002838
2839 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002840 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002841 }
Robert Carr2047fae2016-11-28 14:09:09 -08002842 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 }
2844
2845 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002846 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 */
2848
Mathias Agopiane57f2922012-08-09 16:29:12 -07002849 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002850 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002851 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002854 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002855 // The transform hint might have changed for some layers
2856 // (either because a display has changed, or because a layer
2857 // as changed).
2858 //
2859 // Walk through all the layers in currentLayers,
2860 // and update their transform hint.
2861 //
2862 // If a layer is visible only on a single display, then that
2863 // display is used to calculate the hint, otherwise we use the
2864 // default display.
2865 //
2866 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2867 // the hint is set before we acquire a buffer from the surface texture.
2868 //
2869 // NOTE: layer transactions have taken place already, so we use their
2870 // drawing state. However, SurfaceFlinger's own transaction has not
2871 // happened yet, so we must use the current state layer list
2872 // (soon to become the drawing state list).
2873 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002875 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002876 bool first = true;
2877 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002878 // NOTE: we rely on the fact that layers are sorted by
2879 // layerStack first (so we don't have to traverse the list
2880 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002882 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002883 currentlayerStack = layerStack;
2884 // figure out if this layerstack is mirrored
2885 // (more than one display) if so, pick the default display,
2886 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 hintDisplay = nullptr;
2888 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002889 if (display->getCompositionDisplay()
2890 ->belongsInOutput(layer->getLayerStack(),
2891 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002892 if (hintDisplay) {
2893 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002894 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002895 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002897 }
2898 }
2899 }
2900 }
Chet Haase91d25932013-04-11 15:24:55 -07002901
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002902 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002903 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2904 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002905
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002906 // could be null when this layer is using a layerStack
2907 // that is not visible on any display. Also can occur at
2908 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002909 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002910 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002911
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002913 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 if (hintDisplay) {
2915 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002916 }
Robert Carr2047fae2016-11-28 14:09:09 -08002917
2918 first = false;
2919 });
Mathias Agopian84300952012-11-21 16:02:13 -08002920 }
2921
2922
Mathias Agopian3559b072012-08-15 13:46:03 -07002923 /*
2924 * Perform our own transaction if needed
2925 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002926
2927 if (mLayersAdded) {
2928 mLayersAdded = false;
2929 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002930 mVisibleRegionsDirty = true;
2931 }
2932
2933 // some layers might have been removed, so
2934 // we need to update the regions they're exposing.
2935 if (mLayersRemoved) {
2936 mLayersRemoved = false;
2937 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002938 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002939 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002940 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002942 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002943 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002944 }
Robert Carr2047fae2016-11-28 14:09:09 -08002945 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 }
2947
Vishnu Nairec0ab382019-02-13 15:32:56 -08002948 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002950}
2951
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002952void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002953 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002954 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002955 return;
2956 }
2957
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002958 if (mVisibleRegionsDirty || mInputInfoChanged) {
2959 mInputInfoChanged = false;
2960 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002961 } else if (mInputWindowCommands.syncInputWindows) {
2962 // If the caller requested to sync input windows, but there are no
2963 // changes to input windows, notify immediately.
2964 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002965 }
2966
2967 executeInputWindowCommands();
2968}
2969
2970void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002971 Vector<InputWindowInfo> inputHandles;
2972
2973 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2974 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002975 // When calculating the screen bounds we ignore the transparent region since it may
2976 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002977 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002978 }
2979 });
chaviw291d88a2019-02-14 10:33:58 -08002980
2981 mInputFlinger->setInputWindows(inputHandles,
2982 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2983 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002984}
2985
Vishnu Nairec0ab382019-02-13 15:32:56 -08002986void SurfaceFlinger::commitInputWindowCommands() {
2987 mInputWindowCommands.merge(mPendingInputWindowCommands);
2988 mPendingInputWindowCommands.clear();
2989}
2990
chaviwfbe5d9c2018-12-26 12:23:37 -08002991void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002992 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2993 if (transferTouchFocusCommand.fromToken != nullptr &&
2994 transferTouchFocusCommand.toToken != nullptr &&
2995 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2996 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2997 transferTouchFocusCommand.toToken);
2998 }
2999 }
3000
3001 mInputWindowCommands.clear();
3002}
3003
Riley Andrews03414a12014-07-01 14:22:59 -07003004void SurfaceFlinger::updateCursorAsync()
3005{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003006 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003007 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003008 continue;
3009 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003010
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003011 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3012 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003013 }
3014 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015}
3016
chaviw61626f22018-11-15 16:26:27 -08003017void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3018 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003019 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003020 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003021 }
3022 layer->releasePendingBuffer(systemTime());
3023}
3024
Mathias Agopian4fec8732012-06-29 14:12:52 -07003025void SurfaceFlinger::commitTransaction()
3026{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003027 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003029 for (const auto& l : mLayersPendingRemoval) {
3030 recordBufferingStats(l->getName().string(),
3031 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003032
Lloyd Pique07e33212018-12-18 16:33:37 -08003033 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003034 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003035 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003036 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003037 }
3038 mLayersPendingRemoval.clear();
3039 }
3040
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003041 // If this transaction is part of a window animation then the next frame
3042 // we composite should be considered an animation as well.
3043 mAnimCompositionPending = mAnimTransactionPending;
3044
Mathias Agopian4fec8732012-06-29 14:12:52 -07003045 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003046 // clear the "changed" flags in current state
3047 mCurrentState.colorMatrixChanged = false;
3048
Robert Carr1f0a16a2016-10-24 16:27:39 -07003049 mDrawingState.traverseInZOrder([](Layer* layer) {
3050 layer->commitChildList();
3051 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003052 mTransactionPending = false;
3053 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055}
3056
Lloyd Pique32cbe282018-10-19 13:09:22 -07003057void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003058 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003059 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003060 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003061
Lloyd Pique32cbe282018-10-19 13:09:22 -07003062 auto display = displayDevice->getCompositionDisplay();
3063
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064 Region aboveOpaqueLayers;
3065 Region aboveCoveredLayers;
3066 Region dirty;
3067
Mathias Agopian87baae12012-07-31 12:38:26 -07003068 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069
Robert Carr2047fae2016-11-28 14:09:09 -08003070 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003071 // start with the whole surface at its current location
3072 const Layer::State& s(layer->getDrawingState());
3073
Jesse Hall01e29052013-02-19 16:13:35 -08003074 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003075 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003076 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003077 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003078
Mathias Agopianab028732010-03-16 16:41:46 -07003079 /*
3080 * opaqueRegion: area of a surface that is fully opaque.
3081 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003083
3084 /*
3085 * visibleRegion: area of a surface that is visible on screen
3086 * and not fully transparent. This is essentially the layer's
3087 * footprint minus the opaque regions above it.
3088 * Areas covered by a translucent surface are considered visible.
3089 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003091
3092 /*
3093 * coveredRegion: area of a surface that is covered by all
3094 * visible regions above it (which includes the translucent areas).
3095 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003097
Jesse Halla8026d22012-09-25 13:25:04 -07003098 /*
3099 * transparentRegion: area of a surface that is hinted to be completely
3100 * transparent. This is only used to tell when the layer has no visible
3101 * non-transparent regions and can be removed from the layer list. It
3102 * does not affect the visibleRegion of this layer or any layers
3103 * beneath it. The hint may not be correct if apps don't respect the
3104 * SurfaceView restrictions (which, sadly, some don't).
3105 */
3106 Region transparentRegion;
3107
Mathias Agopianab028732010-03-16 16:41:46 -07003108
3109 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003110 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003111 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003112 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003113
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003115 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003116 if (!visibleRegion.isEmpty()) {
3117 // Remove the transparent area from the visible region
3118 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003119 if (tr.preserveRects()) {
3120 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003121 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003122 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003123 // transformation too complex, can't do the
3124 // transparent region optimization.
3125 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003126 }
Mathias Agopianab028732010-03-16 16:41:46 -07003127 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128
Mathias Agopianab028732010-03-16 16:41:46 -07003129 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003131 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003132 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003133 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003134 // the opaque region is the layer's footprint
3135 opaqueRegion = visibleRegion;
3136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137 }
3138 }
3139
Robert Carre5f4f692018-01-12 13:12:28 -08003140 if (visibleRegion.isEmpty()) {
3141 layer->clearVisibilityRegions();
3142 return;
3143 }
3144
Mathias Agopianab028732010-03-16 16:41:46 -07003145 // Clip the covered region to the visible region
3146 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3147
3148 // Update aboveCoveredLayers for next (lower) layer
3149 aboveCoveredLayers.orSelf(visibleRegion);
3150
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 // subtract the opaque region covered by the layers above us
3152 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153
3154 // compute this layer's dirty region
3155 if (layer->contentDirty) {
3156 // we need to invalidate the whole region
3157 dirty = visibleRegion;
3158 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003159 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 layer->contentDirty = false;
3161 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003162 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003163 * the exposed region consists of two components:
3164 * 1) what's VISIBLE now and was COVERED before
3165 * 2) what's EXPOSED now less what was EXPOSED before
3166 *
3167 * note that (1) is conservative, we start with the whole
3168 * visible region but only keep what used to be covered by
3169 * something -- which mean it may have been exposed.
3170 *
3171 * (2) handles areas that were not covered by anything but got
3172 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003173 */
Mathias Agopianab028732010-03-16 16:41:46 -07003174 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003175 const Region oldVisibleRegion = layer->visibleRegion;
3176 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003177 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3178 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
3180 dirty.subtractSelf(aboveOpaqueLayers);
3181
3182 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003183 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184
Mathias Agopianab028732010-03-16 16:41:46 -07003185 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003187
Jesse Halla8026d22012-09-25 13:25:04 -07003188 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189 layer->setVisibleRegion(visibleRegion);
3190 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003191 layer->setVisibleNonTransparentRegion(
3192 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003193 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194
Mathias Agopian87baae12012-07-31 12:38:26 -07003195 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196}
3197
Chia-I Wuab0c3192017-08-01 11:29:00 -07003198void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003199 for (const auto& [token, displayDevice] : mDisplays) {
3200 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003201 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003202 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003203 }
3204 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003205}
3206
Daniel Solomon42d04562019-01-20 21:03:19 -08003207void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3208 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3209 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3210 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3211 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3212 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3213 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3214 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3215 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3216 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3217 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3218 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3219 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3220}
3221
Dan Stoza6b9454d2014-11-07 16:00:59 -08003222bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003224 ALOGV("handlePageFlip");
3225
Brian Andersond6927fb2016-07-23 23:37:30 -07003226 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227
Mathias Agopian4fec8732012-06-29 14:12:52 -07003228 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003229 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003230 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003231
3232 // Store the set of layers that need updates. This set must not change as
3233 // buffers are being latched, as this could result in a deadlock.
3234 // Example: Two producers share the same command stream and:
3235 // 1.) Layer 0 is latched
3236 // 2.) Layer 0 gets a new frame
3237 // 2.) Layer 1 gets a new frame
3238 // 3.) Layer 1 is latched.
3239 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3240 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003241 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003242 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003243 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003244 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003245 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003246 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003247 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003248 } else {
3249 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003250 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003251 } else {
3252 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003253 }
Robert Carr2047fae2016-11-28 14:09:09 -08003254 });
3255
Lloyd Piquef2c79392018-12-20 16:23:33 -08003256 if (!mLayersWithQueuedFrames.empty()) {
3257 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3258 // writes to Layer current state. See also b/119481871
3259 Mutex::Autolock lock(mStateLock);
3260
3261 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003262 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003263 mLayersPendingRefresh.push_back(layer);
3264 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003265 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003266 if (layer->isBufferLatched()) {
3267 newDataLatched = true;
3268 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003269 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003270 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003271
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003272 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003273
3274 // If we will need to wake up at some time in the future to deal with a
3275 // queued frame that shouldn't be displayed during this vsync period, wake
3276 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003277 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003278 signalLayerUpdate();
3279 }
3280
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003281 // enter boot animation on first buffer latch
3282 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3283 ALOGI("Enter boot animation");
3284 mBootStage = BootStage::BOOTANIMATION;
3285 }
3286
Dan Stoza6b9454d2014-11-07 16:00:59 -08003287 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003288 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289}
3290
Mathias Agopianad456f92011-01-13 17:53:01 -08003291void SurfaceFlinger::invalidateHwcGeometry()
3292{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003293 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003294}
3295
Lloyd Pique32cbe282018-10-19 13:09:22 -07003296void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003297 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003298 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003299 // We only need to actually compose the display if:
3300 // 1) It is being handled by hardware composer, which may need this to
3301 // keep its virtual display state machine in sync, or
3302 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003303 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003305 return;
3306 }
3307
Dan Stoza9e56aa02015-11-02 13:00:03 -08003308 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003309 base::unique_fd readyFence;
3310 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003311
3312 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003313 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314}
3315
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003316bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3317 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003318 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003319 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003320
Lloyd Pique32cbe282018-10-19 13:09:22 -07003321 auto display = displayDevice->getCompositionDisplay();
3322 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003323 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003324
3325 const Region bounds(displayState.bounds);
3326 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003327 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003328 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003329
Peiyong Lind3788632018-09-18 16:01:31 -07003330 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003331 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003332
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003333 renderengine::DisplaySettings clientCompositionDisplay;
3334 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3335 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003336 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003337
Dan Stoza9e56aa02015-11-02 13:00:03 -08003338 if (hasClientComposition) {
3339 ALOGV("hasClientComposition");
3340
Alec Mouri6338c9d2019-02-07 16:57:51 -08003341 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003342 if (buf == nullptr) {
3343 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3344 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003345 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003346 return false;
3347 }
3348
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003349 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3350 clientCompositionDisplay.clip = displayState.scissor;
3351 const ui::Transform& displayTransform = displayState.transform;
3352 mat4 m;
3353 m[0][0] = displayTransform[0][0];
3354 m[0][1] = displayTransform[0][1];
3355 m[0][3] = displayTransform[0][2];
3356 m[1][0] = displayTransform[1][0];
3357 m[1][1] = displayTransform[1][1];
3358 m[1][3] = displayTransform[1][2];
3359 m[3][0] = displayTransform[2][0];
3360 m[3][1] = displayTransform[2][1];
3361 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003362 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003363
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003364 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003365 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003366 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003367 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003368 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003369 clientCompositionDisplay.outputDataspace = outputDataspace;
3370 clientCompositionDisplay.maxLuminance =
3371 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003372
Lloyd Pique441d5042018-10-18 16:49:51 -07003373 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003374 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003375 getHwComposer()
3376 .hasDisplayCapability(displayId,
3377 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003378
Peiyong Lind3788632018-09-18 16:01:31 -07003379 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003380 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3381 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003382 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003383 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003384 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003385
Mathias Agopian85d751c2012-08-29 16:59:24 -07003386 /*
3387 * and then, render the layers targeted at the framebuffer
3388 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003389
Dan Stoza9e56aa02015-11-02 13:00:03 -08003390 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003391 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003392 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003393 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003394 const Region viewportRegion(displayState.viewport);
3395 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003396 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003397 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003398 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003399 switch (layer->getCompositionType(displayDevice)) {
3400 case Hwc2::IComposerClient::Composition::CURSOR:
3401 case Hwc2::IComposerClient::Composition::DEVICE:
3402 case Hwc2::IComposerClient::Composition::SIDEBAND:
3403 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003404 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003405 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003406 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003407 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003408 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 // never clear the very first layer since we're
3410 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003411 renderengine::LayerSettings layerSettings;
3412 Region dummyRegion;
3413 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3414 layerSettings);
3415
3416 if (prepared) {
3417 layerSettings.source.buffer.buffer = nullptr;
3418 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3419 layerSettings.alpha = half(0.0);
3420 layerSettings.disableBlending = true;
3421 clientCompositionLayers.push_back(layerSettings);
3422 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003423 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003424 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003425 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003426 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003427 renderengine::LayerSettings layerSettings;
3428 bool prepared =
3429 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3430 if (prepared) {
3431 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003432 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 break;
3434 }
3435 default:
3436 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003437 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003438 } else {
3439 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003440 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003441 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003442 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003443
Alec Mouri820c7402019-01-23 13:02:39 -08003444 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003445 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003446 clientCompositionDisplay.clearRegion = clearRegion;
3447 if (!debugRegion.isEmpty()) {
3448 Region::const_iterator it = debugRegion.begin();
3449 Region::const_iterator end = debugRegion.end();
3450 while (it != end) {
3451 const Rect& rect = *it++;
3452 renderengine::LayerSettings layerSettings;
3453 layerSettings.source.buffer.buffer = nullptr;
3454 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3455 layerSettings.geometry.boundaries = rect.toFloatRect();
3456 layerSettings.alpha = half(1.0);
3457 clientCompositionLayers.push_back(layerSettings);
3458 }
3459 }
3460 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mouri6338c9d2019-02-07 16:57:51 -08003461 buf->getNativeBuffer(), std::move(fd), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003462 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003463 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464}
3465
Chia-I Wu28e3a252018-09-07 12:05:02 -07003466void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003467 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003468 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469}
3470
Dan Stoza7d89d062015-04-30 13:29:25 -07003471status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003472 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003473 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003474 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003475 const sp<Layer>& parent,
3476 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003477{
Dan Stoza7d89d062015-04-30 13:29:25 -07003478 // add this layer to the current state list
3479 {
3480 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003481 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003482 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3483 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003484 return NO_MEMORY;
3485 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003486 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003487 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003488 } else if (parent == nullptr) {
3489 lbc->onRemovedFromCurrentState();
3490 } else if (parent->isRemovedFromCurrentState()) {
3491 parent->addChild(lbc);
3492 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003493 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003494 parent->addChild(lbc);
3495 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003496
Yiwei Zhang243b3782018-05-15 17:40:04 -07003497 if (gbc != nullptr) {
3498 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3499 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3500 mMaxGraphicBufferProducerListSize,
3501 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3502 mGraphicBufferProducerList.size(),
3503 mMaxGraphicBufferProducerListSize, mNumLayers);
3504 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003505 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003506 }
3507
Mathias Agopian96f08192010-06-02 23:28:45 -07003508 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003509 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003510
Dan Stoza7d89d062015-04-30 13:29:25 -07003511 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003512}
3513
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003514uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003515 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003516}
3517
Mathias Agopian3f844832013-08-07 21:24:32 -07003518uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003519 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520}
3521
Mathias Agopian3f844832013-08-07 21:24:32 -07003522uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003523 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003524}
3525
3526uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003527 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003528 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003529 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003531 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 }
3533 return old;
3534}
3535
Marissa Wall713b63f2018-10-17 15:42:43 -07003536bool SurfaceFlinger::flushTransactionQueues() {
3537 Mutex::Autolock _l(mStateLock);
3538 auto it = mTransactionQueues.begin();
3539 while (it != mTransactionQueues.end()) {
3540 auto& [applyToken, transactionQueue] = *it;
3541
3542 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003543 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3544 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003545 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003546 break;
3547 }
Robert Carr14167e02019-02-13 13:50:55 -08003548 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003549 transactionQueue.pop();
3550 }
3551
3552 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3553 }
3554 return mTransactionQueues.empty();
3555}
3556
chaviwca27f252018-02-06 16:46:39 -08003557bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3558 for (const ComposerState& state : states) {
3559 // Here we need to check that the interface we're given is indeed
3560 // one of our own. A malicious client could give us a nullptr
3561 // IInterface, or one of its own or even one of our own but a
3562 // different type. All these situations would cause us to crash.
3563 if (state.client == nullptr) {
3564 return true;
3565 }
3566
3567 sp<IBinder> binder = IInterface::asBinder(state.client);
3568 if (binder == nullptr) {
3569 return true;
3570 }
3571
3572 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3573 return true;
3574 }
3575 }
3576 return false;
3577}
3578
Marissa Wall17b4e452018-12-26 16:32:34 -08003579bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3580 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003581 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003582 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3583 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3584 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3585 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3586 return false;
3587 }
3588
Marissa Wall713b63f2018-10-17 15:42:43 -07003589 for (const ComposerState& state : states) {
3590 const layer_state_t& s = state.state;
3591 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3592 continue;
3593 }
3594 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003595 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003596 }
3597 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003598 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003599}
3600
3601void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3602 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003603 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003604 const InputWindowCommands& inputWindowCommands,
3605 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003606 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003607
3608 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3609
Mathias Agopian698c0872011-06-28 19:09:31 -07003610 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003611
chaviwca27f252018-02-06 16:46:39 -08003612 if (containsAnyInvalidClientState(states)) {
3613 return;
3614 }
3615
Marissa Wall713b63f2018-10-17 15:42:43 -07003616 // If its TransactionQueue already has a pending TransactionState or if it is pending
3617 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003618 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003619 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3620 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003621 setTransactionFlags(eTransactionNeeded);
3622 return;
3623 }
3624
Robert Carr14167e02019-02-13 13:50:55 -08003625 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003626}
3627
3628void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003629 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003630 const InputWindowCommands& inputWindowCommands,
3631 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003632 uint32_t transactionFlags = 0;
3633
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003634 if (flags & eAnimation) {
3635 // For window updates that are part of an animation we must wait for
3636 // previous animation "frames" to be handled.
3637 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003638 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003639 if (CC_UNLIKELY(err != NO_ERROR)) {
3640 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003641 // caller after a few seconds.
3642 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3643 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003644 mAnimTransactionPending = false;
3645 break;
3646 }
3647 }
3648 }
3649
chaviwca27f252018-02-06 16:46:39 -08003650 for (const DisplayState& display : displays) {
3651 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003652 }
3653
Marissa Walle2ffb422018-10-12 11:33:52 -07003654 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003655 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003656 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003657 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003658 // If the state doesn't require a traversal and there are callbacks, send them now
3659 if (!(clientStateFlags & eTraversalNeeded)) {
3660 mTransactionCompletedThread.sendCallbacks();
3661 }
3662 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003663
chaviw273171b2018-12-26 11:46:30 -08003664 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3665
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003666 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3667 // anyway. This can be used as a flush mechanism for previous async transactions.
3668 // Empty animation transaction can be used to simulate back-pressure, so also force a
3669 // transaction for empty animation transactions.
3670 if (transactionFlags == 0 &&
3671 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003672 transactionFlags = eTransactionNeeded;
3673 }
3674
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003676 if (mInterceptor->isEnabled()) {
3677 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003678 }
Irvel468051e2016-06-13 16:44:44 -07003679
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003681 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3682 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003683 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003684
3685 // if this is a synchronous transaction, wait for it to take effect
3686 // before returning.
3687 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003688 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003689 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003690 if (flags & eAnimation) {
3691 mAnimTransactionPending = true;
3692 }
chaviw95ef3c42019-02-14 10:55:09 -08003693
3694 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3695 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003696 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3697 if (CC_UNLIKELY(err != NO_ERROR)) {
3698 // just in case something goes wrong in SF, return to the
3699 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003700 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3701 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003702 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003703 break;
3704 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003705 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003706 }
3707}
3708
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003709uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3710 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3711 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003712
Mathias Agopiane57f2922012-08-09 16:29:12 -07003713 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003714 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3715
3716 const uint32_t what = s.what;
3717 if (what & DisplayState::eSurfaceChanged) {
3718 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3719 state.surface = s.surface;
3720 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003721 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003722 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003723 if (what & DisplayState::eLayerStackChanged) {
3724 if (state.layerStack != s.layerStack) {
3725 state.layerStack = s.layerStack;
3726 flags |= eDisplayTransactionNeeded;
3727 }
3728 }
3729 if (what & DisplayState::eDisplayProjectionChanged) {
3730 if (state.orientation != s.orientation) {
3731 state.orientation = s.orientation;
3732 flags |= eDisplayTransactionNeeded;
3733 }
3734 if (state.frame != s.frame) {
3735 state.frame = s.frame;
3736 flags |= eDisplayTransactionNeeded;
3737 }
3738 if (state.viewport != s.viewport) {
3739 state.viewport = s.viewport;
3740 flags |= eDisplayTransactionNeeded;
3741 }
3742 }
3743 if (what & DisplayState::eDisplaySizeChanged) {
3744 if (state.width != s.width) {
3745 state.width = s.width;
3746 flags |= eDisplayTransactionNeeded;
3747 }
3748 if (state.height != s.height) {
3749 state.height = s.height;
3750 flags |= eDisplayTransactionNeeded;
3751 }
3752 }
3753
Mathias Agopiane57f2922012-08-09 16:29:12 -07003754 return flags;
3755}
3756
Robert Carr14167e02019-02-13 13:50:55 -08003757bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003758 IPCThreadState* ipc = IPCThreadState::self();
3759 const int pid = ipc->getCallingPid();
3760 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003761 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003762 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003763 return false;
3764 }
3765 return true;
3766}
3767
Robert Carr14167e02019-02-13 13:50:55 -08003768uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3769 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003770 const layer_state_t& s = composerState.state;
3771 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3772
Mathias Agopian13127d82013-03-05 17:47:11 -08003773 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003774 if (layer == nullptr) {
3775 return 0;
3776 }
3777
chaviw8b3871a2017-11-01 17:41:01 -07003778 uint32_t flags = 0;
3779
Garfield Tan8a3083e2018-12-03 13:21:07 -08003780 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003781 bool geometryAppliesWithResize =
3782 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003783
3784 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3785 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003786 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003787 layer->pushPendingState();
3788 }
3789
chaviw8b3871a2017-11-01 17:41:01 -07003790 if (what & layer_state_t::ePositionChanged) {
3791 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3792 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003793 }
chaviw8b3871a2017-11-01 17:41:01 -07003794 }
3795 if (what & layer_state_t::eLayerChanged) {
3796 // NOTE: index needs to be calculated before we update the state
3797 const auto& p = layer->getParent();
3798 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003799 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003800 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003801 mCurrentState.layersSortedByZ.removeAt(idx);
3802 mCurrentState.layersSortedByZ.add(layer);
3803 // we need traversal (state changed)
3804 // AND transaction (list changed)
3805 flags |= eTransactionNeeded|eTraversalNeeded;
3806 }
chaviw8b3871a2017-11-01 17:41:01 -07003807 } else {
3808 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003809 flags |= eTransactionNeeded|eTraversalNeeded;
3810 }
3811 }
chaviw8b3871a2017-11-01 17:41:01 -07003812 }
3813 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003814 // NOTE: index needs to be calculated before we update the state
3815 const auto& p = layer->getParent();
3816 if (p == nullptr) {
3817 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3818 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3819 mCurrentState.layersSortedByZ.removeAt(idx);
3820 mCurrentState.layersSortedByZ.add(layer);
3821 // we need traversal (state changed)
3822 // AND transaction (list changed)
3823 flags |= eTransactionNeeded|eTraversalNeeded;
3824 }
3825 } else {
3826 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3827 flags |= eTransactionNeeded|eTraversalNeeded;
3828 }
chaviw8b3871a2017-11-01 17:41:01 -07003829 }
3830 }
3831 if (what & layer_state_t::eSizeChanged) {
3832 if (layer->setSize(s.w, s.h)) {
3833 flags |= eTraversalNeeded;
3834 }
3835 }
3836 if (what & layer_state_t::eAlphaChanged) {
3837 if (layer->setAlpha(s.alpha))
3838 flags |= eTraversalNeeded;
3839 }
3840 if (what & layer_state_t::eColorChanged) {
3841 if (layer->setColor(s.color))
3842 flags |= eTraversalNeeded;
3843 }
Peiyong Lind3788632018-09-18 16:01:31 -07003844 if (what & layer_state_t::eColorTransformChanged) {
3845 if (layer->setColorTransform(s.colorTransform)) {
3846 flags |= eTraversalNeeded;
3847 }
3848 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003849 if (what & layer_state_t::eBackgroundColorChanged) {
3850 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3851 flags |= eTraversalNeeded;
3852 }
3853 }
chaviw8b3871a2017-11-01 17:41:01 -07003854 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003855 // TODO: b/109894387
3856 //
3857 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3858 // rotation. To see the problem observe that if we have a square parent, and a child
3859 // of the same size, then we rotate the child 45 degrees around it's center, the child
3860 // must now be cropped to a non rectangular 8 sided region.
3861 //
3862 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3863 // private API, and the WindowManager only uses rotation in one case, which is on a top
3864 // level layer in which cropping is not an issue.
3865 //
3866 // However given that abuse of rotation matrices could lead to surfaces extending outside
3867 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3868 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3869 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003870 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003871 flags |= eTraversalNeeded;
3872 }
3873 if (what & layer_state_t::eTransparentRegionChanged) {
3874 if (layer->setTransparentRegionHint(s.transparentRegion))
3875 flags |= eTraversalNeeded;
3876 }
3877 if (what & layer_state_t::eFlagsChanged) {
3878 if (layer->setFlags(s.flags, s.mask))
3879 flags |= eTraversalNeeded;
3880 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003881 if (what & layer_state_t::eCropChanged_legacy) {
3882 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003883 flags |= eTraversalNeeded;
3884 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003885 if (what & layer_state_t::eCornerRadiusChanged) {
3886 if (layer->setCornerRadius(s.cornerRadius))
3887 flags |= eTraversalNeeded;
3888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 if (what & layer_state_t::eLayerStackChanged) {
3890 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3891 // We only allow setting layer stacks for top level layers,
3892 // everything else inherits layer stack from its parent.
3893 if (layer->hasParent()) {
3894 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3895 layer->getName().string());
3896 } else if (idx < 0) {
3897 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3898 "that also does not appear in the top level layer list. Something"
3899 " has gone wrong.", layer->getName().string());
3900 } else if (layer->setLayerStack(s.layerStack)) {
3901 mCurrentState.layersSortedByZ.removeAt(idx);
3902 mCurrentState.layersSortedByZ.add(layer);
3903 // we need traversal (state changed)
3904 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003905 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003906 }
3907 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003908 if (what & layer_state_t::eDeferTransaction_legacy) {
3909 if (s.barrierHandle_legacy != nullptr) {
3910 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3911 } else if (s.barrierGbp_legacy != nullptr) {
3912 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003913 if (authenticateSurfaceTextureLocked(gbp)) {
3914 const auto& otherLayer =
3915 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003916 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003917 } else {
3918 ALOGE("Attempt to defer transaction to to an"
3919 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003920 }
3921 }
chaviw8b3871a2017-11-01 17:41:01 -07003922 // We don't trigger a traversal here because if no other state is
3923 // changed, we don't want this to cause any more work
3924 }
3925 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003926 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003927 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003928 if (!hadParent) {
3929 mCurrentState.layersSortedByZ.remove(layer);
3930 }
chaviw8b3871a2017-11-01 17:41:01 -07003931 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003932 }
chaviw8b3871a2017-11-01 17:41:01 -07003933 }
3934 if (what & layer_state_t::eReparentChildren) {
3935 if (layer->reparentChildren(s.reparentHandle)) {
3936 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003937 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003938 }
chaviw8b3871a2017-11-01 17:41:01 -07003939 if (what & layer_state_t::eDetachChildren) {
3940 layer->detachChildren();
3941 }
3942 if (what & layer_state_t::eOverrideScalingModeChanged) {
3943 layer->setOverrideScalingMode(s.overrideScalingMode);
3944 // We don't trigger a traversal here because if no other state is
3945 // changed, we don't want this to cause any more work
3946 }
Marissa Wall61c58622018-07-18 10:12:20 -07003947 if (what & layer_state_t::eTransformChanged) {
3948 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3949 }
3950 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3951 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3952 flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eCropChanged) {
3955 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3956 }
Marissa Wall861616d2018-10-22 12:52:23 -07003957 if (what & layer_state_t::eFrameChanged) {
3958 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3959 }
Marissa Wall61c58622018-07-18 10:12:20 -07003960 if (what & layer_state_t::eAcquireFenceChanged) {
3961 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3962 }
3963 if (what & layer_state_t::eDataspaceChanged) {
3964 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3965 }
3966 if (what & layer_state_t::eHdrMetadataChanged) {
3967 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3968 }
3969 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3970 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3971 }
3972 if (what & layer_state_t::eApiChanged) {
3973 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3974 }
3975 if (what & layer_state_t::eSidebandStreamChanged) {
3976 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3977 }
Robert Carr720e5062018-07-30 17:45:14 -07003978 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003979 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3980 layer->setInputInfo(s.inputInfo);
3981 flags |= eTraversalNeeded;
3982 } else {
3983 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3984 }
Robert Carr720e5062018-07-30 17:45:14 -07003985 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003986 if (what & layer_state_t::eMetadataChanged) {
3987 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3988 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003989 std::vector<sp<CallbackHandle>> callbackHandles;
3990 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3991 mTransactionCompletedThread.run();
3992 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3993 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3994 }
3995 }
Marissa Wall73411622019-01-25 10:45:41 -08003996
3997 if (what & layer_state_t::eBufferChanged) {
3998 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3999 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4000 s.buffer);
4001 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004002 if (what & layer_state_t::eCachedBufferChanged) {
4003 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004004 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4005 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004006 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4007 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004008 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4009 // Do not put anything that updates layer state or modifies flags after
4010 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004011 return flags;
4012}
4013
chaviw273171b2018-12-26 11:46:30 -08004014uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4015 uint32_t flags = 0;
4016 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4017 flags |= eTraversalNeeded;
4018 }
4019
chaviwa911b102019-02-14 10:18:33 -08004020 if (inputWindowCommands.syncInputWindows) {
4021 flags |= eTraversalNeeded;
4022 }
4023
Vishnu Nairec0ab382019-02-13 15:32:56 -08004024 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004025 return flags;
4026}
4027
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004028status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4029 uint32_t h, PixelFormat format, uint32_t flags,
4030 LayerMetadata metadata, sp<IBinder>* handle,
4031 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004032 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004033 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004034 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004036 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004037
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004038 status_t result = NO_ERROR;
4039
4040 sp<Layer> layer;
4041
Cody Northropbc755282017-03-31 12:00:08 -06004042 String8 uniqueName = getUniqueLayerName(name);
4043
Mathias Agopian3165cc22012-08-08 19:42:09 -07004044 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004045 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004046 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4047 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004050 case ISurfaceComposerClient::eFXSurfaceBufferState:
4051 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4052 break;
chaviw13fdc492017-06-27 12:40:18 -07004053 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004054 // check if buffer size is set for color layer.
4055 if (w > 0 || h > 0) {
4056 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4057 int(w), int(h));
4058 return BAD_VALUE;
4059 }
4060
chaviw13fdc492017-06-27 12:40:18 -07004061 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004062 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004063 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004064 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004065 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004066 // check if buffer size is set for container layer.
4067 if (w > 0 || h > 0) {
4068 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4069 int(w), int(h));
4070 return BAD_VALUE;
4071 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004072 result = createContainerLayer(client,
4073 uniqueName, w, h, flags,
4074 handle, &layer);
4075 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 default:
4077 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 break;
4079 }
4080
Dan Stoza7d89d062015-04-30 13:29:25 -07004081 if (result != NO_ERROR) {
4082 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004083 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004084
Chia-I Wuab0c3192017-08-01 11:29:00 -07004085 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4086 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004087 if (metadata.has(METADATA_WINDOW_TYPE)) {
4088 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4089 if (windowType == 441731) {
4090 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4091 layer->setPrimaryDisplayOnly();
4092 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004093 }
4094
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004095 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004096
Robert Carrb89ea9d2018-12-10 13:01:14 -08004097 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4098 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4099 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004100 if (result != NO_ERROR) {
4101 return result;
4102 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004103 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004104
4105 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107}
4108
Cody Northropbc755282017-03-31 12:00:08 -06004109String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4110{
4111 bool matchFound = true;
4112 uint32_t dupeCounter = 0;
4113
4114 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4115 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4116
Dan Stoza436ccf32018-06-21 12:10:12 -07004117 // Grab the state lock since we're accessing mCurrentState
4118 Mutex::Autolock lock(mStateLock);
4119
Cody Northropbc755282017-03-31 12:00:08 -06004120 // Loop over layers until we're sure there is no matching name
4121 while (matchFound) {
4122 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004123 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004124 if (layer->getName() == uniqueName) {
4125 matchFound = true;
4126 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4127 }
4128 });
4129 }
4130
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004131 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4132 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004133
4134 return uniqueName;
4135}
4136
Marissa Wallfd668622018-05-10 10:21:13 -07004137status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4138 uint32_t w, uint32_t h, uint32_t flags,
4139 PixelFormat& format, sp<IBinder>* handle,
4140 sp<IGraphicBufferProducer>* gbp,
4141 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004143 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004144 case PIXEL_FORMAT_TRANSPARENT:
4145 case PIXEL_FORMAT_TRANSLUCENT:
4146 format = PIXEL_FORMAT_RGBA_8888;
4147 break;
4148 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004149 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150 break;
4151 }
4152
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004153 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004154 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004155 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004156 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004157 *handle = layer->getHandle();
4158 *gbp = layer->getProducer();
4159 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004161
Marissa Wallfd668622018-05-10 10:21:13 -07004162 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004163 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004164}
4165
Marissa Wall61c58622018-07-18 10:12:20 -07004166status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4167 uint32_t w, uint32_t h, uint32_t flags,
4168 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004169 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004170 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004171 *handle = layer->getHandle();
4172 *outLayer = layer;
4173
4174 return NO_ERROR;
4175}
4176
chaviw13fdc492017-06-27 12:40:18 -07004177status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004178 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004179 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004180{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004181 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004182 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004183 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004184}
4185
Robert Carr6b3f6c52018-08-13 13:05:17 -07004186status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4187 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4188 sp<IBinder>* handle, sp<Layer>* outLayer)
4189{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004190 *outLayer =
4191 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004192 *handle = (*outLayer)->getHandle();
4193 return NO_ERROR;
4194}
4195
4196
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004197void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004198 mLayersPendingRemoval.add(layer);
4199 mLayersRemoved = true;
4200 setTransactionFlags(eTransactionNeeded);
4201}
4202
Robert Carr695d5282018-12-18 15:27:58 -08004203void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004204{
Robert Carr2e102c92018-10-23 12:11:15 -07004205 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004206 // If a layer has a parent, we allow it to out-live it's handle
4207 // with the idea that the parent holds a reference and will eventually
4208 // be cleaned up. However no one cleans up the top-level so we do so
4209 // here.
4210 if (layer->getParent() == nullptr) {
4211 mCurrentState.layersSortedByZ.remove(layer);
4212 }
4213 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004214 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004215}
4216
Mathias Agopianb60314a2012-04-10 22:09:54 -07004217// ---------------------------------------------------------------------------
4218
Andy McFadden13a082e2012-08-24 10:16:42 -07004219void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 const auto display = getDefaultDisplayDeviceLocked();
4221 if (!display) return;
4222
4223 const sp<IBinder> token = display->getDisplayToken().promote();
4224 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004225
Jesse Hall01e29052013-02-19 16:13:35 -08004226 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004227 Vector<ComposerState> state;
4228 Vector<DisplayState> displays;
4229 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004230 d.what = DisplayState::eDisplayProjectionChanged |
4231 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004232 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004233 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004234 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004235 d.frame.makeInvalid();
4236 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004237 d.width = 0;
4238 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004239 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004240 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004241
Dominik Laskowskie9774092018-12-11 10:04:24 -08004242 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004243
Dominik Laskowski83b88212018-12-11 13:34:06 -08004244 const nsecs_t vsyncPeriod = getVsyncPeriod();
4245 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004246
Brian Andersond0010582017-03-07 13:20:31 -08004247 // Use phase of 0 since phase is not known.
4248 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004249 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004250 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004251}
4252
4253void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004254 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 postMessageAsync(
4256 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004257}
4258
Dominik Laskowskie9774092018-12-11 10:04:24 -08004259void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 if (display->isVirtual()) {
4261 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004262 return;
4263 }
4264
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 const auto displayId = display->getId();
4266 LOG_ALWAYS_FATAL_IF(!displayId);
4267
Dominik Laskowski34157762018-10-31 13:07:19 -07004268 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004269
4270 int currentMode = display->getPowerMode();
4271 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004272 return;
4273 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275 display->setPowerMode(mode);
4276
Lloyd Pique4dccc412018-01-22 17:21:36 -08004277 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004278 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004279 }
4280
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004281 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004282 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004283 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004284 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004285 mScheduler->onScreenAcquired(mAppConnectionHandle);
4286 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004287 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004288
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004289 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004290 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004291 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004292
4293 struct sched_param param = {0};
4294 param.sched_priority = 1;
4295 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4296 ALOGW("Couldn't set SCHED_FIFO on display on");
4297 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004298 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004299 // Turn off the display
4300 struct sched_param param = {0};
4301 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4302 ALOGW("Couldn't set SCHED_OTHER on display off");
4303 }
4304
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004305 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004306 mScheduler->disableHardwareVsync(true);
4307 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004308 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004309
Dominik Laskowski075d3172018-05-24 15:50:06 -07004310 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004311 mVisibleRegionsDirty = true;
4312 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004313 } else if (mode == HWC_POWER_MODE_DOZE ||
4314 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004315 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004316 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004318 mScheduler->onScreenAcquired(mAppConnectionHandle);
4319 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004320 }
4321 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4322 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004323 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004324 mScheduler->disableHardwareVsync(true);
4325 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004326 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004327 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004328 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004329 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004330 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004331 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004332
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004333 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004334 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004335 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004336 // Update refresh rate stats.
4337 mRefreshRateStats->setPowerMode(mode);
4338 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004339 }
4340
Dominik Laskowski34157762018-10-31 13:07:19 -07004341 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004342}
4343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004344void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004345 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004346 const auto display = getDisplayDevice(displayToken);
4347 if (!display) {
4348 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4349 displayToken.get());
4350 } else if (display->isVirtual()) {
4351 ALOGW("Attempt to set power mode %d for virtual display", mode);
4352 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004353 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004354 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004355 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004356}
4357
4358// ---------------------------------------------------------------------------
4359
Dominik Laskowskic2867142019-01-21 11:33:38 -08004360status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4361 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004363
Mathias Agopianbd115332013-04-18 16:41:04 -07004364 IPCThreadState* ipc = IPCThreadState::self();
4365 const int pid = ipc->getCallingPid();
4366 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004367
Mathias Agopianbd115332013-04-18 16:41:04 -07004368 if ((uid != AID_SHELL) &&
4369 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004370 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4371 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004373 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004374 // (this would indicate SF is stuck, but we want to be able to
4375 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004376 status_t err = mStateLock.timedLock(s2ns(1));
4377 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004378 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004379 StringAppendF(&result,
4380 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4381 "(no locks held)\n",
4382 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004383 }
4384
Dominik Laskowskic2867142019-01-21 11:33:38 -08004385 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004386
Dominik Laskowskic2867142019-01-21 11:33:38 -08004387 static const std::unordered_map<std::string, Dumper> dumpers = {
4388 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4389 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4390 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004391 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004392 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004393 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004394 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4395 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004396 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4397 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4398 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4399 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4400 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4401 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004402 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004403 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4404 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004405
Dominik Laskowskic2867142019-01-21 11:33:38 -08004406 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004407
Dominik Laskowskic2867142019-01-21 11:33:38 -08004408 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4409 (it->second)(args, asProto, result);
4410 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004411 if (asProto) {
4412 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4413 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4414 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004416 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004417 }
4418
Mathias Agopian9795c422009-08-26 16:36:26 -07004419 if (locked) {
4420 mStateLock.unlock();
4421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004422 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004424 return NO_ERROR;
4425}
4426
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 mCurrentState.traverseInZOrder(
4429 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004430}
4431
Dominik Laskowskic2867142019-01-21 11:33:38 -08004432void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004433 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004434
Dominik Laskowskic2867142019-01-21 11:33:38 -08004435 if (args.size() > 1) {
4436 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004437 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004438 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004439 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004440 }
Robert Carr2047fae2016-11-28 14:09:09 -08004441 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004442 } else {
4443 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004444 }
4445}
4446
Dominik Laskowskic2867142019-01-21 11:33:38 -08004447void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004448 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004449 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004450 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004451 }
Robert Carr2047fae2016-11-28 14:09:09 -08004452 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004453
Svetoslavd85084b2014-03-20 10:28:31 -07004454 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004455}
4456
Dominik Laskowskic2867142019-01-21 11:33:38 -08004457void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4458 mTimeStats->parseArgs(asProto, args, result);
4459}
4460
Jamie Gennis6547ff42013-07-16 20:12:42 -07004461// This should only be called from the main thread. Otherwise it would need
4462// the lock and should use mCurrentState rather than mDrawingState.
4463void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004464 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004465 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004466 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004467
4468 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4469}
4470
Yiwei Zhang5434a782018-12-05 18:06:32 -08004471void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004472 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004473
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004474 if (isLayerTripleBufferingDisabled())
4475 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004476
Yiwei Zhang5434a782018-12-05 18:06:32 -08004477 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4478 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4479 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4480 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4481 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4482 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004483 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004484}
4485
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004486void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004487 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004488 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004489 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004490 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004491
Ana Krulecba13ab32019-02-20 14:14:12 -08004492 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4493 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4494 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004495 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004496}
4497
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4499 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004500 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4501 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004502 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004503 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004505 }
David Sodman4a36e932017-11-07 14:29:47 -08004506 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004507 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004508 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4510 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004511}
4512
Dan Stozae77c7662016-05-13 11:37:28 -07004513void SurfaceFlinger::recordBufferingStats(const char* layerName,
4514 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004515 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4516 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004517 for (const auto& segment : history) {
4518 if (!segment.usedThirdBuffer) {
4519 stats.twoBufferTime += segment.totalTime;
4520 }
4521 if (segment.occupancyAverage < 1.0f) {
4522 stats.doubleBufferedTime += segment.totalTime;
4523 } else if (segment.occupancyAverage < 2.0f) {
4524 stats.tripleBufferedTime += segment.totalTime;
4525 }
4526 ++stats.numSegments;
4527 stats.totalTime += segment.totalTime;
4528 }
4529}
4530
Yiwei Zhang5434a782018-12-05 18:06:32 -08004531void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4532 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004533
4534 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4535 const size_t count = currentLayers.size();
4536 for (size_t i=0 ; i<count ; i++) {
4537 currentLayers[i]->dumpFrameEvents(result);
4538 }
4539}
4540
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004542 result.append("Buffering stats:\n");
4543 result.append(" [Layer name] <Active time> <Two buffer> "
4544 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004545 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004546 typedef std::tuple<std::string, float, float, float> BufferTuple;
4547 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004548 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004549 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004550 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004551 if (stats.numSegments == 0) {
4552 continue;
4553 }
4554 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4555 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4556 stats.totalTime;
4557 float doubleBufferRatio = static_cast<float>(
4558 stats.doubleBufferedTime) / stats.totalTime;
4559 float tripleBufferRatio = static_cast<float>(
4560 stats.tripleBufferedTime) / stats.totalTime;
4561 sorted.insert({activeTime, {name, twoBufferRatio,
4562 doubleBufferRatio, tripleBufferRatio}});
4563 }
4564 for (const auto& sortedPair : sorted) {
4565 float activeTime = sortedPair.first;
4566 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004567 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4568 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004569 }
4570 result.append("\n");
4571}
4572
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004574 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004575 const auto displayId = display->getId();
4576 if (!displayId) {
4577 continue;
4578 }
4579 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004580 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004581 continue;
4582 }
4583
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584 StringAppendF(&result,
4585 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4586 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004587 uint8_t port;
4588 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004589 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004590 result.append("no identification data\n");
4591 continue;
4592 }
4593
4594 if (!isEdid(data)) {
4595 result.append("unknown identification data: ");
4596 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004598 }
4599 result.append("\n");
4600 continue;
4601 }
4602
4603 const auto edid = parseEdid(data);
4604 if (!edid) {
4605 result.append("invalid EDID: ");
4606 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004608 }
4609 result.append("\n");
4610 continue;
4611 }
4612
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004614 result.append(edid->displayName.data(), edid->displayName.length());
4615 result.append("\"\n");
4616 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004617}
4618
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4620 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4621 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4622 StringAppendF(&result, "DisplayColorSetting: %s\n",
4623 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004624
4625 // TODO: print out if wide-color mode is active or not
4626
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004627 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004628 const auto displayId = display->getId();
4629 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630 continue;
4631 }
4632
Yiwei Zhang5434a782018-12-05 18:06:32 -08004633 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004634 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004635 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004637 }
4638
Lloyd Pique32cbe282018-10-19 13:09:22 -07004639 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004640 StringAppendF(&result, " Current color mode: %s (%d)\n",
4641 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004642 }
4643 result.append("\n");
4644}
4645
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004646LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004647 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004648 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4649 const State& state = useDrawing ? mDrawingState : mCurrentState;
4650 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004651 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004652 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004653 });
4654
4655 return layersProto;
4656}
4657
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004658LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4659 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004660 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004661
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004662 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004663 resolution->set_w(displayDevice->getWidth());
4664 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004665
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004666 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004667 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004668
Lloyd Pique32cbe282018-10-19 13:09:22 -07004669 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4670 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4671 layersProto.set_global_transform(displayState.orientation);
4672
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004673 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004674 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004675 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004676 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004677 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004678 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004679 }
4680 });
4681
4682 return layersProto;
4683}
4684
Dominik Laskowskic2867142019-01-21 11:33:38 -08004685void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4686 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004687 Colorizer colorizer(colorize);
4688
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004689 // figure out if we're stuck somewhere
4690 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4693
4694 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004695 * Dump library configuration.
4696 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004697
4698 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004699 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004701 appendSfConfigString(result);
4702 appendUiConfigString(result);
4703 appendGuiConfigString(result);
4704 result.append("\n");
4705
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004706 result.append("\nDisplay identification data:\n");
4707 dumpDisplayIdentificationData(result);
4708
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004709 result.append("\nWide-Color information:\n");
4710 dumpWideColorInfo(result);
4711
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004712 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004713 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004714 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004715 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004716 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004717
Andy McFadden41d67d72014-04-25 16:58:34 -07004718 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004719 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004720 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004721 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004722 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004723
Dan Stozab90cf072015-03-05 11:05:59 -08004724 dumpStaticScreenStats(result);
4725 result.append("\n");
4726
Yiwei Zhang5434a782018-12-05 18:06:32 -08004727 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004728
Dan Stozae77c7662016-05-13 11:37:28 -07004729 dumpBufferingStats(result);
4730
Andy McFadden4803b742012-09-24 19:07:20 -07004731 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732 * Dump the visible layer list
4733 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004734 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004735 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4736 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4737 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004738 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004739
Chia-I Wu2f884132018-09-13 15:17:58 -07004740 {
4741 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4742 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004743 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004744 result.append("\n");
4745 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004746
4747 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004748 * Dump Display state
4749 */
4750
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004752 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004753 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004754 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004755 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004756 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004757 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004758
4759 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004760 * Dump SurfaceFlinger global state
4761 */
4762
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004764 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004765 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004766
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004767 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768
Dominik Laskowski075d3172018-05-24 15:50:06 -07004769 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004770 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4771 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004772 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4773 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004774 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result,
4776 " transaction-flags : %08x\n"
4777 " gpu_to_cpu_unsupported : %d\n",
4778 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004779
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004780 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004781 displayId && getHwComposer().isConnected(*displayId)) {
4782 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783 StringAppendF(&result,
4784 " refresh-rate : %f fps\n"
4785 " x-dpi : %f\n"
4786 " y-dpi : %f\n",
4787 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4788 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004789 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004790
Yiwei Zhang5434a782018-12-05 18:06:32 -08004791 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004792
Dan Stozae22aec72016-08-01 13:20:59 -07004793 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004794 * Tracing state
4795 */
4796 mTracing.dump(result);
4797 result.append("\n");
4798
4799 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004800 * HWC layer minidump
4801 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004802 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004803 const auto displayId = display->getId();
4804 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004805 continue;
4806 }
4807
Yiwei Zhang5434a782018-12-05 18:06:32 -08004808 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004809 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004810 const sp<DisplayDevice> displayDevice = display;
4811 mCurrentState.traverseInZOrder(
4812 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004813 result.append("\n");
4814 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004815
4816 /*
4817 * Dump HWComposer state
4818 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004819 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004820 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004821 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004822 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004824 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004825
4826 /*
4827 * Dump gralloc state
4828 */
4829 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4830 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004831
4832 /*
4833 * Dump VrFlinger state if in use.
4834 */
4835 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4836 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004838 result.append("\n");
4839 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004840
4841 /**
4842 * Scheduler dump state.
4843 */
Ana Krulecc2870422019-01-29 19:00:58 -08004844 result.append("\nScheduler state:\n");
4845 result.append(mScheduler->doDump() + "\n");
4846 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004847}
4848
Dominik Laskowski075d3172018-05-24 15:50:06 -07004849const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004850 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004851 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004852 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004853 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004854 }
4855 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004856
Dominik Laskowski34157762018-10-31 13:07:19 -07004857 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004858 static const Vector<sp<Layer>> empty;
4859 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004860}
4861
Chia-I Wu28f320b2018-05-03 11:02:56 -07004862void SurfaceFlinger::updateColorMatrixLocked() {
4863 mat4 colorMatrix;
4864 if (mGlobalSaturationFactor != 1.0f) {
4865 // Rec.709 luma coefficients
4866 float3 luminance{0.213f, 0.715f, 0.072f};
4867 luminance *= 1.0f - mGlobalSaturationFactor;
4868 mat4 saturationMatrix = mat4(
4869 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4870 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4871 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4872 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4873 );
4874 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4875 } else {
4876 colorMatrix = mClientColorMatrix * mDaltonizer();
4877 }
4878
4879 if (mCurrentState.colorMatrix != colorMatrix) {
4880 mCurrentState.colorMatrix = colorMatrix;
4881 mCurrentState.colorMatrixChanged = true;
4882 setTransactionFlags(eTransactionNeeded);
4883 }
4884}
4885
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004886status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887#pragma clang diagnostic push
4888#pragma clang diagnostic error "-Wswitch-enum"
4889 switch (static_cast<ISurfaceComposerTag>(code)) {
4890 // These methods should at minimum make sure that the client requested
4891 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004892 case BOOT_FINISHED:
4893 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 case CREATE_DISPLAY:
4895 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004896 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897 case GET_ACTIVE_COLOR_MODE:
4898 case GET_ANIMATION_FRAME_STATS:
4899 case GET_HDR_CAPABILITIES:
4900 case SET_ACTIVE_CONFIG:
4901 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004902 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004903 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004904 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004905 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4906 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004907 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4908 IPCThreadState* ipc = IPCThreadState::self();
4909 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4910 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004911 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 }
Robert Carr1db73f62016-12-21 12:58:51 -08004913 return OK;
4914 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004916 IPCThreadState* ipc = IPCThreadState::self();
4917 const int pid = ipc->getCallingPid();
4918 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4920 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004921 return PERMISSION_DENIED;
4922 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 // Used by apps to hook Choreographer to SurfaceFlinger.
4926 case CREATE_DISPLAY_EVENT_CONNECTION:
4927 // The following calls are currently used by clients that do not
4928 // request necessary permissions. However, they do not expose any secret
4929 // information, so it is OK to pass them.
4930 case AUTHENTICATE_SURFACE:
4931 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004932 case GET_PHYSICAL_DISPLAY_IDS:
4933 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004935 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 case GET_DISPLAY_CONFIGS:
4937 case GET_DISPLAY_STATS:
4938 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4939 // Calling setTransactionState is safe, because you need to have been
4940 // granted a reference to Client* and Handle* to do anything with it.
4941 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004942 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004943 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004944 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004945 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004946 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 return OK;
4948 }
4949 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004950 case CAPTURE_SCREEN:
4951 case ADD_REGION_SAMPLING_LISTENER:
4952 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004953 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004954 IPCThreadState* ipc = IPCThreadState::self();
4955 const int pid = ipc->getCallingPid();
4956 const int uid = ipc->getCallingUid();
4957 if ((uid != AID_GRAPHICS) &&
4958 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4959 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4960 return PERMISSION_DENIED;
4961 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004962 return OK;
4963 }
4964 // The following codes are deprecated and should never be allowed to access SF.
4965 case CONNECT_DISPLAY_UNUSED:
4966 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4967 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4968 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004969 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004971
4972 // These codes are used for the IBinder protocol to either interrogate the recipient
4973 // side of the transaction for its canonical interface descriptor or to dump its state.
4974 // We let them pass by default.
4975 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4976 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4977 code == IBinder::SYSPROPS_TRANSACTION) {
4978 return OK;
4979 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004980 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004982 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004983 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4984 return OK;
4985 }
4986 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4987 return PERMISSION_DENIED;
4988#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004989}
4990
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4992 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004993 status_t credentialCheck = CheckTransactCodeCredentials(code);
4994 if (credentialCheck != OK) {
4995 return credentialCheck;
4996 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004997
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004998 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4999 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005000 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005001 IPCThreadState* ipc = IPCThreadState::self();
5002 const int uid = ipc->getCallingUid();
5003 if (CC_UNLIKELY(uid != AID_SYSTEM
5004 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005005 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005006 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005007 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 return PERMISSION_DENIED;
5009 }
5010 int n;
5011 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005012 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005013 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 return NO_ERROR;
5015 case 1002: // SHOW_UPDATES
5016 n = data.readInt32();
5017 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005018 invalidateHwcGeometry();
5019 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005021 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005022 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005023 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005025 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005026 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005027 setTransactionFlags(
5028 eTransactionNeeded|
5029 eDisplayTransactionNeeded|
5030 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005031 return NO_ERROR;
5032 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005033 case 1006:{ // send empty update
5034 signalRefresh();
5035 return NO_ERROR;
5036 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005037 case 1008: // toggle use of hw composer
5038 n = data.readInt32();
5039 mDebugDisableHWC = n ? 1 : 0;
5040 invalidateHwcGeometry();
5041 repaintEverything();
5042 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005043 case 1009: // toggle use of transform hint
5044 n = data.readInt32();
5045 mDebugDisableTransformHint = n ? 1 : 0;
5046 invalidateHwcGeometry();
5047 repaintEverything();
5048 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005050 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005051 reply->writeInt32(0);
5052 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005053 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005054 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005055 return NO_ERROR;
5056 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005057 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005058 if (!display) {
5059 return NAME_NOT_FOUND;
5060 }
5061
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005062 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005063 return NO_ERROR;
5064 }
5065 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005066 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005067 // daltonize
5068 n = data.readInt32();
5069 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005070 case 1:
5071 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5072 break;
5073 case 2:
5074 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5075 break;
5076 case 3:
5077 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5078 break;
5079 default:
5080 mDaltonizer.setType(ColorBlindnessType::None);
5081 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005082 }
5083 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005084 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005085 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005086 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005087 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005088
5089 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005090 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005091 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005092 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005093 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005094 // apply a color matrix
5095 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005096 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005097 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005098 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005099 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005100 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005101 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005102 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005103 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005105 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005106
5107 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5108 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005110 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5111 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5112 }
5113
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005115 return NO_ERROR;
5116 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005117 // This is an experimental interface
5118 // Needs to be shifted to proper binder interface when we productize
5119 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005120 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005121 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005122 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005123 return NO_ERROR;
5124 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005125 case 1017: {
5126 n = data.readInt32();
5127 mForceFullDamage = static_cast<bool>(n);
5128 return NO_ERROR;
5129 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005130 case 1018: { // Modify Choreographer's phase offset
5131 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005132 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005133 return NO_ERROR;
5134 }
5135 case 1019: { // Modify SurfaceFlinger's phase offset
5136 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005137 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005138 return NO_ERROR;
5139 }
Irvel468051e2016-06-13 16:44:44 -07005140 case 1020: { // Layer updates interceptor
5141 n = data.readInt32();
5142 if (n) {
5143 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005144 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005145 }
5146 else{
5147 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005148 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005149 }
5150 return NO_ERROR;
5151 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005152 case 1021: { // Disable HWC virtual displays
5153 n = data.readInt32();
5154 mUseHwcVirtualDisplays = !n;
5155 return NO_ERROR;
5156 }
Romain Guy0147a172017-06-01 13:53:56 -07005157 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005158 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005159 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005160
Chia-I Wu28f320b2018-05-03 11:02:56 -07005161 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005162 return NO_ERROR;
5163 }
Romain Guy54f154a2017-10-24 21:40:32 +01005164 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005165 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005166 invalidateHwcGeometry();
5167 repaintEverything();
5168 return NO_ERROR;
5169 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005170 // Deprecate, use 1030 to check whether the device is color managed.
5171 case 1024: {
5172 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005173 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005174 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005175 n = data.readInt32();
5176 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005177 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005178 mTracing.enable();
5179 doTracing("tracing.enable");
5180 reply->writeInt32(NO_ERROR);
5181 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005182 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005183 status_t err = mTracing.disable();
5184 reply->writeInt32(err);
5185 }
5186 return NO_ERROR;
5187 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005188 case 1026: { // Get layer tracing status
5189 reply->writeBool(mTracing.isEnabled());
5190 return NO_ERROR;
5191 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005192 // Is a DisplayColorSetting supported?
5193 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005194 const auto display = getDefaultDisplayDevice();
5195 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005196 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005197 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005198
5199 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5200 switch (setting) {
5201 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005202 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005203 break;
5204 case DisplayColorSetting::UNMANAGED:
5205 reply->writeBool(true);
5206 break;
5207 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005208 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005209 break;
5210 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005211 reply->writeBool(
5212 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005213 break;
5214 }
5215 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005216 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005217 // Is VrFlinger active?
5218 case 1028: {
5219 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005220 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005221 return NO_ERROR;
5222 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005223 // Is device color managed?
5224 case 1030: {
5225 reply->writeBool(useColorManagement);
5226 return NO_ERROR;
5227 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005228 // Override default composition data space
5229 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5230 // && adb shell stop zygote && adb shell start zygote
5231 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5232 // adb shell stop zygote && adb shell start zygote
5233 case 1031: {
5234 Mutex::Autolock _l(mStateLock);
5235 n = data.readInt32();
5236 if (n) {
5237 n = data.readInt32();
5238 if (n) {
5239 Dataspace dataspace = static_cast<Dataspace>(n);
5240 if (!validateCompositionDataspace(dataspace)) {
5241 return BAD_VALUE;
5242 }
5243 mDefaultCompositionDataspace = dataspace;
5244 }
5245 n = data.readInt32();
5246 if (n) {
5247 Dataspace dataspace = static_cast<Dataspace>(n);
5248 if (!validateCompositionDataspace(dataspace)) {
5249 return BAD_VALUE;
5250 }
5251 mWideColorGamutCompositionDataspace = dataspace;
5252 }
5253 } else {
5254 // restore composition data space.
5255 mDefaultCompositionDataspace = defaultCompositionDataspace;
5256 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5257 }
5258 return NO_ERROR;
5259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005260 }
5261 }
5262 return err;
5263}
5264
Steven Thomas6d8110b2017-08-31 18:24:21 -07005265void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005266 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005267 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005268}
5269
Ana Krulec7d1d6832018-12-27 11:10:09 -08005270void SurfaceFlinger::repaintEverythingForHWC() {
5271 mRepaintEverything = true;
5272 mEventQueue->invalidateForHWC();
5273}
5274
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005275// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5276class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005277public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5279 ~WindowDisconnector() {
5280 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005281 }
5282
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005283private:
5284 ANativeWindow* mWindow;
5285 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005286};
5287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005288status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005289 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5290 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005291 uint32_t reqWidth, uint32_t reqHeight,
5292 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005293 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005294 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005295
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005296 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005297
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005298 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5299
Chia-I Wu20261cb2018-08-23 12:55:44 -07005300 sp<DisplayDevice> display;
5301 {
5302 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005303
Chia-I Wu20261cb2018-08-23 12:55:44 -07005304 display = getDisplayDeviceLocked(displayToken);
5305 if (!display) return BAD_VALUE;
5306
Chia-I Wucb023152018-08-28 12:57:23 -07005307 // set the requested width/height to the logical display viewport size
5308 // by default
5309 if (reqWidth == 0 || reqHeight == 0) {
5310 reqWidth = uint32_t(display->getViewport().width());
5311 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005312 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005313 }
5314
Peiyong Lin0e003c92018-09-17 11:09:51 -07005315 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5316 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005317
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005318 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5319 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005320 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5321 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005322}
5323
5324status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005325 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5326 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005327 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005328 ATRACE_CALL();
5329
5330 class LayerRenderArea : public RenderArea {
5331 public:
Robert Carr578038f2018-03-09 12:25:24 -08005332 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005333 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5334 bool childrenOnly)
5335 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005336 mLayer(layer),
5337 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005338 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005339 mFlinger(flinger),
5340 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005341 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005342 Rect getBounds() const override {
5343 const Layer::State& layerState(mLayer->getDrawingState());
5344 return mLayer->getBufferSize(layerState);
5345 }
Marissa Wall61c58622018-07-18 10:12:20 -07005346 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005347 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005348 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005349 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005350 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005351 }
chaviwa76b2712017-09-20 12:02:26 -07005352 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005353 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005354 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005355 Rect getSourceCrop() const override {
5356 if (mCrop.isEmpty()) {
5357 return getBounds();
5358 } else {
5359 return mCrop;
5360 }
5361 }
Robert Carr578038f2018-03-09 12:25:24 -08005362 class ReparentForDrawing {
5363 public:
5364 const sp<Layer>& oldParent;
5365 const sp<Layer>& newParent;
5366
Vishnu Nair4351ad52019-02-11 14:13:02 -08005367 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5368 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005369 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005370 // Compute and cache the bounds for the new parent layer.
5371 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005372 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005373 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005374 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005375 };
5376
5377 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005378 const Rect sourceCrop = getSourceCrop();
5379 // no need to check rotation because there is none
5380 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5381 sourceCrop.height() != getReqHeight();
5382
Robert Carr578038f2018-03-09 12:25:24 -08005383 if (!mChildrenOnly) {
5384 mTransform = mLayer->getTransform().inverse();
5385 drawLayers();
5386 } else {
5387 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005388 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005389 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5390 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005391
Vishnu Nair4351ad52019-02-11 14:13:02 -08005392 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005393 drawLayers();
5394 }
5395 }
chaviwa76b2712017-09-20 12:02:26 -07005396
chaviwa76b2712017-09-20 12:02:26 -07005397 private:
chaviw7206d492017-11-10 16:16:12 -08005398 const sp<Layer> mLayer;
5399 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005400
5401 // In the "childrenOnly" case we reparent the children to a screenshot
5402 // layer which has no properties set and which does not draw.
5403 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005404 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005405 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005406
5407 SurfaceFlinger* mFlinger;
5408 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005409 };
5410
5411 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5412 auto parent = layerHandle->owner.promote();
5413
Robert Carr2e102c92018-10-23 12:11:15 -07005414 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005415 ALOGE("captureLayers called with a removed parent");
5416 return NAME_NOT_FOUND;
5417 }
5418
Robert Carr578038f2018-03-09 12:25:24 -08005419 const int uid = IPCThreadState::self()->getCallingUid();
5420 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005421 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005422 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5423 return PERMISSION_DENIED;
5424 }
5425
chaviw7206d492017-11-10 16:16:12 -08005426 Rect crop(sourceCrop);
5427 if (sourceCrop.width() <= 0) {
5428 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005429 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005430 }
5431
5432 if (sourceCrop.height() <= 0) {
5433 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005434 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005435 }
5436
5437 int32_t reqWidth = crop.width() * frameScale;
5438 int32_t reqHeight = crop.height() * frameScale;
5439
Chia-I Wu20261cb2018-08-23 12:55:44 -07005440 // really small crop or frameScale
5441 if (reqWidth <= 0) {
5442 reqWidth = 1;
5443 }
5444 if (reqHeight <= 0) {
5445 reqHeight = 1;
5446 }
5447
Peiyong Lin0e003c92018-09-17 11:09:51 -07005448 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005449
Robert Carr578038f2018-03-09 12:25:24 -08005450 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005451 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5452 if (!layer->isVisible()) {
5453 return;
Robert Carr578038f2018-03-09 12:25:24 -08005454 } else if (childrenOnly && layer == parent.get()) {
5455 return;
chaviwa76b2712017-09-20 12:02:26 -07005456 }
5457 visitor(layer);
5458 });
5459 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005460 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005461}
5462
5463status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5464 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005465 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005466 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005467 bool useIdentityTransform) {
5468 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005469
Peiyong Lin0e003c92018-09-17 11:09:51 -07005470 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005471 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5472 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005473 *outBuffer =
5474 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5475 static_cast<android_pixel_format>(reqPixelFormat), 1,
5476 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005477
5478 // This mutex protects syncFd and captureResult for communication of the return values from the
5479 // main thread back to this Binder thread
5480 std::mutex captureMutex;
5481 std::condition_variable captureCondition;
5482 std::unique_lock<std::mutex> captureLock(captureMutex);
5483 int syncFd = -1;
5484 std::optional<status_t> captureResult;
5485
Robert Carr03480e22018-01-04 16:02:06 -08005486 const int uid = IPCThreadState::self()->getCallingUid();
5487 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5488
Dominik Laskowski8c001672018-05-30 16:52:06 -07005489 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005490 // If there is a refresh pending, bug out early and tell the binder thread to try again
5491 // after the refresh.
5492 if (mRefreshPending) {
5493 ATRACE_NAME("Skipping screenshot for now");
5494 std::unique_lock<std::mutex> captureLock(captureMutex);
5495 captureResult = std::make_optional<status_t>(EAGAIN);
5496 captureCondition.notify_one();
5497 return;
5498 }
5499
5500 status_t result = NO_ERROR;
5501 int fd = -1;
5502 {
5503 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005504 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005505 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5506 useIdentityTransform, forSystem, &fd);
5507 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005508 }
5509
5510 {
5511 std::unique_lock<std::mutex> captureLock(captureMutex);
5512 syncFd = fd;
5513 captureResult = std::make_optional<status_t>(result);
5514 captureCondition.notify_one();
5515 }
5516 });
5517
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005518 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005520 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005521 while (*captureResult == EAGAIN) {
5522 captureResult.reset();
5523 result = postMessageAsync(message);
5524 if (result != NO_ERROR) {
5525 return result;
5526 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005527 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005528 }
5529 result = *captureResult;
5530 }
5531
5532 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005533 sync_wait(syncFd, -1);
5534 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005535 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005536
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005537 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005538}
5539
chaviwa76b2712017-09-20 12:02:26 -07005540void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005541 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005542 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5543 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005544 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005545
chaviwa76b2712017-09-20 12:02:26 -07005546 const auto reqWidth = renderArea.getReqWidth();
5547 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005548 const auto sourceCrop = renderArea.getSourceCrop();
5549 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005550
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005551 renderengine::DisplaySettings clientCompositionDisplay;
5552 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005553
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005554 // assume that bounds are never offset, and that they are the same as the
5555 // buffer bounds.
5556 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5557 ui::Transform transform = renderArea.getTransform();
5558 mat4 m;
5559 m[0][0] = transform[0][0];
5560 m[0][1] = transform[0][1];
5561 m[0][3] = transform[0][2];
5562 m[1][0] = transform[1][0];
5563 m[1][1] = transform[1][1];
5564 m[1][3] = transform[1][2];
5565 m[3][0] = transform[2][0];
5566 m[3][1] = transform[2][1];
5567 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005568
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005569 clientCompositionDisplay.globalTransform = m;
5570 mat4 rotMatrix;
5571 // Displacement for repositioning the clipping rectangle after rotating it
5572 // with the rotation hint.
5573 int displacementX = 0;
5574 int displacementY = 0;
5575 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5576 switch (rotation) {
5577 case ui::Transform::ROT_90:
5578 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5579 displacementX = reqWidth;
5580 break;
5581 case ui::Transform::ROT_180:
5582 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5583 displacementX = reqWidth;
5584 displacementY = reqHeight;
5585 break;
5586 case ui::Transform::ROT_270:
5587 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5588 displacementY = reqHeight;
5589 break;
5590 default:
5591 break;
5592 }
5593 // We need to transform the clipping window into the right spot.
5594 // First, rotate the clipping rectangle by the rotation hint to get the
5595 // right orientation
5596 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5597 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5598 const vec4 rotClipTL = rotMatrix * clipTL;
5599 const vec4 rotClipBR = rotMatrix * clipBR;
5600 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5601 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5602 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5603 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5604
5605 // Now reposition the clipping rectangle with the displacement vector
5606 // computed above.
5607 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5608
5609 clientCompositionDisplay.clip =
5610 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5611 newClipRight + displacementX, newClipBottom + displacementY);
5612
5613 // We need to perform the same transformation in layer space, so propagate
5614 // it to the global transform.
5615 mat4 clipTransform = displacementMat * rotMatrix;
5616 clientCompositionDisplay.globalTransform *= clipTransform;
5617 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5618 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005619
chaviw50da5042018-04-09 13:49:37 -07005620 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005621
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005622 renderengine::LayerSettings fillLayer;
5623 fillLayer.source.buffer.buffer = nullptr;
5624 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5625 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5626 fillLayer.alpha = half(alpha);
5627 clientCompositionLayers.push_back(fillLayer);
5628
5629 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005630 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005631 renderengine::LayerSettings layerSettings;
5632 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5633 layerSettings);
5634 if (prepared) {
5635 clientCompositionLayers.push_back(layerSettings);
5636 }
chaviwa76b2712017-09-20 12:02:26 -07005637 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005638
5639 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005640 // Use an empty fence for the buffer fence, since we just created the buffer so
5641 // there is no need for synchronization with the GPU.
5642 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005643 base::unique_fd drawFence;
5644 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005645 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005646
5647 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005648}
5649
chaviwa76b2712017-09-20 12:02:26 -07005650status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5651 TraverseLayersFunction traverseLayers,
5652 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005653 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005654 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005655 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005656 ATRACE_CALL();
5657
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005658 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005659
5660 traverseLayers([&](Layer* layer) {
5661 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5662 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005663
Robert Carr03480e22018-01-04 16:02:06 -08005664 // We allow the system server to take screenshots of secure layers for
5665 // use in situations like the Screen-rotation animation and place
5666 // the impetus on WindowManager to not persist them.
5667 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005668 ALOGW("FB is protected: PERMISSION_DENIED");
5669 return PERMISSION_DENIED;
5670 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005671 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005672 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005673}
5674
chaviw95ef3c42019-02-14 10:55:09 -08005675void SurfaceFlinger::setInputWindowsFinished() {
5676 Mutex::Autolock _l(mStateLock);
5677
5678 mPendingSyncInputWindows = false;
5679 mTransactionCV.broadcast();
5680}
chaviw5f21a5e2019-02-14 10:00:34 -08005681
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005682// ---------------------------------------------------------------------------
5683
Dan Stoza412903f2017-04-27 13:42:17 -07005684void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5685 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005686}
5687
Dan Stoza412903f2017-04-27 13:42:17 -07005688void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5689 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005690}
5691
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005692void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005693 const LayerVector::Visitor& visitor) {
5694 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005695 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005696 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005697 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005698 continue;
5699 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005700 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005701 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005702 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005703 return;
5704 }
chaviwa76b2712017-09-20 12:02:26 -07005705 if (!layer->isVisible()) {
5706 return;
5707 }
5708 visitor(layer);
5709 });
5710 }
5711}
5712
chaviw291d88a2019-02-14 10:33:58 -08005713// ----------------------------------------------------------------------------
5714
5715void SetInputWindowsListener::onSetInputWindowsFinished() {
5716 mFlinger->setInputWindowsFinished();
5717}
5718
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005719}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005720
Lloyd Pique074e8122018-07-26 12:57:23 -07005721
Mathias Agopian3f844832013-08-07 21:24:32 -07005722#if defined(__gl_h_)
5723#error "don't include gl/gl.h in this file"
5724#endif
5725
5726#if defined(__gl2_h_)
5727#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005728#endif