blob: a59d45a181417f52faba136f15eae55d790d2e14 [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
Dan Stozaec460082018-12-17 15:35:09 -0800404 property_get("debug.sf.luma_sampling", value, "1");
405 mLumaSampling = atoi(value);
406
Ana Krulec757f63a2019-01-25 10:46:18 -0800407 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
408 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700409
Romain Guy11d63f42017-07-20 12:47:14 -0700410 // We should be reading 'persist.sys.sf.color_saturation' here
411 // but since /data may be encrypted, we need to wait until after vold
412 // comes online to attempt to read the property. The property is
413 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800414
415 if (useTrebleTestingOverride()) {
416 // Without the override SurfaceFlinger cannot connect to HIDL
417 // services that are not listed in the manifests. Considered
418 // deriving the setting from the set service name, but it
419 // would be brittle if the name that's not 'default' is used
420 // for production purposes later on.
421 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425void SurfaceFlinger::onFirstRef()
426{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800427 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430SurfaceFlinger::~SurfaceFlinger()
431{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Dan Stozac7014012014-02-14 15:03:43 -0800434void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435{
436 // the window manager died on us. prepare its eulogy.
437
Andy McFadden13a082e2012-08-24 10:16:42 -0700438 // restore initial conditions (default device unblank, etc)
439 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440
441 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700442 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443}
444
Robert Carr1db73f62016-12-21 12:58:51 -0800445static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700446 status_t err = client->initCheck();
447 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return nullptr;
451}
452
453sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
454 return initClient(new Client(this));
455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 // Display ID is assigned when virtual display is allocated by HWC.
478 DisplayDeviceState state;
479 state.isSecure = secure;
480 state.displayName = displayName;
481 mCurrentState.displays.add(token, state);
482 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
490 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
496 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 mInterceptor->saveDisplayDeletion(state.sequenceId);
501 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
506 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 const auto internalDisplayId = getInternalDisplayIdLocked();
509 if (!internalDisplayId) {
510 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 }
512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 std::vector<PhysicalDisplayId> displayIds;
514 displayIds.reserve(mPhysicalDisplayTokens.size());
515 displayIds.push_back(internalDisplayId->value);
516
517 for (const auto& [id, token] : mPhysicalDisplayTokens) {
518 if (id != *internalDisplayId) {
519 displayIds.push_back(id.value);
520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800523 return displayIds;
524}
525
526sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
527 Mutex::Autolock lock(mStateLock);
528 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
Ady Abraham37965d42018-11-01 13:43:32 -0700531status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
532 if (!outGetColorManagement) {
533 return BAD_VALUE;
534 }
535 *outGetColorManagement = useColorManagement;
536 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700537}
538
Lloyd Pique441d5042018-10-18 16:49:51 -0700539HWComposer& SurfaceFlinger::getHwComposer() const {
540 return mCompositionEngine->getHwComposer();
541}
542
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700543renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
544 return mCompositionEngine->getRenderEngine();
545}
546
Lloyd Pique70d91362018-10-18 16:02:55 -0700547compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
548 return *mCompositionEngine.get();
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551void SurfaceFlinger::bootFinished()
552{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700553 if (mStartPropertySetThread->join() != NO_ERROR) {
554 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556 const nsecs_t now = systemTime();
557 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000558 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559
560 // wait patiently for the window manager death
561 const String16 name("window");
562 sp<IBinder> window(defaultServiceManager()->getService(name));
563 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 }
Robert Carr720e5062018-07-30 17:45:14 -0700566 sp<IBinder> input(defaultServiceManager()->getService(
567 String16("inputflinger")));
568 if (input == nullptr) {
569 ALOGE("Failed to link to input service");
570 } else {
571 mInputFlinger = interface_cast<IInputFlinger>(input);
572 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 if (mVrFlinger) {
575 mVrFlinger->OnBootFinished();
576 }
577
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700579 // formerly we would just kill the process, but we now ask it to exit so it
580 // can choose where to stop the animation.
581 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700582
583 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
584 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
585 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700586
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
591 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
592 // away and it should be controlled by flipping the switch in setting. The switch in
593 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
594 // The boot must be complete before we can set the active config.
595
596 if (mUse90Hz) {
597 mPhaseOffsets->setRefreshRateType(
598 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
599 setRefreshRateTo(RefreshRateType::PERFORMANCE);
600 } else {
601 mPhaseOffsets->setRefreshRateType(
602 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
603 setRefreshRateTo(RefreshRateType::DEFAULT);
604 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800605 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800606}
607
Dan Stoza436ccf32018-06-21 12:10:12 -0700608uint32_t SurfaceFlinger::getNewTexture() {
609 {
610 std::lock_guard lock(mTexturePoolMutex);
611 if (!mTexturePool.empty()) {
612 uint32_t name = mTexturePool.back();
613 mTexturePool.pop_back();
614 ATRACE_INT("TexturePoolSize", mTexturePool.size());
615 return name;
616 }
617
618 // The pool was too small, so increase it for the future
619 ++mTexturePoolSize;
620 }
621
622 // The pool was empty, so we need to get a new texture name directly using a
623 // blocking call to the main thread
624 uint32_t name = 0;
625 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
626 return name;
627}
628
Mathias Agopian3f844832013-08-07 21:24:32 -0700629void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700630 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700631}
632
Wei Wangf9b05ee2017-07-19 20:59:39 -0700633// Do not call property_set on main thread which will be blocked by init
634// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700636 ALOGI( "SurfaceFlinger's main thread ready to run. "
637 "Initializing graphics H/W...");
638
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700642 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800643 mScheduler =
644 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
645 auto resyncCallback =
646 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800647
Ana Krulecc2870422019-01-29 19:00:58 -0800648 mAppConnectionHandle =
649 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
650 resyncCallback,
651 impl::EventThread::InterceptVSyncsCallback());
652 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
653 resyncCallback, [this](nsecs_t timestamp) {
654 mInterceptor->saveVSyncEvent(timestamp);
655 });
656
657 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
658 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
659 mSfConnectionHandle.get());
660
Steven Thomasb02664d2017-07-26 18:48:28 -0700661 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700662 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700663 renderEngineFeature |= (useColorManagement ?
664 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700665 renderEngineFeature |= (useContextPriority ?
666 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700667
668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700669 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700670 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700671 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700672
673 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
674 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700675 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
676 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800677 // Process any initial hotplug and resulting display changes.
678 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 const auto display = getDefaultDisplayDeviceLocked();
680 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700681 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800683
Steven Thomas050b2c82017-03-06 11:45:16 -0800684 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700686 // This callback is called from the vr flinger dispatch thread. We
687 // need to call signalTransaction(), which requires holding
688 // mStateLock when we're not on the main thread. Acquiring
689 // mStateLock from the vr flinger dispatch thread might trigger a
690 // deadlock in surface flinger (see b/66916578), so post a message
691 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700692 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700693 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
694 mVrFlingerRequestsDisplay = requestDisplay;
695 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
699 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700700 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 .value_or(0),
702 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 if (!mVrFlinger) {
704 ALOGE("Failed to start vrflinger");
705 }
706 }
707
Mathias Agopian92a979a2012-08-02 18:32:23 -0700708 // initialize our drawing state
709 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700710
Andy McFadden13a082e2012-08-24 10:16:42 -0700711 // set initial conditions (e.g. unblank default device)
712 initializeDisplays();
713
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700714 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700715
Wei Wangf9b05ee2017-07-19 20:59:39 -0700716 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700717
718 const bool presentFenceReliable =
719 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
720 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700721
722 if (mStartPropertySetThread->Start() != NO_ERROR) {
723 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800725
Kevin DuBois36233132019-02-19 14:08:55 -0800726 if (mUse90Hz) {
727 mScheduler->setExpiredIdleTimerCallback([this] {
728 Mutex::Autolock lock(mStateLock);
729 setRefreshRateTo(RefreshRateType::DEFAULT);
730 });
731 mScheduler->setResetIdleTimerCallback([this] {
732 Mutex::Autolock lock(mStateLock);
733 setRefreshRateTo(RefreshRateType::PERFORMANCE);
734 });
735 }
Ana Krulecc2870422019-01-29 19:00:58 -0800736 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
737 *display->getId()),
738 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800739
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700741}
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700744 Mutex::Autolock _l(mStateLock);
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746 char value[PROPERTY_VALUE_MAX];
747
748 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100752
753 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700754 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800755
756 property_get("persist.sys.sf.color_mode", value, "0");
757 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700758}
759
Mathias Agopiana67e4182012-06-19 17:26:12 -0700760void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Start boot animation service by setting a property mailbox
762 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 if (mStartPropertySetThread->join() != NO_ERROR) {
766 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800767 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700771 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800779
Jamie Gennis582270d2011-08-17 18:19:00 -0700780bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800782 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800783 return authenticateSurfaceTextureLocked(bufferProducer);
784}
785
786bool SurfaceFlinger::authenticateSurfaceTextureLocked(
787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800788 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800789 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800790}
791
Brian Anderson6b376712017-04-04 10:51:39 -0700792status_t SurfaceFlinger::getSupportedFrameTimestamps(
793 std::vector<FrameEvent>* outSupported) const {
794 *outSupported = {
795 FrameEvent::REQUESTED_PRESENT,
796 FrameEvent::ACQUIRE,
797 FrameEvent::LATCH,
798 FrameEvent::FIRST_REFRESH_START,
799 FrameEvent::LAST_REFRESH_START,
800 FrameEvent::GPU_COMPOSITION_DONE,
801 FrameEvent::DEQUEUE_READY,
802 FrameEvent::RELEASE,
803 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700804 ConditionalLock _l(mStateLock,
805 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700806 if (!getHwComposer().hasCapability(
807 HWC2::Capability::PresentFenceIsNotReliable)) {
808 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
809 }
810 return NO_ERROR;
811}
812
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800813status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
814 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 return BAD_VALUE;
817 }
818
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800819 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700820 if (!displayId) {
821 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700822 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 // TODO: Not sure if display density should handled by SF any longer
825 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700828 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800829 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 }
832 return density;
833 }
834 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("ro.sf.lcd_density"); }
839 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 DisplayInfo info = DisplayInfo();
845
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846 float xdpi = hwConfig->getDpiX();
847 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849 info.w = hwConfig->getWidth();
850 info.h = hwConfig->getHeight();
851 // Default display viewport to display width and height
852 info.viewportW = info.w;
853 info.viewportH = info.h;
854
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800855 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 // The density of the device is provided by a build property
857 float density = Density::getBuildDensity() / 160.0f;
858 if (density == 0) {
859 // the build doesn't provide a density -- this is wrong!
860 // use xdpi instead
861 ALOGE("ro.sf.lcd_density must be defined as a build property");
862 density = xdpi / 160.0f;
863 }
864 if (Density::getEmuDensity()) {
865 // if "qemu.sf.lcd_density" is specified, it overrides everything
866 xdpi = ydpi = density = Density::getEmuDensity();
867 density /= 160.0f;
868 }
869 info.density = density;
870
871 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872 const auto display = getDefaultDisplayDeviceLocked();
873 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700874
875 // This is for screenrecord
876 const Rect viewport = display->getViewport();
877 if (viewport.isValid()) {
878 info.viewportW = uint32_t(viewport.getWidth());
879 info.viewportH = uint32_t(viewport.getHeight());
880 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 } else {
882 // TODO: where should this value come from?
883 static const int TV_DENSITY = 213;
884 info.density = TV_DENSITY / 160.0f;
885 info.orientation = 0;
886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 info.xdpi = xdpi;
889 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800891 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892
Andy McFadden91b2ca82014-06-13 14:04:23 -0700893 // This is how far in advance a buffer must be queued for
894 // presentation at a given time. If you want a buffer to appear
895 // on the screen at time N, you must submit the buffer before
896 // (N - presentationDeadline).
897 //
898 // Normally it's one full refresh period (to give SF a chance to
899 // latch the buffer), but this can be reduced by configuring a
900 // DispSync offset. Any additional delays introduced by the hardware
901 // composer or panel must be accounted for here.
902 //
903 // We add an additional 1ms to allow for processing time and
904 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800905 info.presentationDeadline =
906 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700907
908 // All non-virtual displays are currently considered secure.
909 info.secure = true;
910
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800911 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700912 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800913 std::swap(info.w, info.h);
914 }
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700917 }
918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 return NO_ERROR;
920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
923 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return BAD_VALUE;
925 }
926
Ana Krulecc2870422019-01-29 19:00:58 -0800927 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return NO_ERROR;
929}
930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
932 const auto display = getDisplayDevice(displayToken);
933 if (!display) {
934 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800935 return BAD_VALUE;
936 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700939}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700940
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
942 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 // Lock is acquired by setRefreshRateTo.
946 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800947 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
948 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
949 return;
950 }
951
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952 // Lock is acquired by setRefreshRateTo.
953 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954 if (!display) {
955 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
956 displayToken.get());
957 return;
958 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700959 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800960 ALOGW("Attempt to set active config %d for virtual display", mode);
961 return;
962 }
963 int currentDisplayPowerMode = display->getPowerMode();
964 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
965 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700966 return;
967 }
968
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 // Don't check against the current mode yet. Worst case we set the desired
970 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800971 std::lock_guard<std::mutex> lock(mActiveConfigLock);
972 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
973
974 if (!mDesiredActiveConfigChanged) {
975 // This is the first time we set the desired
976 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
977
978 // This will trigger HWC refresh without resetting the idle timer.
979 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800981 mDesiredActiveConfigChanged = true;
982 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983}
984
985status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
986 ATRACE_CALL();
987 postMessageSync(new LambdaMessage(
988 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
989 return NO_ERROR;
990}
991
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992void SurfaceFlinger::setActiveConfigInternal() {
993 ATRACE_CALL();
994
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800996 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997
998 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
999 display->setActiveConfig(mUpcomingActiveConfig.configId);
1000
Ana Krulecc2870422019-01-29 19:00:58 -08001001 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1003}
1004
Ady Abrahamb838aed2019-02-12 15:30:16 -08001005bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001006 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 // we may be in the process of changing the active state
1008 if (mWaitForNextInvalidate) {
1009 mWaitForNextInvalidate = false;
1010
1011 repaintEverythingForHWC();
1012 // We do not want to give another frame to HWC while we are transitioning.
1013 return true;
1014 }
1015
1016 if (mCheckPendingFence) {
1017 if (mPreviousPresentFence != Fence::NO_FENCE &&
1018 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1019 // fence has not signaled yet. wait for the next invalidate
1020 repaintEverythingForHWC();
1021 return true;
1022 }
1023
1024 // We received the present fence from the HWC, so we assume it successfully updated
1025 // the config, hence we update SF.
1026 mCheckPendingFence = false;
1027 setActiveConfigInternal();
1028 }
1029
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001030 // Store the local variable to release the lock.
1031 ActiveConfigInfo desiredActiveConfig;
1032 {
1033 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (!mDesiredActiveConfigChanged) {
1035 return false;
1036 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001037 desiredActiveConfig = mDesiredActiveConfig;
1038 }
1039
1040 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1042 // display is not valid or we are already in the requested mode
1043 // on both cases there is nothing left to do
1044 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1045 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1046 mDesiredActiveConfigChanged = false;
1047 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1048 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001049 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050
1051 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1052 mUpcomingActiveConfig = desiredActiveConfig;
1053 const auto displayId = display->getId();
1054 LOG_ALWAYS_FATAL_IF(!displayId);
1055
1056 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1057 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1058
1059 // we need to submit an empty frame to HWC to start the process
1060 mWaitForNextInvalidate = true;
1061 mCheckPendingFence = true;
1062
1063 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001064}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001066status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1067 Vector<ColorMode>* outColorModes) {
1068 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001069 return BAD_VALUE;
1070 }
1071
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001073 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001074 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1075
1076 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1077 if (!displayId) {
1078 return NAME_NOT_FOUND;
1079 }
1080
Dominik Laskowski075d3172018-05-24 15:50:06 -07001081 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001082 }
Michael Wright28f24d02016-07-12 13:30:53 -07001083 outColorModes->clear();
1084 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1085
1086 return NO_ERROR;
1087}
1088
Daniel Solomon42d04562019-01-20 21:03:19 -08001089status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1090 ui::DisplayPrimaries &primaries) {
1091 if (!displayToken) {
1092 return BAD_VALUE;
1093 }
1094
1095 // Currently we only support this API for a single internal display.
1096 if (getInternalDisplayToken() != displayToken) {
1097 return BAD_VALUE;
1098 }
1099
1100 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1101 return NO_ERROR;
1102}
1103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1105 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001106 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001107 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001108 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001109}
1110
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001112 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113 Vector<ColorMode> modes;
1114 getDisplayColorModes(displayToken, &modes);
1115 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1116 if (mode < ColorMode::NATIVE || !exists) {
1117 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1118 decodeColorMode(mode).c_str(), mode, displayToken.get());
1119 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001120 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121 const auto display = getDisplayDevice(displayToken);
1122 if (!display) {
1123 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1124 decodeColorMode(mode).c_str(), mode, displayToken.get());
1125 } else if (display->isVirtual()) {
1126 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1127 decodeColorMode(mode).c_str(), mode);
1128 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001129 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1130 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131 }
1132 }));
1133
Michael Wright28f24d02016-07-12 13:30:53 -07001134 return NO_ERROR;
1135}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001136
Svetoslavd85084b2014-03-20 10:28:31 -07001137status_t SurfaceFlinger::clearAnimationFrameStats() {
1138 Mutex::Autolock _l(mStateLock);
1139 mAnimFrameTracker.clearStats();
1140 return NO_ERROR;
1141}
1142
1143status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1144 Mutex::Autolock _l(mStateLock);
1145 mAnimFrameTracker.getStats(outStats);
1146 return NO_ERROR;
1147}
1148
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1150 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001151 Mutex::Autolock _l(mStateLock);
1152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001153 const auto display = getDisplayDeviceLocked(displayToken);
1154 if (!display) {
1155 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001156 return BAD_VALUE;
1157 }
1158
Peiyong Linfb069302018-04-25 14:34:31 -07001159 // At this point the DisplayDeivce should already be set up,
1160 // meaning the luminance information is already queried from
1161 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001162 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001163 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1164 capabilities.getDesiredMaxLuminance(),
1165 capabilities.getDesiredMaxAverageLuminance(),
1166 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001167
1168 return NO_ERROR;
1169}
1170
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001171status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1172 ui::PixelFormat* outFormat,
1173 ui::Dataspace* outDataspace,
1174 uint8_t* outComponentMask) const {
1175 if (!outFormat || !outDataspace || !outComponentMask) {
1176 return BAD_VALUE;
1177 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001178 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001179 if (!display || !display->getId()) {
1180 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1181 return BAD_VALUE;
1182 }
1183 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1184 outDataspace, outComponentMask);
1185}
1186
Kevin DuBois74e53772018-11-19 10:52:38 -08001187status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1188 bool enable, uint8_t componentMask,
1189 uint64_t maxFrames) const {
1190 const auto display = getDisplayDevice(displayToken);
1191 if (!display || !display->getId()) {
1192 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1193 return BAD_VALUE;
1194 }
1195
1196 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1197 componentMask, maxFrames);
1198}
1199
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001200status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1201 uint64_t maxFrames, uint64_t timestamp,
1202 DisplayedFrameStats* outStats) const {
1203 const auto display = getDisplayDevice(displayToken);
1204 if (!display || !display->getId()) {
1205 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1206 return BAD_VALUE;
1207 }
1208
1209 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1210 outStats);
1211}
1212
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001213status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1214 if (!outSupported) {
1215 return BAD_VALUE;
1216 }
1217 *outSupported = getRenderEngine().supportsProtectedContent();
1218 return NO_ERROR;
1219}
1220
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001221status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1222 bool* outIsWideColorDisplay) const {
1223 if (!displayToken || !outIsWideColorDisplay) {
1224 return BAD_VALUE;
1225 }
1226 Mutex::Autolock _l(mStateLock);
1227 const auto display = getDisplayDeviceLocked(displayToken);
1228 if (!display) {
1229 return BAD_VALUE;
1230 }
1231 *outIsWideColorDisplay = display->hasWideColorGamut();
1232 return NO_ERROR;
1233}
1234
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001236 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001237 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238
Chia-I Wu90f669f2017-10-05 14:24:41 -07001239 if (mInjectVSyncs == enable) {
1240 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001241 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242
Ana Krulecc2870422019-01-29 19:00:58 -08001243 auto resyncCallback =
1244 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001245
Ana Krulec98b5b242018-08-10 15:03:23 -07001246 // TODO(akrulec): Part of the Injector should be refactored, so that it
1247 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001248 if (enable) {
1249 ALOGV("VSync Injections enabled");
1250 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001251 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001252 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001253 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001254 impl::EventThread::InterceptVSyncsCallback(),
1255 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001257 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258 } else {
1259 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001260 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1261 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 }
1263
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001264 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001265 }));
1266
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001267 return NO_ERROR;
1268}
1269
1270status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 Mutex::Autolock _l(mStateLock);
1272
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001273 if (!mInjectVSyncs) {
1274 ALOGE("VSync Injections not enabled");
1275 return BAD_VALUE;
1276 }
1277 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1278 ALOGV("Injecting VSync inside SurfaceFlinger");
1279 mVSyncInjector->onInjectSyncEvent(when);
1280 }
1281 return NO_ERROR;
1282}
1283
Lloyd Pique755e3192018-01-31 16:46:15 -08001284status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1285 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001286 // Try to acquire a lock for 1s, fail gracefully
1287 const status_t err = mStateLock.timedLock(s2ns(1));
1288 const bool locked = (err == NO_ERROR);
1289 if (!locked) {
1290 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1291 return TIMED_OUT;
1292 }
1293
1294 outLayers->clear();
1295 mCurrentState.traverseInZOrder([&](Layer* layer) {
1296 outLayers->push_back(layer->getLayerDebugInfo());
1297 });
1298
1299 mStateLock.unlock();
1300 return NO_ERROR;
1301}
1302
Peiyong Linc6780972018-10-28 15:24:08 -07001303status_t SurfaceFlinger::getCompositionPreference(
1304 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1305 Dataspace* outWideColorGamutDataspace,
1306 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001307 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001308 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001309 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001310 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001311 return NO_ERROR;
1312}
1313
Dan Stozaec460082018-12-17 15:35:09 -08001314status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1315 const sp<IBinder>& stopLayerHandle,
1316 const sp<IRegionSamplingListener>& listener) {
1317 if (!listener) {
1318 return BAD_VALUE;
1319 }
1320 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001321 return NO_ERROR;
1322}
1323
Dan Stozaec460082018-12-17 15:35:09 -08001324status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1325 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001326 return NO_ERROR;
1327}
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001328// ----------------------------------------------------------------------------
1329
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001330sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1331 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001332 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001333 Mutex::Autolock lock(mStateLock);
1334 return getVsyncPeriod();
1335 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001336
Ana Krulecc2870422019-01-29 19:00:58 -08001337 const auto& handle =
1338 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001339
Ana Krulecc2870422019-01-29 19:00:58 -08001340 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001341}
1342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001343// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344
1345void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001346 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347}
1348
1349void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001350 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351}
1352
1353void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001354 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001355}
1356
1357void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001358 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001359 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001360}
1361
1362status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001363 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001364 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365}
1366
1367status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001368 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001369 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001370 if (res == NO_ERROR) {
1371 msg->wait();
1372 }
1373 return res;
1374}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001375
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001376void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001377 do {
1378 waitForEvent();
1379 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001380}
1381
Dominik Laskowski83b88212018-12-11 13:34:06 -08001382nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001383 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001384 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1385 return 0;
1386 }
1387
1388 const auto config = getHwComposer().getActiveConfig(*displayId);
1389 return config ? config->getVsyncPeriod() : 0;
1390}
1391
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001392void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1393 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001394 ATRACE_NAME("SF onVsync");
1395
Steven Thomas3cfac282017-02-06 12:29:30 -08001396 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001397 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001398 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001399 return;
1400 }
1401
Dominik Laskowski075d3172018-05-24 15:50:06 -07001402 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001403 return;
1404 }
1405
Dominik Laskowski075d3172018-05-24 15:50:06 -07001406 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001407 // For now, we don't do anything with external display vsyncs.
1408 return;
1409 }
1410
Ana Krulecc2870422019-01-29 19:00:58 -08001411 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001412}
1413
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001414void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001415 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1416 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001417}
1418
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001419void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1420 mPhaseOffsets->setRefreshRateType(refreshRate);
1421
1422 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1423 mVsyncModulator.setPhaseOffsets(early, gl, late);
1424
1425 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001426 return;
1427 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001428
Ana Krulec7d1d6832018-12-27 11:10:09 -08001429 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1430 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1431 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1432 // refresh cycle.
1433
1434 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001435 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001436 if (currentVsyncPeriod == 0) {
1437 return;
1438 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001439
Ana Krulec7d1d6832018-12-27 11:10:09 -08001440 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1441 // floating numbers.
1442 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001443 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1444 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001445 if (std::abs(currentFps - newFps) <= 1) {
1446 return;
1447 }
1448
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001449 const auto displayId = getInternalDisplayIdLocked();
1450 LOG_ALWAYS_FATAL_IF(!displayId);
1451
1452 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001453 for (int i = 0; i < configs.size(); i++) {
1454 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1455 if (vsyncPeriod == 0) {
1456 continue;
1457 }
1458 const float fps = 1e9 / vsyncPeriod;
1459 // TODO(b/113612090): There should be a better way at determining which config
1460 // has the right refresh rate.
1461 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001462 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001463 }
1464 }
1465}
1466
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001467void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001468 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001469 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001470 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471
Lloyd Piqueba04e622017-12-14 17:11:26 -08001472 // Ignore events that do not have the right sequenceId.
1473 if (sequenceId != getBE().mComposerSequenceId) {
1474 return;
1475 }
1476
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 // Only lock if we're not on the main thread. This function is normally
1478 // called on a hwbinder thread, but for the primary display it's called on
1479 // the main thread with the state lock already held, so don't attempt to
1480 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001482
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001484
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001485 if (std::this_thread::get_id() == mMainThreadId) {
1486 // Process all pending hot plug events immediately if we are on the main thread.
1487 processDisplayHotplugEventsLocked();
1488 }
1489
Lloyd Piqueba04e622017-12-14 17:11:26 -08001490 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001491}
1492
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001494 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001495 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001497 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001498 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001499}
1500
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001501void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001502 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001504 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001505 getHwComposer().setVsyncEnabled(*displayId,
1506 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1507 }
Mathias Agopian86303202012-07-24 22:46:10 -07001508}
1509
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001510// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001511void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001512 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001513 // Clear the drawing state so that the logic inside of
1514 // handleTransactionLocked will fire. It will determine the delta between
1515 // mCurrentState and mDrawingState and re-apply all changes when we make the
1516 // transition.
1517 mDrawingState.displays.clear();
1518 mDisplays.clear();
1519}
1520
Steven Thomas050b2c82017-03-06 11:45:16 -08001521void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001522 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001523 if (!mVrFlinger)
1524 return;
1525 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001526 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001527 return;
1528 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529
Lloyd Pique441d5042018-10-18 16:49:51 -07001530 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 ALOGE("Vr flinger is only supported for remote hardware composer"
1532 " service connections. Ignoring request to transition to vr"
1533 " flinger.");
1534 mVrFlingerRequestsDisplay = false;
1535 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001536 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001537
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001539
Steven Thomas0123ac62018-07-12 11:32:34 -07001540 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001541 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001542
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001543 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001544
1545 // Clear out all the output layers from the composition engine for all
1546 // displays before destroying the hardware composer interface. This ensures
1547 // any HWC layers are destroyed through that interface before it becomes
1548 // invalid.
1549 for (const auto& [token, displayDevice] : mDisplays) {
1550 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1551 compositionengine::Output::OutputLayers());
1552 }
1553
Steven Thomas0123ac62018-07-12 11:32:34 -07001554 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1555 // called below. Clear the reference now so we don't accidentally use it
1556 // later.
1557 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001558
Steven Thomasb02664d2017-07-26 18:48:28 -07001559 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001562
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001564 // Delete the current instance before creating the new one
1565 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1566 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1567 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1568 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001569
Lloyd Pique441d5042018-10-18 16:49:51 -07001570 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001571 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001572
1573 if (vrFlingerRequestsDisplay) {
1574 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001575 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001576
1577 mVisibleRegionsDirty = true;
1578 invalidateHwcGeometry();
1579
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001580 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001581 display = getDefaultDisplayDeviceLocked();
1582 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001583 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001586 const nsecs_t vsyncPeriod = getVsyncPeriod();
1587 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001588
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001589 // The present fences returned from vr_hwc are not an accurate
1590 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001591 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001592
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 // Use phase of 0 since phase is not known.
1594 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001595 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001596 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001597
Ana Krulecc2870422019-01-29 19:00:58 -08001598 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001599
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001600 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001601 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001602}
1603
Mathias Agopian4fec8732012-06-29 14:12:52 -07001604void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001605 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001606 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001607 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001608 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001609 break;
1610 }
1611
Ana Krulecba13ab32019-02-20 14:14:12 -08001612 if (mUse90Hz && mUseSmart90ForVideo) {
1613 // This call is made each time SF wakes up and creates a new frame. It is part
1614 // of video detection feature.
1615 mScheduler->incrementFrameCounter();
1616 }
Alec Mourife3dc942019-02-12 14:19:18 -08001617 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001618 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001619 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001620 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001621 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1622 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001623 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001624 }
1625 // For now, only propagate backpressure when missing a hwc frame.
1626 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001627 if (mPropagateBackpressure) {
1628 signalLayerUpdate();
1629 break;
1630 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001631 }
Dan Stoza50182882016-07-08 12:02:20 -07001632
Steven Thomas050b2c82017-03-06 11:45:16 -08001633 // Now that we're going to make it to the handleMessageTransaction()
1634 // call below it's safe to call updateVrFlinger(), which will
1635 // potentially trigger a display handoff.
1636 updateVrFlinger();
1637
Dan Stoza6b9454d2014-11-07 16:00:59 -08001638 bool refreshNeeded = handleMessageTransaction();
1639 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001640
1641 updateCursorAsync();
1642 updateInputFlinger();
1643
Dan Stoza58784442014-12-02 16:58:17 -08001644 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001645 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001646 // Signal a refresh if a transaction modified the window state,
1647 // a new buffer was latched, or if HWC has requested a full
1648 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001649 signalRefresh();
1650 }
1651 break;
1652 }
1653 case MessageQueue::REFRESH: {
1654 handleMessageRefresh();
1655 break;
1656 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001657 }
1658}
1659
Dan Stoza6b9454d2014-11-07 16:00:59 -08001660bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001661 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001662 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001663
1664 // Apply any ready transactions in the queues if there are still transactions that have not been
1665 // applied, wake up during the next vsync period and check again
1666 bool transactionNeeded = false;
1667 if (!flushTransactionQueues()) {
1668 transactionNeeded = true;
1669 }
1670
Mathias Agopian4fec8732012-06-29 14:12:52 -07001671 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001672 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001673 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001674
1675 if (transactionNeeded) {
1676 setTransactionFlags(eTransactionNeeded);
1677 }
1678
1679 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001680}
1681
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001684
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001685 mRefreshPending = false;
1686
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001687 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001688 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001689 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001690 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691 for (const auto& [token, display] : mDisplays) {
1692 beginFrame(display);
1693 prepareFrame(display);
1694 doDebugFlashRegions(display, repaintEverything);
1695 doComposition(display, repaintEverything);
1696 }
1697
Adrian Roos1e1a1282017-11-01 19:05:31 +01001698 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001699 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001700
1701 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001702 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001703
Dan Stozabfbffeb2016-07-21 14:49:33 -07001704 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001705 for (const auto& [token, displayDevice] : mDisplays) {
1706 auto display = displayDevice->getCompositionDisplay();
1707 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001708 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001709 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001710 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711
Jorim Jaggi90535212018-05-23 23:44:06 +02001712 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001713
David Sodman7e4ae112018-02-09 15:02:28 -08001714 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001715
1716 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001717}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001718
David Sodmanfa9b2af2017-12-24 13:28:59 -08001719
1720bool SurfaceFlinger::handleMessageInvalidate() {
1721 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001722 bool refreshNeeded = handlePageFlip();
1723
Vishnu Nair4351ad52019-02-11 14:13:02 -08001724 if (mVisibleRegionsDirty) {
1725 computeLayerBounds();
1726 }
1727
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001728 for (auto& layer : mLayersPendingRefresh) {
1729 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001730 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001731 invalidateLayerStack(layer, visibleReg);
1732 }
1733 mLayersPendingRefresh.clear();
1734 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001735}
1736
David Sodman79bba0e2018-08-05 18:07:49 -07001737void SurfaceFlinger::calculateWorkingSet() {
1738 ATRACE_CALL();
1739 ALOGV(__FUNCTION__);
1740
David Sodman79bba0e2018-08-05 18:07:49 -07001741 // build the h/w work list
1742 if (CC_UNLIKELY(mGeometryInvalid)) {
1743 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001744 for (const auto& [token, displayDevice] : mDisplays) {
1745 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001746 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747 if (!displayId) {
1748 continue;
1749 }
David Sodman79bba0e2018-08-05 18:07:49 -07001750
Lloyd Pique32cbe282018-10-19 13:09:22 -07001751 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752 for (size_t i = 0; i < currentLayers.size(); i++) {
1753 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001754
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001755 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001756 layer->forceClientComposition(displayDevice);
1757 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001758 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001759
Lloyd Pique32cbe282018-10-19 13:09:22 -07001760 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001761 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001762 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763 }
David Sodman79bba0e2018-08-05 18:07:49 -07001764 }
1765 }
1766 }
1767
1768 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001769 for (const auto& [token, displayDevice] : mDisplays) {
1770 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001771 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001772 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001773 continue;
1774 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001775 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001776
1777 if (mDrawingState.colorMatrixChanged) {
1778 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001779 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001780 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001781 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001782 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001783 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1784 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001785 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001786 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001787 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1788 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001789 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001790 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
1792
Peiyong Lind3788632018-09-18 16:01:31 -07001793 // TODO(b/111562338) remove when composer 2.3 is shipped.
1794 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001795 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001796 }
1797
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001798 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001799 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001800 }
1801
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001802 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001803 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001804 layer->setCompositionType(displayDevice,
1805 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 continue;
1807 }
1808
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001810 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001811 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001812 }
1813
Peiyong Lin13effd12018-07-24 17:01:47 -07001814 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001815 ColorMode colorMode;
1816 Dataspace dataSpace;
1817 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001818 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001819 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001820 }
1821 }
1822
1823 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001824
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001825 for (const auto& [token, displayDevice] : mDisplays) {
1826 auto display = displayDevice->getCompositionDisplay();
1827 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001828 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001829 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1830 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1831 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001832 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001833 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001834 }
1835 }
David Sodman79bba0e2018-08-05 18:07:49 -07001836}
1837
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1839 bool repaintEverything) {
1840 auto display = displayDevice->getCompositionDisplay();
1841 const auto& displayState = display->getState();
1842
Mathias Agopiancd60f992012-08-16 16:28:27 -07001843 // is debugging enabled
1844 if (CC_LIKELY(!mDebugRegion))
1845 return;
1846
Lloyd Pique32cbe282018-10-19 13:09:22 -07001847 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001848 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001849 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001850 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001851 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001852 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001853 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001855 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856 }
1857 }
1858
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001860
1861 if (mDebugRegion > 1) {
1862 usleep(mDebugRegion * 1000);
1863 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001864
Lloyd Pique32cbe282018-10-19 13:09:22 -07001865 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866}
1867
Adrian Roos1e1a1282017-11-01 19:05:31 +01001868void SurfaceFlinger::doTracing(const char* where) {
1869 ATRACE_CALL();
1870 ATRACE_NAME(where);
1871 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001872 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001873 }
1874}
1875
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001876void SurfaceFlinger::logLayerStats() {
1877 ATRACE_CALL();
1878 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001879 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001880 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001881 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001882 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001883 }
1884 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001885
1886 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001887 }
1888}
1889
David Sodman2b406362017-12-15 13:33:47 -08001890void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 ATRACE_CALL();
1893 ALOGV("preComposition");
1894
David Sodman2b406362017-12-15 13:33:47 -08001895 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1896
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001898 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001899 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001900 needExtraInvalidate = true;
1901 }
Robert Carr2047fae2016-11-28 14:09:09 -08001902 });
1903
Mathias Agopiancd60f992012-08-16 16:28:27 -07001904 if (needExtraInvalidate) {
1905 signalLayerUpdate();
1906 }
1907}
1908
Ana Krulece588e312018-09-18 12:32:24 -07001909void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1910 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // Update queue of past composite+present times and determine the
1912 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001913 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001915 while (!getBE().mCompositePresentTimes.empty()) {
1916 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917 // Cached values should have been updated before calling this method,
1918 // which helps avoid duplicate syscalls.
1919 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1920 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1921 break;
1922 }
1923 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001924 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925 }
1926
1927 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001928 while (getBE().mCompositePresentTimes.size() > 16) {
1929 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930 }
1931
Ana Krulece588e312018-09-18 12:32:24 -07001932 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001933}
1934
Ana Krulece588e312018-09-18 12:32:24 -07001935void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1936 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001937 // Integer division and modulo round toward 0 not -inf, so we need to
1938 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001939 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1940 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1941 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942
Ana Krulec757f63a2019-01-25 10:46:18 -08001943 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001944 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001945 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001946 }
1947
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 // Snap the latency to a value that removes scheduling jitter from the
1949 // composition and present times, which often have >1ms of jitter.
1950 // Reducing jitter is important if an app attempts to extrapolate
1951 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001952 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001954 nsecs_t bias = stats.vsyncPeriod / 2;
1955 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1956 nsecs_t snappedCompositeToPresentLatency =
1957 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958
David Sodman99974d22017-11-28 12:04:33 -08001959 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001960 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1961 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001962 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963}
1964
Ady Abraham8164d482019-01-11 14:47:59 -08001965// debug patch for b/119477596 - add stack guards to catch stack
1966// corruptions and disable clang optimizations.
1967// The code below is temporary and planned to be removed once stack
1968// corruptions are found.
1969#pragma clang optimize off
1970class StackGuard {
1971public:
1972 StackGuard(const char* name, const char* func, int line) {
1973 guarders.reserve(MIN_CAPACITY);
1974 guarders.push_back({this, name, func, line});
1975 validate();
1976 }
1977 ~StackGuard() {
1978 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1979 if (i->guard == this) {
1980 guarders.erase(i);
1981 break;
1982 }
1983 }
1984 }
1985
1986 static void validate() {
1987 for (const auto& guard : guarders) {
1988 if (guard.guard->cookie != COOKIE_VALUE) {
1989 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1990 CallStack stack(LOG_TAG);
1991 abort();
1992 }
1993 }
1994 }
1995
1996private:
1997 uint64_t cookie = COOKIE_VALUE;
1998 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1999 static constexpr size_t MIN_CAPACITY = 16;
2000
2001 struct GuarderElement {
2002 StackGuard* guard;
2003 const char* name;
2004 const char* func;
2005 int line;
2006 };
2007
2008 static std::vector<GuarderElement> guarders;
2009};
2010std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2011
2012#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2013
2014#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002015void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002016{
Ady Abraham8164d482019-01-11 14:47:59 -08002017 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ATRACE_CALL();
2019 ALOGV("postComposition");
2020
Brian Anderson3546a3f2016-07-14 11:51:14 -07002021 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002022 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002023 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002024 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002025 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002026 }
Ady Abraham8164d482019-01-11 14:47:59 -08002027 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002028
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002029 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002030 const auto displayDevice = getDefaultDisplayDeviceLocked();
2031 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032
David Sodman73beded2017-11-15 11:56:06 -08002033 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002035 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2036
Lloyd Pique32cbe282018-10-19 13:09:22 -07002037 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002038 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002039 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2040 ->getRenderSurface()
2041 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 } else {
2044 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2045 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046
Ady Abraham8164d482019-01-11 14:47:59 -08002047 ASSERT_ON_STACK_GUARD();
2048
David Sodman73beded2017-11-15 11:56:06 -08002049 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002050 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2051 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002052 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002054 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055
Ana Krulece588e312018-09-18 12:32:24 -07002056 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002057 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002058 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059
Ady Abraham8164d482019-01-11 14:47:59 -08002060 ASSERT_ON_STACK_GUARD();
2061
David Sodman2b406362017-12-15 13:33:47 -08002062 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063 // when we started doing work for this frame, but that should be okay
2064 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002065 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002066 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(compositorTiming);
2068
Brian Andersond0010582017-03-07 13:20:31 -08002069 {
David Sodman99974d22017-11-28 12:04:33 -08002070 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002071 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002072 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002073
2074 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002075 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076
Robert Carr2047fae2016-11-28 14:09:09 -08002077 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002078 bool frameLatched =
2079 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2080 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002081 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002082 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002083 recordBufferingStats(layer->getName().string(),
2084 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002085 }
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002087 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002088
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002089 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002091 mScheduler->addPresentFence(presentFenceTime);
2092 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002093 }
2094
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002095 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002096 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2097 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002098 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002099 }
2100 }
2101
Ady Abraham8164d482019-01-11 14:47:59 -08002102 ASSERT_ON_STACK_GUARD();
2103
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002104 if (mAnimCompositionPending) {
2105 mAnimCompositionPending = false;
2106
Brian Anderson4e606e32017-03-16 15:34:57 -07002107 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002108 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002109 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002110
2111 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002112 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 // The HWC doesn't support present fences, so use the refresh
2114 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002115 const nsecs_t presentTime =
2116 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002117 DEFINE_STACK_GUARD(presentTime);
2118
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002119 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002120 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002121 }
2122 mAnimFrameTracker.advanceFrame();
2123 }
Dan Stozab90cf072015-03-05 11:05:59 -08002124
Ady Abraham8164d482019-01-11 14:47:59 -08002125 ASSERT_ON_STACK_GUARD();
2126
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002127 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002128 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002129 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002130 }
2131
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
2133
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002134 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002135
Ady Abraham8164d482019-01-11 14:47:59 -08002136 ASSERT_ON_STACK_GUARD();
2137
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2139 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002140 return;
2141 }
2142
2143 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002144 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002145 if (mHasPoweredOff) {
2146 mHasPoweredOff = false;
2147 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002148 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002149 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002150 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002151 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002152 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2153 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002154 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002155 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002156 }
David Sodman4a36e932017-11-07 14:29:47 -08002157 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002158
2159 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002160 }
David Sodman4a36e932017-11-07 14:29:47 -08002161 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002162 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002163
2164 {
2165 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002166 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002167 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002168 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002169 if (refillCount > 0) {
2170 const size_t offset = mTexturePool.size();
2171 mTexturePool.resize(mTexturePoolSize);
2172 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2173 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2174 }
Ady Abraham8164d482019-01-11 14:47:59 -08002175 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002176 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002177
Marissa Wallfda30bb2018-10-12 11:34:28 -07002178 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002179 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002180
Dan Stozaec460082018-12-17 15:35:09 -08002181 if (mLumaSampling) {
2182 mRegionSamplingThread->sampleNow();
2183 }
2184
Ady Abraham8164d482019-01-11 14:47:59 -08002185 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002186}
Ady Abraham8164d482019-01-11 14:47:59 -08002187#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002188
Vishnu Nair4351ad52019-02-11 14:13:02 -08002189void SurfaceFlinger::computeLayerBounds() {
2190 for (const auto& pair : mDisplays) {
2191 const auto& displayDevice = pair.second;
2192 const auto display = displayDevice->getCompositionDisplay();
2193 for (const auto& layer : mDrawingState.layersSortedByZ) {
2194 // only consider the layers on the given layer stack
2195 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002196 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002197 }
2198
2199 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2200 }
2201 }
2202}
2203
Mathias Agopiancd60f992012-08-16 16:28:27 -07002204void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002205 ATRACE_CALL();
2206 ALOGV("rebuildLayerStacks");
2207
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002208 // We need to clear these out now as these may be holding on to a
2209 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2210 // also holds a reference. When the set of visible layers is recomputed,
2211 // some layers may be destroyed if the only thing keeping them alive was
2212 // that list of visible layers associated with each display. The layer
2213 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2214 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2215 for (const auto& [token, display] : mDisplays) {
2216 getBE().mCompositionInfo[token].clear();
2217 }
2218
Mathias Agopiancd60f992012-08-16 16:28:27 -07002219 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002220 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002221 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002222 mVisibleRegionsDirty = false;
2223 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002224
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002225 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002226 const auto& displayDevice = pair.second;
2227 auto display = displayDevice->getCompositionDisplay();
2228 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002229 Region opaqueRegion;
2230 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002231 compositionengine::Output::OutputLayers layersSortedByZ;
2232 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002233 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002234 const ui::Transform& tr = displayState.transform;
2235 const Rect bounds = displayState.bounds;
2236 if (displayState.isEnabled) {
2237 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002238
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002240 auto compositionLayer = layer->getCompositionLayer();
2241 if (compositionLayer == nullptr) {
2242 return;
2243 }
2244
Lloyd Pique32cbe282018-10-19 13:09:22 -07002245 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002246 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2247 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2248
Lloyd Pique07e33212018-12-18 16:33:37 -08002249 bool needsOutputLayer = false;
2250
Lloyd Piqueef36b002019-01-23 17:52:04 -08002251 if (display->belongsInOutput(layer->getLayerStack(),
2252 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002253 Region drawRegion(tr.transform(
2254 layer->visibleNonTransparentRegion));
2255 drawRegion.andSelf(bounds);
2256 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002257 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 }
Chia-I Wu83806892017-11-16 10:50:20 -08002259 }
2260
Lloyd Pique07e33212018-12-18 16:33:37 -08002261 if (needsOutputLayer) {
2262 layersSortedByZ.emplace_back(
2263 display->getOrCreateOutputLayer(displayId, compositionLayer,
2264 layerFE));
2265 deprecated_layersSortedByZ.add(layer);
2266
2267 auto& outputLayerState = layersSortedByZ.back()->editState();
2268 outputLayerState.visibleRegion =
2269 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2270 } else if (displayId) {
2271 // For layers that are being removed from a HWC display,
2272 // and that have queued frames, add them to a a list of
2273 // released layers so we can properly set a fence.
2274 bool hasExistingOutputLayer =
2275 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2276 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2277 mLayersWithQueuedFrames.cend(),
2278 layer) != mLayersWithQueuedFrames.cend();
2279
2280 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002281 layersNeedingFences.add(layer);
2282 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002283 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002284 });
2285 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002286
2287 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2288
2289 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002290 displayDevice->setLayersNeedingFences(layersNeedingFences);
2291
2292 Region undefinedRegion{bounds};
2293 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2294
2295 display->editState().undefinedRegion = undefinedRegion;
2296 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002297 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002298 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002299}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002300
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002302// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002303// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002305// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306// The returned HDR data space is one of
2307// - Dataspace::UNKNOWN
2308// - Dataspace::BT2020_HLG
2309// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2311 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002312 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 *outHdrDataSpace = Dataspace::UNKNOWN;
2314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002316 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317 case Dataspace::V0_SCRGB:
2318 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002319 case Dataspace::BT2020:
2320 case Dataspace::BT2020_ITU:
2321 case Dataspace::BT2020_LINEAR:
2322 case Dataspace::DISPLAY_BT2020:
2323 bestDataSpace = Dataspace::DISPLAY_BT2020;
2324 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002326 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 case Dataspace::BT2020_PQ:
2329 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002330 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002333 case Dataspace::BT2020_HLG:
2334 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002335 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336 // When there's mixed PQ content and HLG content, we set the HDR
2337 // data space to be BT2020_PQ and convert HLG to PQ.
2338 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2339 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002340 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 break;
2342 default:
2343 break;
2344 }
Romain Guy54f154a2017-10-24 21:40:32 +01002345 }
2346
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002347 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002348}
2349
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002351void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2352 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002353 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2354 *outMode = ColorMode::NATIVE;
2355 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002358 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002359
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002362
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002363 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2364
Peiyong Lina3ea5592019-02-10 14:45:00 -08002365 switch (mForceColorMode) {
2366 case ColorMode::SRGB:
2367 bestDataSpace = Dataspace::V0_SRGB;
2368 break;
2369 case ColorMode::DISPLAY_P3:
2370 bestDataSpace = Dataspace::DISPLAY_P3;
2371 break;
2372 default:
2373 break;
2374 }
2375
Peiyong Lindfde5112018-06-05 10:58:41 -07002376 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002377 const bool isHdr =
2378 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002379 if (isHdr) {
2380 bestDataSpace = hdrDataSpace;
2381 }
2382
Chia-I Wu0d711262018-05-21 15:19:35 -07002383 RenderIntent intent;
2384 switch (mDisplayColorSetting) {
2385 case DisplayColorSetting::MANAGED:
2386 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002387 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002388 break;
2389 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002390 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002391 break;
2392 default: // vendor display color setting
2393 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2394 break;
2395 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002396
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002397 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002398}
2399
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2401 auto display = displayDevice->getCompositionDisplay();
2402 const auto& displayState = display->getState();
2403
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002404 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002405 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2406 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002407
David Sodmanfa9b2af2017-12-24 13:28:59 -08002408 // If nothing has changed (!dirty), don't recompose.
2409 // If something changed, but we don't currently have any visible layers,
2410 // and didn't when we last did a composition, then skip it this time.
2411 // The second rule does two things:
2412 // - When all layers are removed from a display, we'll emit one black
2413 // frame, then nothing more until we get new layers.
2414 // - When a display is created with a private layer stack, we won't
2415 // emit any black frames until a layer is added to the layer stack.
2416 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002417
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 const char flagPrefix[] = {'-', '+'};
2419 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2421 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2422 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2423 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002424
Lloyd Pique31cb2942018-10-19 17:23:03 -07002425 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002426
David Sodmanfa9b2af2017-12-24 13:28:59 -08002427 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002428 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002429 }
2430}
2431
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2433 auto display = displayDevice->getCompositionDisplay();
2434 const auto& displayState = display->getState();
2435
2436 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 return;
David Sodman2b406362017-12-15 13:33:47 -08002438 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002439
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002440 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002443}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002444
Lloyd Pique32cbe282018-10-19 13:09:22 -07002445void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002446 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447 ALOGV("doComposition");
2448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 auto display = displayDevice->getCompositionDisplay();
2450 const auto& displayState = display->getState();
2451
2452 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002453 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002454 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002455
David Sodmanfa9b2af2017-12-24 13:28:59 -08002456 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002458
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002460 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002461 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002463}
2464
David Sodmanfa9b2af2017-12-24 13:28:59 -08002465void SurfaceFlinger::postFrame()
2466{
2467 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 const auto display = getDefaultDisplayDeviceLocked();
2469 if (display && getHwComposer().isConnected(*display->getId())) {
2470 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002471 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2472 logFrameStats();
2473 }
2474 }
2475}
2476
Lloyd Pique32cbe282018-10-19 13:09:22 -07002477void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002478 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 auto display = displayDevice->getCompositionDisplay();
2482 const auto& displayState = display->getState();
2483 const auto displayId = display->getId();
2484
David Sodmanfa9b2af2017-12-24 13:28:59 -08002485 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002486
Lloyd Pique32cbe282018-10-19 13:09:22 -07002487 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 if (displayId) {
2489 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002490 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002491 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002492 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002493 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002494
Chia-I Wu7b549592017-11-15 09:14:57 -08002495 // The layer buffer from the previous frame (if any) is released
2496 // by HWC only when the release fence from this frame (if any) is
2497 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002498 if (displayId && layer->hasHwcLayer(displayDevice)) {
2499 releaseFence =
2500 getHwComposer().getLayerReleaseFence(*displayId,
2501 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002502 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002503
2504 // If the layer was client composited in the previous frame, we
2505 // need to merge with the previous client target acquire fence.
2506 // Since we do not track that, always merge with the current
2507 // client target acquire fence when it is available, even though
2508 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002509 if (layer->getCompositionType(displayDevice) ==
2510 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002511 releaseFence =
2512 Fence::merge("LayerRelease", releaseFence,
2513 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002514 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002515
David Sodman15094112018-10-11 09:39:37 -07002516 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002517 }
Chia-I Wu83806892017-11-16 10:50:20 -08002518
2519 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002521 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002522 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002523 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002524 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002525 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002526 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002527 }
2528 }
2529
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 if (displayId) {
2531 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002532 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534}
2535
Mathias Agopian87baae12012-07-31 12:38:26 -07002536void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537{
Mathias Agopian841cde52012-03-01 15:44:37 -08002538 ATRACE_CALL();
2539
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002540 // here we keep a copy of the drawing state (that is the state that's
2541 // going to be overwritten by handleTransactionLocked()) outside of
2542 // mStateLock so that the side-effects of the State assignment
2543 // don't happen with mStateLock held (which can cause deadlocks).
2544 State drawingState(mDrawingState);
2545
Mathias Agopianca4d3602011-05-19 15:38:14 -07002546 Mutex::Autolock _l(mStateLock);
2547 const nsecs_t now = systemTime();
2548 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549
Mathias Agopianca4d3602011-05-19 15:38:14 -07002550 // Here we're guaranteed that some transaction flags are set
2551 // so we can call handleTransactionLocked() unconditionally.
2552 // We call getTransactionFlags(), which will also clear the flags,
2553 // with mStateLock held to guarantee that mCurrentState won't change
2554 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002555
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002556 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002557 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002558 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002559
Mathias Agopianca4d3602011-05-19 15:38:14 -07002560 mLastTransactionTime = systemTime() - now;
2561 mDebugInTransaction = 0;
2562 invalidateHwcGeometry();
2563 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002564}
2565
Lloyd Piqueba04e622017-12-14 17:11:26 -08002566void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2567 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 const std::optional<DisplayIdentificationInfo> info =
2569 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002570
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572 continue;
2573 }
2574
Lloyd Piqueba04e622017-12-14 17:11:26 -08002575 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002576 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002577 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002578 mPhysicalDisplayTokens[info->id] = new BBinder();
2579 DisplayDeviceState state;
2580 state.displayId = info->id;
2581 state.isSecure = true; // All physical displays are currently considered secure.
2582 state.displayName = info->name;
2583 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2584 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002585 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002587 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588
Dominik Laskowski075d3172018-05-24 15:50:06 -07002589 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2590 if (index >= 0) {
2591 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2592 mInterceptor->saveDisplayDeletion(state.sequenceId);
2593 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002594 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002596 }
2597
2598 processDisplayChangesLocked();
2599 }
2600
2601 mPendingHotplugEvents.clear();
2602}
2603
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002604void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002605 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2606 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002607}
2608
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002611 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612 const sp<IGraphicBufferProducer>& producer) {
2613 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002614 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002616 creationArgs.isSecure = state.isSecure;
2617 creationArgs.displaySurface = dispSurface;
2618 creationArgs.hasWideColorGamut = false;
2619 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002620
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002621 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 creationArgs.isPrimary = isInternalDisplay;
2623
2624 if (useColorManagement && displayId) {
2625 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002627 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002628 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002629 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002630
Dominik Laskowski7e045462018-05-30 13:02:02 -07002631 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002633 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 }
tangrobin6753a022018-08-10 10:58:54 +08002635 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636
Dominik Laskowski075d3172018-05-24 15:50:06 -07002637 if (displayId) {
2638 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002639 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002641 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642
Lloyd Pique90c115d2018-09-18 21:39:42 -07002643 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002645 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 // Make sure that composition can never be stalled by a virtual display
2648 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002649 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002650 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2652 }
2653
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 creationArgs.displayInstallOrientation =
2655 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002656
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002658 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659
Lloyd Pique90c115d2018-09-18 21:39:42 -07002660 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661
2662 if (maxFrameBufferAcquiredBuffers >= 3) {
2663 nativeWindowSurface->preallocateBuffers();
2664 }
2665
2666 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002667 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002668 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002670 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002672 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2673 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002674 if (!state.isVirtual()) {
2675 LOG_ALWAYS_FATAL_IF(!displayId);
2676 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002677 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002678
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002679 display->setLayerStack(state.layerStack);
2680 display->setProjection(state.orientation, state.viewport, state.frame);
2681 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002682
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002684}
2685
Lloyd Pique347200f2017-12-14 17:00:15 -08002686void SurfaceFlinger::processDisplayChangesLocked() {
2687 // here we take advantage of Vector's copy-on-write semantics to
2688 // improve performance by skipping the transaction entirely when
2689 // know that the lists are identical
2690 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2691 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2692 if (!curr.isIdenticalTo(draw)) {
2693 mVisibleRegionsDirty = true;
2694 const size_t cc = curr.size();
2695 size_t dc = draw.size();
2696
2697 // find the displays that were removed
2698 // (ie: in drawing state but not in current state)
2699 // also handle displays that changed
2700 // (ie: displays that are in both lists)
2701 for (size_t i = 0; i < dc;) {
2702 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2703 if (j < 0) {
2704 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002706 // Save display ID before disconnecting.
2707 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002708 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002709
2710 if (!display->isVirtual()) {
2711 LOG_ALWAYS_FATAL_IF(!displayId);
2712 dispatchDisplayHotplugEvent(displayId->value, false);
2713 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002715
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002716 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 } else {
2718 // this display is in both lists. see if something changed.
2719 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002720 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2722 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2723 if (state_binder != draw_binder) {
2724 // changing the surface is like destroying and
2725 // recreating the DisplayDevice, so we just remove it
2726 // from the drawing state, so that it get re-added
2727 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002729 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002730 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002731 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 mDrawingState.displays.removeItemsAt(i);
2733 dc--;
2734 // at this point we must loop to the next item
2735 continue;
2736 }
2737
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002738 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002740 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 }
2742 if ((state.orientation != draw[i].orientation) ||
2743 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 }
2746 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 }
2749 }
2750 }
2751 ++i;
2752 }
2753
2754 // find displays that were added
2755 // (ie: in current state but not in drawing state)
2756 for (size_t i = 0; i < cc; i++) {
2757 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2758 const DisplayDeviceState& state(curr[i]);
2759
Lloyd Pique542307f2018-10-19 13:24:08 -07002760 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 sp<IGraphicBufferProducer> producer;
2762 sp<IGraphicBufferProducer> bqProducer;
2763 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002764 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002767 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 // Virtual displays without a surface are dormant:
2769 // they have external state (layer stack, projection,
2770 // etc.) but no internal state (i.e. a DisplayDevice).
2771 if (state.surface != nullptr) {
2772 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 int width = 0;
2775 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2776 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2777 int height = 0;
2778 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2779 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2780 int intFormat = 0;
2781 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2782 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002783 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002784
Dominik Laskowski075d3172018-05-24 15:50:06 -07002785 displayId =
2786 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002787 }
2788
2789 // TODO: Plumb requested format back up to consumer
2790
2791 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 bqProducer, bqConsumer,
2794 state.displayName);
2795
2796 dispSurface = vds;
2797 producer = vds;
2798 }
2799 } else {
2800 ALOGE_IF(state.surface != nullptr,
2801 "adding a supported display, but rendering "
2802 "surface is provided (%p), ignoring it",
2803 state.surface.get());
2804
Dominik Laskowski075d3172018-05-24 15:50:06 -07002805 displayId = state.displayId;
2806 LOG_ALWAYS_FATAL_IF(!displayId);
2807 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002808 producer = bqProducer;
2809 }
2810
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002811 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002812 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002813 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002814 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002815 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002816 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002817 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002818 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002819 }
2820 }
2821 }
2822 }
2823 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002824
2825 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002826}
2827
Mathias Agopian87baae12012-07-31 12:38:26 -07002828void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002829{
Dan Stoza7dde5992015-05-22 09:51:44 -07002830 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mCurrentState.traverseInZOrder([](Layer* layer) {
2832 layer->notifyAvailableFrames();
2833 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002834
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 /*
2836 * Traversal of the children
2837 * (perform the transaction for each of them if needed)
2838 */
2839
Mathias Agopian3559b072012-08-15 13:46:03 -07002840 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002841 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002843 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844
2845 const uint32_t flags = layer->doTransaction(0);
2846 if (flags & Layer::eVisibleRegion)
2847 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002848
2849 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002850 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002851 }
Robert Carr2047fae2016-11-28 14:09:09 -08002852 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 }
2854
2855 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002856 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 */
2858
Mathias Agopiane57f2922012-08-09 16:29:12 -07002859 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002860 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002861 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002862 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002864 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002865 // The transform hint might have changed for some layers
2866 // (either because a display has changed, or because a layer
2867 // as changed).
2868 //
2869 // Walk through all the layers in currentLayers,
2870 // and update their transform hint.
2871 //
2872 // If a layer is visible only on a single display, then that
2873 // display is used to calculate the hint, otherwise we use the
2874 // default display.
2875 //
2876 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2877 // the hint is set before we acquire a buffer from the surface texture.
2878 //
2879 // NOTE: layer transactions have taken place already, so we use their
2880 // drawing state. However, SurfaceFlinger's own transaction has not
2881 // happened yet, so we must use the current state layer list
2882 // (soon to become the drawing state list).
2883 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002885 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002886 bool first = true;
2887 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002888 // NOTE: we rely on the fact that layers are sorted by
2889 // layerStack first (so we don't have to traverse the list
2890 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002891 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002892 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002893 currentlayerStack = layerStack;
2894 // figure out if this layerstack is mirrored
2895 // (more than one display) if so, pick the default display,
2896 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002897 hintDisplay = nullptr;
2898 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002899 if (display->getCompositionDisplay()
2900 ->belongsInOutput(layer->getLayerStack(),
2901 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002902 if (hintDisplay) {
2903 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002904 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002905 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002907 }
2908 }
2909 }
2910 }
Chet Haase91d25932013-04-11 15:24:55 -07002911
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002913 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2914 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002915
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002916 // could be null when this layer is using a layerStack
2917 // that is not visible on any display. Also can occur at
2918 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002919 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002920 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002921
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002922 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002923 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002924 if (hintDisplay) {
2925 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002926 }
Robert Carr2047fae2016-11-28 14:09:09 -08002927
2928 first = false;
2929 });
Mathias Agopian84300952012-11-21 16:02:13 -08002930 }
2931
2932
Mathias Agopian3559b072012-08-15 13:46:03 -07002933 /*
2934 * Perform our own transaction if needed
2935 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936
2937 if (mLayersAdded) {
2938 mLayersAdded = false;
2939 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002940 mVisibleRegionsDirty = true;
2941 }
2942
2943 // some layers might have been removed, so
2944 // we need to update the regions they're exposing.
2945 if (mLayersRemoved) {
2946 mLayersRemoved = false;
2947 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002948 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002949 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002950 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002952 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002953 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002954 }
Robert Carr2047fae2016-11-28 14:09:09 -08002955 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 }
2957
Vishnu Nairec0ab382019-02-13 15:32:56 -08002958 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002960}
2961
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002962void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002963 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002964 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002965 return;
2966 }
2967
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002968 if (mVisibleRegionsDirty || mInputInfoChanged) {
2969 mInputInfoChanged = false;
2970 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002971 } else if (mInputWindowCommands.syncInputWindows) {
2972 // If the caller requested to sync input windows, but there are no
2973 // changes to input windows, notify immediately.
2974 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002975 }
2976
2977 executeInputWindowCommands();
2978}
2979
2980void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002981 Vector<InputWindowInfo> inputHandles;
2982
2983 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2984 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002985 // When calculating the screen bounds we ignore the transparent region since it may
2986 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002987 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002988 }
2989 });
chaviw291d88a2019-02-14 10:33:58 -08002990
2991 mInputFlinger->setInputWindows(inputHandles,
2992 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2993 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002994}
2995
Vishnu Nairec0ab382019-02-13 15:32:56 -08002996void SurfaceFlinger::commitInputWindowCommands() {
2997 mInputWindowCommands.merge(mPendingInputWindowCommands);
2998 mPendingInputWindowCommands.clear();
2999}
3000
chaviwfbe5d9c2018-12-26 12:23:37 -08003001void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003002 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3003 if (transferTouchFocusCommand.fromToken != nullptr &&
3004 transferTouchFocusCommand.toToken != nullptr &&
3005 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3006 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3007 transferTouchFocusCommand.toToken);
3008 }
3009 }
3010
3011 mInputWindowCommands.clear();
3012}
3013
Riley Andrews03414a12014-07-01 14:22:59 -07003014void SurfaceFlinger::updateCursorAsync()
3015{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003016 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003017 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003018 continue;
3019 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003021 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3022 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003023 }
3024 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003025}
3026
chaviw61626f22018-11-15 16:26:27 -08003027void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3028 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003029 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003030 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003031 }
3032 layer->releasePendingBuffer(systemTime());
3033}
3034
Mathias Agopian4fec8732012-06-29 14:12:52 -07003035void SurfaceFlinger::commitTransaction()
3036{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003037 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003038 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003039 for (const auto& l : mLayersPendingRemoval) {
3040 recordBufferingStats(l->getName().string(),
3041 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003042
Lloyd Pique07e33212018-12-18 16:33:37 -08003043 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003044 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003045 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003046 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003047 }
3048 mLayersPendingRemoval.clear();
3049 }
3050
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003051 // If this transaction is part of a window animation then the next frame
3052 // we composite should be considered an animation as well.
3053 mAnimCompositionPending = mAnimTransactionPending;
3054
Mathias Agopian4fec8732012-06-29 14:12:52 -07003055 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003056 // clear the "changed" flags in current state
3057 mCurrentState.colorMatrixChanged = false;
3058
Robert Carr1f0a16a2016-10-24 16:27:39 -07003059 mDrawingState.traverseInZOrder([](Layer* layer) {
3060 layer->commitChildList();
3061 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003062 mTransactionPending = false;
3063 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003064 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065}
3066
Lloyd Pique32cbe282018-10-19 13:09:22 -07003067void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003068 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003069 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003071
Lloyd Pique32cbe282018-10-19 13:09:22 -07003072 auto display = displayDevice->getCompositionDisplay();
3073
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 Region aboveOpaqueLayers;
3075 Region aboveCoveredLayers;
3076 Region dirty;
3077
Mathias Agopian87baae12012-07-31 12:38:26 -07003078 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079
Robert Carr2047fae2016-11-28 14:09:09 -08003080 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003081 // start with the whole surface at its current location
3082 const Layer::State& s(layer->getDrawingState());
3083
Jesse Hall01e29052013-02-19 16:13:35 -08003084 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003085 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003086 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003087 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003088
Mathias Agopianab028732010-03-16 16:41:46 -07003089 /*
3090 * opaqueRegion: area of a surface that is fully opaque.
3091 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003093
3094 /*
3095 * visibleRegion: area of a surface that is visible on screen
3096 * and not fully transparent. This is essentially the layer's
3097 * footprint minus the opaque regions above it.
3098 * Areas covered by a translucent surface are considered visible.
3099 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003101
3102 /*
3103 * coveredRegion: area of a surface that is covered by all
3104 * visible regions above it (which includes the translucent areas).
3105 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003107
Jesse Halla8026d22012-09-25 13:25:04 -07003108 /*
3109 * transparentRegion: area of a surface that is hinted to be completely
3110 * transparent. This is only used to tell when the layer has no visible
3111 * non-transparent regions and can be removed from the layer list. It
3112 * does not affect the visibleRegion of this layer or any layers
3113 * beneath it. The hint may not be correct if apps don't respect the
3114 * SurfaceView restrictions (which, sadly, some don't).
3115 */
3116 Region transparentRegion;
3117
Mathias Agopianab028732010-03-16 16:41:46 -07003118
3119 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003120 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003121 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003122 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003125 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003126 if (!visibleRegion.isEmpty()) {
3127 // Remove the transparent area from the visible region
3128 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003129 if (tr.preserveRects()) {
3130 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003131 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003132 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003133 // transformation too complex, can't do the
3134 // transparent region optimization.
3135 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003136 }
Mathias Agopianab028732010-03-16 16:41:46 -07003137 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138
Mathias Agopianab028732010-03-16 16:41:46 -07003139 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003140 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003141 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003142 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003143 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003144 // the opaque region is the layer's footprint
3145 opaqueRegion = visibleRegion;
3146 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 }
3148 }
3149
Robert Carre5f4f692018-01-12 13:12:28 -08003150 if (visibleRegion.isEmpty()) {
3151 layer->clearVisibilityRegions();
3152 return;
3153 }
3154
Mathias Agopianab028732010-03-16 16:41:46 -07003155 // Clip the covered region to the visible region
3156 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3157
3158 // Update aboveCoveredLayers for next (lower) layer
3159 aboveCoveredLayers.orSelf(visibleRegion);
3160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 // subtract the opaque region covered by the layers above us
3162 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163
3164 // compute this layer's dirty region
3165 if (layer->contentDirty) {
3166 // we need to invalidate the whole region
3167 dirty = visibleRegion;
3168 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003169 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 layer->contentDirty = false;
3171 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003172 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003173 * the exposed region consists of two components:
3174 * 1) what's VISIBLE now and was COVERED before
3175 * 2) what's EXPOSED now less what was EXPOSED before
3176 *
3177 * note that (1) is conservative, we start with the whole
3178 * visible region but only keep what used to be covered by
3179 * something -- which mean it may have been exposed.
3180 *
3181 * (2) handles areas that were not covered by anything but got
3182 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003183 */
Mathias Agopianab028732010-03-16 16:41:46 -07003184 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003185 const Region oldVisibleRegion = layer->visibleRegion;
3186 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003187 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3188 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189 }
3190 dirty.subtractSelf(aboveOpaqueLayers);
3191
3192 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003193 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194
Mathias Agopianab028732010-03-16 16:41:46 -07003195 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003197
Jesse Halla8026d22012-09-25 13:25:04 -07003198 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199 layer->setVisibleRegion(visibleRegion);
3200 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003201 layer->setVisibleNonTransparentRegion(
3202 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003203 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204
Mathias Agopian87baae12012-07-31 12:38:26 -07003205 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206}
3207
Chia-I Wuab0c3192017-08-01 11:29:00 -07003208void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003209 for (const auto& [token, displayDevice] : mDisplays) {
3210 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003211 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003212 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003213 }
3214 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003215}
3216
Daniel Solomon42d04562019-01-20 21:03:19 -08003217void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3218 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3219 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3220 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3221 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3222 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3223 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3224 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3225 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3226 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3227 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3228 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3229 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3230}
3231
Dan Stoza6b9454d2014-11-07 16:00:59 -08003232bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003233{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003234 ALOGV("handlePageFlip");
3235
Brian Andersond6927fb2016-07-23 23:37:30 -07003236 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237
Mathias Agopian4fec8732012-06-29 14:12:52 -07003238 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003239 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003240 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003241
3242 // Store the set of layers that need updates. This set must not change as
3243 // buffers are being latched, as this could result in a deadlock.
3244 // Example: Two producers share the same command stream and:
3245 // 1.) Layer 0 is latched
3246 // 2.) Layer 0 gets a new frame
3247 // 2.) Layer 1 gets a new frame
3248 // 3.) Layer 1 is latched.
3249 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3250 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003251 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003252 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003253 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003254 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003255 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003256 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003257 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003258 } else {
3259 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003260 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003261 } else {
3262 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263 }
Robert Carr2047fae2016-11-28 14:09:09 -08003264 });
3265
Lloyd Piquef2c79392018-12-20 16:23:33 -08003266 if (!mLayersWithQueuedFrames.empty()) {
3267 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3268 // writes to Layer current state. See also b/119481871
3269 Mutex::Autolock lock(mStateLock);
3270
3271 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003272 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003273 mLayersPendingRefresh.push_back(layer);
3274 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003275 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003276 if (layer->isBufferLatched()) {
3277 newDataLatched = true;
3278 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003279 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003280 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003281
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003282 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003283
3284 // If we will need to wake up at some time in the future to deal with a
3285 // queued frame that shouldn't be displayed during this vsync period, wake
3286 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003287 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003288 signalLayerUpdate();
3289 }
3290
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003291 // enter boot animation on first buffer latch
3292 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3293 ALOGI("Enter boot animation");
3294 mBootStage = BootStage::BOOTANIMATION;
3295 }
3296
Dan Stoza6b9454d2014-11-07 16:00:59 -08003297 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003298 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299}
3300
Mathias Agopianad456f92011-01-13 17:53:01 -08003301void SurfaceFlinger::invalidateHwcGeometry()
3302{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003303 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003304}
3305
Lloyd Pique32cbe282018-10-19 13:09:22 -07003306void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003307 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003308 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003309 // We only need to actually compose the display if:
3310 // 1) It is being handled by hardware composer, which may need this to
3311 // keep its virtual display state machine in sync, or
3312 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003313 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003314 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003315 return;
3316 }
3317
Dan Stoza9e56aa02015-11-02 13:00:03 -08003318 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003319 base::unique_fd readyFence;
3320 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003321
3322 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003323 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324}
3325
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003326bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3327 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003328 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003329 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003330
Lloyd Pique32cbe282018-10-19 13:09:22 -07003331 auto display = displayDevice->getCompositionDisplay();
3332 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003333 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003334
3335 const Region bounds(displayState.bounds);
3336 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003337 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003338 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003339
Peiyong Lind3788632018-09-18 16:01:31 -07003340 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003341 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003342
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003343 renderengine::DisplaySettings clientCompositionDisplay;
3344 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3345 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003346 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003347
Dan Stoza9e56aa02015-11-02 13:00:03 -08003348 if (hasClientComposition) {
3349 ALOGV("hasClientComposition");
3350
Alec Mouri6338c9d2019-02-07 16:57:51 -08003351 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003352 if (buf == nullptr) {
3353 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3354 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003355 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003356 return false;
3357 }
3358
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003359 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3360 clientCompositionDisplay.clip = displayState.scissor;
3361 const ui::Transform& displayTransform = displayState.transform;
3362 mat4 m;
3363 m[0][0] = displayTransform[0][0];
3364 m[0][1] = displayTransform[0][1];
3365 m[0][3] = displayTransform[0][2];
3366 m[1][0] = displayTransform[1][0];
3367 m[1][1] = displayTransform[1][1];
3368 m[1][3] = displayTransform[1][2];
3369 m[3][0] = displayTransform[2][0];
3370 m[3][1] = displayTransform[2][1];
3371 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003372 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003373
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003374 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003375 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003376 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003377 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003378 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003379 clientCompositionDisplay.outputDataspace = outputDataspace;
3380 clientCompositionDisplay.maxLuminance =
3381 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003382
Lloyd Pique441d5042018-10-18 16:49:51 -07003383 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003384 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003385 getHwComposer()
3386 .hasDisplayCapability(displayId,
3387 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003388
Peiyong Lind3788632018-09-18 16:01:31 -07003389 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003390 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3391 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003392 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003393 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003394 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003395
Mathias Agopian85d751c2012-08-29 16:59:24 -07003396 /*
3397 * and then, render the layers targeted at the framebuffer
3398 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003399
Dan Stoza9e56aa02015-11-02 13:00:03 -08003400 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003401 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003402 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003403 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 const Region viewportRegion(displayState.viewport);
3405 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003406 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003407 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003409 switch (layer->getCompositionType(displayDevice)) {
3410 case Hwc2::IComposerClient::Composition::CURSOR:
3411 case Hwc2::IComposerClient::Composition::DEVICE:
3412 case Hwc2::IComposerClient::Composition::SIDEBAND:
3413 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003414 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003415 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003416 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003417 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003418 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003419 // never clear the very first layer since we're
3420 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003421 renderengine::LayerSettings layerSettings;
3422 Region dummyRegion;
3423 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3424 layerSettings);
3425
3426 if (prepared) {
3427 layerSettings.source.buffer.buffer = nullptr;
3428 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3429 layerSettings.alpha = half(0.0);
3430 layerSettings.disableBlending = true;
3431 clientCompositionLayers.push_back(layerSettings);
3432 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003433 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003434 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003435 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003436 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003437 renderengine::LayerSettings layerSettings;
3438 bool prepared =
3439 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3440 if (prepared) {
3441 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003442 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003443 break;
3444 }
3445 default:
3446 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003447 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003448 } else {
3449 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003450 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003452 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003453
Alec Mouri820c7402019-01-23 13:02:39 -08003454 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003455 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003456 clientCompositionDisplay.clearRegion = clearRegion;
3457 if (!debugRegion.isEmpty()) {
3458 Region::const_iterator it = debugRegion.begin();
3459 Region::const_iterator end = debugRegion.end();
3460 while (it != end) {
3461 const Rect& rect = *it++;
3462 renderengine::LayerSettings layerSettings;
3463 layerSettings.source.buffer.buffer = nullptr;
3464 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3465 layerSettings.geometry.boundaries = rect.toFloatRect();
3466 layerSettings.alpha = half(1.0);
3467 clientCompositionLayers.push_back(layerSettings);
3468 }
3469 }
3470 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mouri6338c9d2019-02-07 16:57:51 -08003471 buf->getNativeBuffer(), std::move(fd), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003472 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003473 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003474}
3475
Chia-I Wu28e3a252018-09-07 12:05:02 -07003476void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003477 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003478 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003479}
3480
Dan Stoza7d89d062015-04-30 13:29:25 -07003481status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003482 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003483 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003484 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003485 const sp<Layer>& parent,
3486 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003487{
Dan Stoza7d89d062015-04-30 13:29:25 -07003488 // add this layer to the current state list
3489 {
3490 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003491 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003492 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3493 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003494 return NO_MEMORY;
3495 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003496 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003497 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003498 } else if (parent == nullptr) {
3499 lbc->onRemovedFromCurrentState();
3500 } else if (parent->isRemovedFromCurrentState()) {
3501 parent->addChild(lbc);
3502 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003503 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003504 parent->addChild(lbc);
3505 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003506
Yiwei Zhang243b3782018-05-15 17:40:04 -07003507 if (gbc != nullptr) {
3508 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3509 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3510 mMaxGraphicBufferProducerListSize,
3511 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3512 mGraphicBufferProducerList.size(),
3513 mMaxGraphicBufferProducerListSize, mNumLayers);
3514 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003515 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003516 }
3517
Mathias Agopian96f08192010-06-02 23:28:45 -07003518 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003519 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003520
Dan Stoza7d89d062015-04-30 13:29:25 -07003521 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003522}
3523
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003524uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003525 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003526}
3527
Mathias Agopian3f844832013-08-07 21:24:32 -07003528uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003529 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530}
3531
Mathias Agopian3f844832013-08-07 21:24:32 -07003532uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003533 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003534}
3535
3536uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003537 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003538 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003539 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003540 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003541 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003542 }
3543 return old;
3544}
3545
Marissa Wall713b63f2018-10-17 15:42:43 -07003546bool SurfaceFlinger::flushTransactionQueues() {
3547 Mutex::Autolock _l(mStateLock);
3548 auto it = mTransactionQueues.begin();
3549 while (it != mTransactionQueues.end()) {
3550 auto& [applyToken, transactionQueue] = *it;
3551
3552 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003553 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3554 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003555 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003556 break;
3557 }
Robert Carr14167e02019-02-13 13:50:55 -08003558 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003559 transactionQueue.pop();
3560 }
3561
3562 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3563 }
3564 return mTransactionQueues.empty();
3565}
3566
chaviwca27f252018-02-06 16:46:39 -08003567bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3568 for (const ComposerState& state : states) {
3569 // Here we need to check that the interface we're given is indeed
3570 // one of our own. A malicious client could give us a nullptr
3571 // IInterface, or one of its own or even one of our own but a
3572 // different type. All these situations would cause us to crash.
3573 if (state.client == nullptr) {
3574 return true;
3575 }
3576
3577 sp<IBinder> binder = IInterface::asBinder(state.client);
3578 if (binder == nullptr) {
3579 return true;
3580 }
3581
3582 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3583 return true;
3584 }
3585 }
3586 return false;
3587}
3588
Marissa Wall17b4e452018-12-26 16:32:34 -08003589bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3590 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003591 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003592 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3593 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3594 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3595 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3596 return false;
3597 }
3598
Marissa Wall713b63f2018-10-17 15:42:43 -07003599 for (const ComposerState& state : states) {
3600 const layer_state_t& s = state.state;
3601 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3602 continue;
3603 }
3604 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003605 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003606 }
3607 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003608 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003609}
3610
3611void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3612 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003613 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003614 const InputWindowCommands& inputWindowCommands,
3615 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003616 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003617
3618 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3619
Mathias Agopian698c0872011-06-28 19:09:31 -07003620 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003621
chaviwca27f252018-02-06 16:46:39 -08003622 if (containsAnyInvalidClientState(states)) {
3623 return;
3624 }
3625
Marissa Wall713b63f2018-10-17 15:42:43 -07003626 // If its TransactionQueue already has a pending TransactionState or if it is pending
3627 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003628 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003629 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3630 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003631 setTransactionFlags(eTransactionNeeded);
3632 return;
3633 }
3634
Robert Carr14167e02019-02-13 13:50:55 -08003635 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003636}
3637
3638void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003639 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003640 const InputWindowCommands& inputWindowCommands,
3641 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003642 uint32_t transactionFlags = 0;
3643
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003644 if (flags & eAnimation) {
3645 // For window updates that are part of an animation we must wait for
3646 // previous animation "frames" to be handled.
3647 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003648 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003649 if (CC_UNLIKELY(err != NO_ERROR)) {
3650 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003651 // caller after a few seconds.
3652 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3653 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003654 mAnimTransactionPending = false;
3655 break;
3656 }
3657 }
3658 }
3659
chaviwca27f252018-02-06 16:46:39 -08003660 for (const DisplayState& display : displays) {
3661 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003662 }
3663
Marissa Walle2ffb422018-10-12 11:33:52 -07003664 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003665 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003666 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003667 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003668 // If the state doesn't require a traversal and there are callbacks, send them now
3669 if (!(clientStateFlags & eTraversalNeeded)) {
3670 mTransactionCompletedThread.sendCallbacks();
3671 }
3672 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003673
chaviw273171b2018-12-26 11:46:30 -08003674 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3675
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003676 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3677 // anyway. This can be used as a flush mechanism for previous async transactions.
3678 // Empty animation transaction can be used to simulate back-pressure, so also force a
3679 // transaction for empty animation transactions.
3680 if (transactionFlags == 0 &&
3681 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003682 transactionFlags = eTransactionNeeded;
3683 }
3684
Mathias Agopian386aa982011-11-07 21:58:03 -08003685 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003686 if (mInterceptor->isEnabled()) {
3687 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003688 }
Irvel468051e2016-06-13 16:44:44 -07003689
Mathias Agopian386aa982011-11-07 21:58:03 -08003690 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003691 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3692 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003693 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003694
3695 // if this is a synchronous transaction, wait for it to take effect
3696 // before returning.
3697 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003698 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003699 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003700 if (flags & eAnimation) {
3701 mAnimTransactionPending = true;
3702 }
chaviw95ef3c42019-02-14 10:55:09 -08003703
3704 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3705 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003706 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3707 if (CC_UNLIKELY(err != NO_ERROR)) {
3708 // just in case something goes wrong in SF, return to the
3709 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003710 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3711 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003712 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003713 break;
3714 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 }
3717}
3718
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003719uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3720 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3721 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003722
Mathias Agopiane57f2922012-08-09 16:29:12 -07003723 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003724 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3725
3726 const uint32_t what = s.what;
3727 if (what & DisplayState::eSurfaceChanged) {
3728 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3729 state.surface = s.surface;
3730 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003731 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003732 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003733 if (what & DisplayState::eLayerStackChanged) {
3734 if (state.layerStack != s.layerStack) {
3735 state.layerStack = s.layerStack;
3736 flags |= eDisplayTransactionNeeded;
3737 }
3738 }
3739 if (what & DisplayState::eDisplayProjectionChanged) {
3740 if (state.orientation != s.orientation) {
3741 state.orientation = s.orientation;
3742 flags |= eDisplayTransactionNeeded;
3743 }
3744 if (state.frame != s.frame) {
3745 state.frame = s.frame;
3746 flags |= eDisplayTransactionNeeded;
3747 }
3748 if (state.viewport != s.viewport) {
3749 state.viewport = s.viewport;
3750 flags |= eDisplayTransactionNeeded;
3751 }
3752 }
3753 if (what & DisplayState::eDisplaySizeChanged) {
3754 if (state.width != s.width) {
3755 state.width = s.width;
3756 flags |= eDisplayTransactionNeeded;
3757 }
3758 if (state.height != s.height) {
3759 state.height = s.height;
3760 flags |= eDisplayTransactionNeeded;
3761 }
3762 }
3763
Mathias Agopiane57f2922012-08-09 16:29:12 -07003764 return flags;
3765}
3766
Robert Carr14167e02019-02-13 13:50:55 -08003767bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003768 IPCThreadState* ipc = IPCThreadState::self();
3769 const int pid = ipc->getCallingPid();
3770 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003771 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003772 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003773 return false;
3774 }
3775 return true;
3776}
3777
Robert Carr14167e02019-02-13 13:50:55 -08003778uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3779 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003780 const layer_state_t& s = composerState.state;
3781 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3782
Mathias Agopian13127d82013-03-05 17:47:11 -08003783 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003784 if (layer == nullptr) {
3785 return 0;
3786 }
3787
chaviw8b3871a2017-11-01 17:41:01 -07003788 uint32_t flags = 0;
3789
Garfield Tan8a3083e2018-12-03 13:21:07 -08003790 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003791 bool geometryAppliesWithResize =
3792 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003793
3794 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3795 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003796 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003797 layer->pushPendingState();
3798 }
3799
chaviw8b3871a2017-11-01 17:41:01 -07003800 if (what & layer_state_t::ePositionChanged) {
3801 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3802 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003803 }
chaviw8b3871a2017-11-01 17:41:01 -07003804 }
3805 if (what & layer_state_t::eLayerChanged) {
3806 // NOTE: index needs to be calculated before we update the state
3807 const auto& p = layer->getParent();
3808 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003809 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003810 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003811 mCurrentState.layersSortedByZ.removeAt(idx);
3812 mCurrentState.layersSortedByZ.add(layer);
3813 // we need traversal (state changed)
3814 // AND transaction (list changed)
3815 flags |= eTransactionNeeded|eTraversalNeeded;
3816 }
chaviw8b3871a2017-11-01 17:41:01 -07003817 } else {
3818 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003819 flags |= eTransactionNeeded|eTraversalNeeded;
3820 }
3821 }
chaviw8b3871a2017-11-01 17:41:01 -07003822 }
3823 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003824 // NOTE: index needs to be calculated before we update the state
3825 const auto& p = layer->getParent();
3826 if (p == nullptr) {
3827 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3828 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3829 mCurrentState.layersSortedByZ.removeAt(idx);
3830 mCurrentState.layersSortedByZ.add(layer);
3831 // we need traversal (state changed)
3832 // AND transaction (list changed)
3833 flags |= eTransactionNeeded|eTraversalNeeded;
3834 }
3835 } else {
3836 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3837 flags |= eTransactionNeeded|eTraversalNeeded;
3838 }
chaviw8b3871a2017-11-01 17:41:01 -07003839 }
3840 }
3841 if (what & layer_state_t::eSizeChanged) {
3842 if (layer->setSize(s.w, s.h)) {
3843 flags |= eTraversalNeeded;
3844 }
3845 }
3846 if (what & layer_state_t::eAlphaChanged) {
3847 if (layer->setAlpha(s.alpha))
3848 flags |= eTraversalNeeded;
3849 }
3850 if (what & layer_state_t::eColorChanged) {
3851 if (layer->setColor(s.color))
3852 flags |= eTraversalNeeded;
3853 }
Peiyong Lind3788632018-09-18 16:01:31 -07003854 if (what & layer_state_t::eColorTransformChanged) {
3855 if (layer->setColorTransform(s.colorTransform)) {
3856 flags |= eTraversalNeeded;
3857 }
3858 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003859 if (what & layer_state_t::eBackgroundColorChanged) {
3860 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3861 flags |= eTraversalNeeded;
3862 }
3863 }
chaviw8b3871a2017-11-01 17:41:01 -07003864 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003865 // TODO: b/109894387
3866 //
3867 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3868 // rotation. To see the problem observe that if we have a square parent, and a child
3869 // of the same size, then we rotate the child 45 degrees around it's center, the child
3870 // must now be cropped to a non rectangular 8 sided region.
3871 //
3872 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3873 // private API, and the WindowManager only uses rotation in one case, which is on a top
3874 // level layer in which cropping is not an issue.
3875 //
3876 // However given that abuse of rotation matrices could lead to surfaces extending outside
3877 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3878 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3879 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003880 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003881 flags |= eTraversalNeeded;
3882 }
3883 if (what & layer_state_t::eTransparentRegionChanged) {
3884 if (layer->setTransparentRegionHint(s.transparentRegion))
3885 flags |= eTraversalNeeded;
3886 }
3887 if (what & layer_state_t::eFlagsChanged) {
3888 if (layer->setFlags(s.flags, s.mask))
3889 flags |= eTraversalNeeded;
3890 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003891 if (what & layer_state_t::eCropChanged_legacy) {
3892 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003893 flags |= eTraversalNeeded;
3894 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003895 if (what & layer_state_t::eCornerRadiusChanged) {
3896 if (layer->setCornerRadius(s.cornerRadius))
3897 flags |= eTraversalNeeded;
3898 }
chaviw8b3871a2017-11-01 17:41:01 -07003899 if (what & layer_state_t::eLayerStackChanged) {
3900 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3901 // We only allow setting layer stacks for top level layers,
3902 // everything else inherits layer stack from its parent.
3903 if (layer->hasParent()) {
3904 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3905 layer->getName().string());
3906 } else if (idx < 0) {
3907 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3908 "that also does not appear in the top level layer list. Something"
3909 " has gone wrong.", layer->getName().string());
3910 } else if (layer->setLayerStack(s.layerStack)) {
3911 mCurrentState.layersSortedByZ.removeAt(idx);
3912 mCurrentState.layersSortedByZ.add(layer);
3913 // we need traversal (state changed)
3914 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003915 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003916 }
3917 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003918 if (what & layer_state_t::eDeferTransaction_legacy) {
3919 if (s.barrierHandle_legacy != nullptr) {
3920 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3921 } else if (s.barrierGbp_legacy != nullptr) {
3922 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003923 if (authenticateSurfaceTextureLocked(gbp)) {
3924 const auto& otherLayer =
3925 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003926 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003927 } else {
3928 ALOGE("Attempt to defer transaction to to an"
3929 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003930 }
3931 }
chaviw8b3871a2017-11-01 17:41:01 -07003932 // We don't trigger a traversal here because if no other state is
3933 // changed, we don't want this to cause any more work
3934 }
3935 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003936 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003937 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003938 if (!hadParent) {
3939 mCurrentState.layersSortedByZ.remove(layer);
3940 }
chaviw8b3871a2017-11-01 17:41:01 -07003941 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003942 }
chaviw8b3871a2017-11-01 17:41:01 -07003943 }
3944 if (what & layer_state_t::eReparentChildren) {
3945 if (layer->reparentChildren(s.reparentHandle)) {
3946 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003947 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003948 }
chaviw8b3871a2017-11-01 17:41:01 -07003949 if (what & layer_state_t::eDetachChildren) {
3950 layer->detachChildren();
3951 }
3952 if (what & layer_state_t::eOverrideScalingModeChanged) {
3953 layer->setOverrideScalingMode(s.overrideScalingMode);
3954 // We don't trigger a traversal here because if no other state is
3955 // changed, we don't want this to cause any more work
3956 }
Marissa Wall61c58622018-07-18 10:12:20 -07003957 if (what & layer_state_t::eTransformChanged) {
3958 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3961 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3962 flags |= eTraversalNeeded;
3963 }
3964 if (what & layer_state_t::eCropChanged) {
3965 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3966 }
Marissa Wall861616d2018-10-22 12:52:23 -07003967 if (what & layer_state_t::eFrameChanged) {
3968 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3969 }
Marissa Wall61c58622018-07-18 10:12:20 -07003970 if (what & layer_state_t::eAcquireFenceChanged) {
3971 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3972 }
3973 if (what & layer_state_t::eDataspaceChanged) {
3974 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3975 }
3976 if (what & layer_state_t::eHdrMetadataChanged) {
3977 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3978 }
3979 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3980 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3981 }
3982 if (what & layer_state_t::eApiChanged) {
3983 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3984 }
3985 if (what & layer_state_t::eSidebandStreamChanged) {
3986 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3987 }
Robert Carr720e5062018-07-30 17:45:14 -07003988 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003989 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3990 layer->setInputInfo(s.inputInfo);
3991 flags |= eTraversalNeeded;
3992 } else {
3993 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3994 }
Robert Carr720e5062018-07-30 17:45:14 -07003995 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003996 if (what & layer_state_t::eMetadataChanged) {
3997 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3998 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003999 std::vector<sp<CallbackHandle>> callbackHandles;
4000 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4001 mTransactionCompletedThread.run();
4002 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4003 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4004 }
4005 }
Marissa Wall73411622019-01-25 10:45:41 -08004006
4007 if (what & layer_state_t::eBufferChanged) {
4008 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4009 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4010 s.buffer);
4011 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004012 if (what & layer_state_t::eCachedBufferChanged) {
4013 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004014 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4015 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004016 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4017 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004018 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4019 // Do not put anything that updates layer state or modifies flags after
4020 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004021 return flags;
4022}
4023
chaviw273171b2018-12-26 11:46:30 -08004024uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4025 uint32_t flags = 0;
4026 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4027 flags |= eTraversalNeeded;
4028 }
4029
chaviwa911b102019-02-14 10:18:33 -08004030 if (inputWindowCommands.syncInputWindows) {
4031 flags |= eTraversalNeeded;
4032 }
4033
Vishnu Nairec0ab382019-02-13 15:32:56 -08004034 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004035 return flags;
4036}
4037
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004038status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4039 uint32_t h, PixelFormat format, uint32_t flags,
4040 LayerMetadata metadata, sp<IBinder>* handle,
4041 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004042 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004043 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004044 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004045 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004046 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004047
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004048 status_t result = NO_ERROR;
4049
4050 sp<Layer> layer;
4051
Cody Northropbc755282017-03-31 12:00:08 -06004052 String8 uniqueName = getUniqueLayerName(name);
4053
Mathias Agopian3165cc22012-08-08 19:42:09 -07004054 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004055 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004056 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4057 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004058
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004060 case ISurfaceComposerClient::eFXSurfaceBufferState:
4061 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4062 break;
chaviw13fdc492017-06-27 12:40:18 -07004063 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004064 // check if buffer size is set for color layer.
4065 if (w > 0 || h > 0) {
4066 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4067 int(w), int(h));
4068 return BAD_VALUE;
4069 }
4070
chaviw13fdc492017-06-27 12:40:18 -07004071 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004072 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004073 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004075 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004076 // check if buffer size is set for container layer.
4077 if (w > 0 || h > 0) {
4078 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4079 int(w), int(h));
4080 return BAD_VALUE;
4081 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004082 result = createContainerLayer(client,
4083 uniqueName, w, h, flags,
4084 handle, &layer);
4085 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004086 default:
4087 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 break;
4089 }
4090
Dan Stoza7d89d062015-04-30 13:29:25 -07004091 if (result != NO_ERROR) {
4092 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004093 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004094
Chia-I Wuab0c3192017-08-01 11:29:00 -07004095 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4096 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004097 if (metadata.has(METADATA_WINDOW_TYPE)) {
4098 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4099 if (windowType == 441731) {
4100 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4101 layer->setPrimaryDisplayOnly();
4102 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004103 }
4104
Evan Roskyef876c92019-01-25 17:46:06 -08004105 layer->setMetadata(metadata);
Albert Chaulk479c60c2017-01-27 14:21:34 -05004106
Robert Carrb89ea9d2018-12-10 13:01:14 -08004107 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4108 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4109 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004110 if (result != NO_ERROR) {
4111 return result;
4112 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004113 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004114
4115 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004116 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004117}
4118
Cody Northropbc755282017-03-31 12:00:08 -06004119String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4120{
4121 bool matchFound = true;
4122 uint32_t dupeCounter = 0;
4123
4124 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4125 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4126
Dan Stoza436ccf32018-06-21 12:10:12 -07004127 // Grab the state lock since we're accessing mCurrentState
4128 Mutex::Autolock lock(mStateLock);
4129
Cody Northropbc755282017-03-31 12:00:08 -06004130 // Loop over layers until we're sure there is no matching name
4131 while (matchFound) {
4132 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004133 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004134 if (layer->getName() == uniqueName) {
4135 matchFound = true;
4136 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4137 }
4138 });
4139 }
4140
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004141 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4142 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004143
4144 return uniqueName;
4145}
4146
Marissa Wallfd668622018-05-10 10:21:13 -07004147status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4148 uint32_t w, uint32_t h, uint32_t flags,
4149 PixelFormat& format, sp<IBinder>* handle,
4150 sp<IGraphicBufferProducer>* gbp,
4151 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004153 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004154 case PIXEL_FORMAT_TRANSPARENT:
4155 case PIXEL_FORMAT_TRANSLUCENT:
4156 format = PIXEL_FORMAT_RGBA_8888;
4157 break;
4158 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004159 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004160 break;
4161 }
4162
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004163 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004164 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004165 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004166 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004167 *handle = layer->getHandle();
4168 *gbp = layer->getProducer();
4169 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004170 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004171
Marissa Wallfd668622018-05-10 10:21:13 -07004172 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004173 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004174}
4175
Marissa Wall61c58622018-07-18 10:12:20 -07004176status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4177 uint32_t w, uint32_t h, uint32_t flags,
4178 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004179 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004180 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004181 *handle = layer->getHandle();
4182 *outLayer = layer;
4183
4184 return NO_ERROR;
4185}
4186
chaviw13fdc492017-06-27 12:40:18 -07004187status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004189 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004191 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004192 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004193 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004194}
4195
Robert Carr6b3f6c52018-08-13 13:05:17 -07004196status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4197 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4198 sp<IBinder>* handle, sp<Layer>* outLayer)
4199{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004200 *outLayer =
4201 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004202 *handle = (*outLayer)->getHandle();
4203 return NO_ERROR;
4204}
4205
4206
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004207void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004208 mLayersPendingRemoval.add(layer);
4209 mLayersRemoved = true;
4210 setTransactionFlags(eTransactionNeeded);
4211}
4212
Robert Carr695d5282018-12-18 15:27:58 -08004213void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004214{
Robert Carr2e102c92018-10-23 12:11:15 -07004215 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004216 // If a layer has a parent, we allow it to out-live it's handle
4217 // with the idea that the parent holds a reference and will eventually
4218 // be cleaned up. However no one cleans up the top-level so we do so
4219 // here.
4220 if (layer->getParent() == nullptr) {
4221 mCurrentState.layersSortedByZ.remove(layer);
4222 }
4223 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004224 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004225}
4226
Mathias Agopianb60314a2012-04-10 22:09:54 -07004227// ---------------------------------------------------------------------------
4228
Andy McFadden13a082e2012-08-24 10:16:42 -07004229void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004230 const auto display = getDefaultDisplayDeviceLocked();
4231 if (!display) return;
4232
4233 const sp<IBinder> token = display->getDisplayToken().promote();
4234 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004235
Jesse Hall01e29052013-02-19 16:13:35 -08004236 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004237 Vector<ComposerState> state;
4238 Vector<DisplayState> displays;
4239 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004240 d.what = DisplayState::eDisplayProjectionChanged |
4241 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004242 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004243 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004244 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004245 d.frame.makeInvalid();
4246 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004247 d.width = 0;
4248 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004249 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004250 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004251
Dominik Laskowskie9774092018-12-11 10:04:24 -08004252 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004253
Dominik Laskowski83b88212018-12-11 13:34:06 -08004254 const nsecs_t vsyncPeriod = getVsyncPeriod();
4255 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004256
Brian Andersond0010582017-03-07 13:20:31 -08004257 // Use phase of 0 since phase is not known.
4258 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004259 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004260 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004261}
4262
4263void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004264 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004265 postMessageAsync(
4266 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004267}
4268
Dominik Laskowskie9774092018-12-11 10:04:24 -08004269void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004270 if (display->isVirtual()) {
4271 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004272 return;
4273 }
4274
Dominik Laskowski075d3172018-05-24 15:50:06 -07004275 const auto displayId = display->getId();
4276 LOG_ALWAYS_FATAL_IF(!displayId);
4277
Dominik Laskowski34157762018-10-31 13:07:19 -07004278 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004279
4280 int currentMode = display->getPowerMode();
4281 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004282 return;
4283 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004285 display->setPowerMode(mode);
4286
Lloyd Pique4dccc412018-01-22 17:21:36 -08004287 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004288 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004289 }
4290
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004291 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004292 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004294 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004295 mScheduler->onScreenAcquired(mAppConnectionHandle);
4296 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004298
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004299 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004300 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004301 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004302
4303 struct sched_param param = {0};
4304 param.sched_priority = 1;
4305 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4306 ALOGW("Couldn't set SCHED_FIFO on display on");
4307 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004308 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004309 // Turn off the display
4310 struct sched_param param = {0};
4311 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4312 ALOGW("Couldn't set SCHED_OTHER on display off");
4313 }
4314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004316 mScheduler->disableHardwareVsync(true);
4317 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004318 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004319
Dominik Laskowski075d3172018-05-24 15:50:06 -07004320 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004321 mVisibleRegionsDirty = true;
4322 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004323 } else if (mode == HWC_POWER_MODE_DOZE ||
4324 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004325 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004326 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004328 mScheduler->onScreenAcquired(mAppConnectionHandle);
4329 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004330 }
4331 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4332 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004333 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004334 mScheduler->disableHardwareVsync(true);
4335 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004336 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004337 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004338 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004339 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004340 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004341 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004342
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004343 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004344 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004345 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004346 // Update refresh rate stats.
4347 mRefreshRateStats->setPowerMode(mode);
4348 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004349 }
4350
Dominik Laskowski34157762018-10-31 13:07:19 -07004351 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004352}
4353
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004354void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004355 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004356 const auto display = getDisplayDevice(displayToken);
4357 if (!display) {
4358 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4359 displayToken.get());
4360 } else if (display->isVirtual()) {
4361 ALOGW("Attempt to set power mode %d for virtual display", mode);
4362 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004363 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004364 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004365 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004366}
4367
4368// ---------------------------------------------------------------------------
4369
Dominik Laskowskic2867142019-01-21 11:33:38 -08004370status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4371 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004372 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004373
Mathias Agopianbd115332013-04-18 16:41:04 -07004374 IPCThreadState* ipc = IPCThreadState::self();
4375 const int pid = ipc->getCallingPid();
4376 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004377
Mathias Agopianbd115332013-04-18 16:41:04 -07004378 if ((uid != AID_SHELL) &&
4379 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4381 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004382 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004383 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004384 // (this would indicate SF is stuck, but we want to be able to
4385 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004386 status_t err = mStateLock.timedLock(s2ns(1));
4387 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004388 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004389 StringAppendF(&result,
4390 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4391 "(no locks held)\n",
4392 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004393 }
4394
Dominik Laskowskic2867142019-01-21 11:33:38 -08004395 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004396
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397 static const std::unordered_map<std::string, Dumper> dumpers = {
4398 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4399 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4400 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004401 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004402 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004403 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004404 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4405 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004406 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4407 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4408 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4409 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4410 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4411 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004412 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004413 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4414 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004415
Dominik Laskowskic2867142019-01-21 11:33:38 -08004416 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4419 (it->second)(args, asProto, result);
4420 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004421 if (asProto) {
4422 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4423 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4424 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004426 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004427 }
4428
Mathias Agopian9795c422009-08-26 16:36:26 -07004429 if (locked) {
4430 mStateLock.unlock();
4431 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434 return NO_ERROR;
4435}
4436
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004438 mCurrentState.traverseInZOrder(
4439 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004440}
4441
Dominik Laskowskic2867142019-01-21 11:33:38 -08004442void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004443 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004444
Dominik Laskowskic2867142019-01-21 11:33:38 -08004445 if (args.size() > 1) {
4446 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004447 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004448 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004449 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004450 }
Robert Carr2047fae2016-11-28 14:09:09 -08004451 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004452 } else {
4453 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454 }
4455}
4456
Dominik Laskowskic2867142019-01-21 11:33:38 -08004457void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004458 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004459 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004460 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004461 }
Robert Carr2047fae2016-11-28 14:09:09 -08004462 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004463
Svetoslavd85084b2014-03-20 10:28:31 -07004464 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004465}
4466
Dominik Laskowskic2867142019-01-21 11:33:38 -08004467void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4468 mTimeStats->parseArgs(asProto, args, result);
4469}
4470
Jamie Gennis6547ff42013-07-16 20:12:42 -07004471// This should only be called from the main thread. Otherwise it would need
4472// the lock and should use mCurrentState rather than mDrawingState.
4473void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004474 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004475 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004476 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004477
4478 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4479}
4480
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004482 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004483
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004484 if (isLayerTripleBufferingDisabled())
4485 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004486
Yiwei Zhang5434a782018-12-05 18:06:32 -08004487 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4488 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4489 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4490 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4491 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4492 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004493 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004494}
4495
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004496void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004497 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004498 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004499 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004500 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004501
Ana Krulecba13ab32019-02-20 14:14:12 -08004502 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4503 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4504 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004505 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004506}
4507
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4509 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004510 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4511 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004512 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004513 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004515 }
David Sodman4a36e932017-11-07 14:29:47 -08004516 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004517 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004518 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4520 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004521}
4522
Dan Stozae77c7662016-05-13 11:37:28 -07004523void SurfaceFlinger::recordBufferingStats(const char* layerName,
4524 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004525 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4526 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004527 for (const auto& segment : history) {
4528 if (!segment.usedThirdBuffer) {
4529 stats.twoBufferTime += segment.totalTime;
4530 }
4531 if (segment.occupancyAverage < 1.0f) {
4532 stats.doubleBufferedTime += segment.totalTime;
4533 } else if (segment.occupancyAverage < 2.0f) {
4534 stats.tripleBufferedTime += segment.totalTime;
4535 }
4536 ++stats.numSegments;
4537 stats.totalTime += segment.totalTime;
4538 }
4539}
4540
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4542 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004543
4544 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4545 const size_t count = currentLayers.size();
4546 for (size_t i=0 ; i<count ; i++) {
4547 currentLayers[i]->dumpFrameEvents(result);
4548 }
4549}
4550
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004552 result.append("Buffering stats:\n");
4553 result.append(" [Layer name] <Active time> <Two buffer> "
4554 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004555 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004556 typedef std::tuple<std::string, float, float, float> BufferTuple;
4557 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004558 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004559 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004560 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004561 if (stats.numSegments == 0) {
4562 continue;
4563 }
4564 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4565 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4566 stats.totalTime;
4567 float doubleBufferRatio = static_cast<float>(
4568 stats.doubleBufferedTime) / stats.totalTime;
4569 float tripleBufferRatio = static_cast<float>(
4570 stats.tripleBufferedTime) / stats.totalTime;
4571 sorted.insert({activeTime, {name, twoBufferRatio,
4572 doubleBufferRatio, tripleBufferRatio}});
4573 }
4574 for (const auto& sortedPair : sorted) {
4575 float activeTime = sortedPair.first;
4576 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4578 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004579 }
4580 result.append("\n");
4581}
4582
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004584 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004585 const auto displayId = display->getId();
4586 if (!displayId) {
4587 continue;
4588 }
4589 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004590 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004591 continue;
4592 }
4593
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 StringAppendF(&result,
4595 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4596 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004597 uint8_t port;
4598 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004599 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004600 result.append("no identification data\n");
4601 continue;
4602 }
4603
4604 if (!isEdid(data)) {
4605 result.append("unknown identification data: ");
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
4613 const auto edid = parseEdid(data);
4614 if (!edid) {
4615 result.append("invalid EDID: ");
4616 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004618 }
4619 result.append("\n");
4620 continue;
4621 }
4622
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004624 result.append(edid->displayName.data(), edid->displayName.length());
4625 result.append("\"\n");
4626 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004627}
4628
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4630 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4631 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4632 StringAppendF(&result, "DisplayColorSetting: %s\n",
4633 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004634
4635 // TODO: print out if wide-color mode is active or not
4636
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004637 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004638 const auto displayId = display->getId();
4639 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004640 continue;
4641 }
4642
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004644 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004645 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004646 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004647 }
4648
Lloyd Pique32cbe282018-10-19 13:09:22 -07004649 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004650 StringAppendF(&result, " Current color mode: %s (%d)\n",
4651 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004652 }
4653 result.append("\n");
4654}
4655
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004656LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004657 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004658 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4659 const State& state = useDrawing ? mDrawingState : mCurrentState;
4660 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004661 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004662 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004663 });
4664
4665 return layersProto;
4666}
4667
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004668LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4669 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004670 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004671
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004672 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004673 resolution->set_w(displayDevice->getWidth());
4674 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004675
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004676 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004677 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004678
Lloyd Pique32cbe282018-10-19 13:09:22 -07004679 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4680 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4681 layersProto.set_global_transform(displayState.orientation);
4682
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004683 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004684 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004685 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004686 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004687 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004688 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004689 }
4690 });
4691
4692 return layersProto;
4693}
4694
Dominik Laskowskic2867142019-01-21 11:33:38 -08004695void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4696 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004697 Colorizer colorizer(colorize);
4698
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004699 // figure out if we're stuck somewhere
4700 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004702 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4703
4704 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004705 * Dump library configuration.
4706 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707
4708 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004709 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004710 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004711 appendSfConfigString(result);
4712 appendUiConfigString(result);
4713 appendGuiConfigString(result);
4714 result.append("\n");
4715
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004716 result.append("\nDisplay identification data:\n");
4717 dumpDisplayIdentificationData(result);
4718
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004719 result.append("\nWide-Color information:\n");
4720 dumpWideColorInfo(result);
4721
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004722 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004723 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004724 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004725 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004726 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004727
Andy McFadden41d67d72014-04-25 16:58:34 -07004728 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004729 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004730 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004731 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004732 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004733
Dan Stozab90cf072015-03-05 11:05:59 -08004734 dumpStaticScreenStats(result);
4735 result.append("\n");
4736
Yiwei Zhang5434a782018-12-05 18:06:32 -08004737 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004738
Dan Stozae77c7662016-05-13 11:37:28 -07004739 dumpBufferingStats(result);
4740
Andy McFadden4803b742012-09-24 19:07:20 -07004741 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742 * Dump the visible layer list
4743 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004744 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004745 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4746 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4747 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004749
Chia-I Wu2f884132018-09-13 15:17:58 -07004750 {
4751 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4752 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004753 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004754 result.append("\n");
4755 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
4757 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004758 * Dump Display state
4759 */
4760
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004761 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004762 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004763 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004764 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004765 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004766 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004767 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004768
4769 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004770 * Dump SurfaceFlinger global state
4771 */
4772
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004773 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004774 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004776
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004777 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
Dominik Laskowski075d3172018-05-24 15:50:06 -07004779 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004780 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4781 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4783 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004784 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 StringAppendF(&result,
4786 " transaction-flags : %08x\n"
4787 " gpu_to_cpu_unsupported : %d\n",
4788 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004789
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004790 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004791 displayId && getHwComposer().isConnected(*displayId)) {
4792 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 StringAppendF(&result,
4794 " refresh-rate : %f fps\n"
4795 " x-dpi : %f\n"
4796 " y-dpi : %f\n",
4797 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4798 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004799 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004800
Yiwei Zhang5434a782018-12-05 18:06:32 -08004801 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802
Dan Stozae22aec72016-08-01 13:20:59 -07004803 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004804 * Tracing state
4805 */
4806 mTracing.dump(result);
4807 result.append("\n");
4808
4809 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004810 * HWC layer minidump
4811 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004812 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004813 const auto displayId = display->getId();
4814 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004815 continue;
4816 }
4817
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004819 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004820 const sp<DisplayDevice> displayDevice = display;
4821 mCurrentState.traverseInZOrder(
4822 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004823 result.append("\n");
4824 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004825
4826 /*
4827 * Dump HWComposer state
4828 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004829 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004830 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004831 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004832 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004833 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004834 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835
4836 /*
4837 * Dump gralloc state
4838 */
4839 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4840 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004841
4842 /*
4843 * Dump VrFlinger state if in use.
4844 */
4845 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4846 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004847 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004848 result.append("\n");
4849 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004850
4851 /**
4852 * Scheduler dump state.
4853 */
Ana Krulecc2870422019-01-29 19:00:58 -08004854 result.append("\nScheduler state:\n");
4855 result.append(mScheduler->doDump() + "\n");
4856 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004857}
4858
Dominik Laskowski075d3172018-05-24 15:50:06 -07004859const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004860 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004861 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004862 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004863 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004864 }
4865 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004866
Dominik Laskowski34157762018-10-31 13:07:19 -07004867 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004868 static const Vector<sp<Layer>> empty;
4869 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004870}
4871
Chia-I Wu28f320b2018-05-03 11:02:56 -07004872void SurfaceFlinger::updateColorMatrixLocked() {
4873 mat4 colorMatrix;
4874 if (mGlobalSaturationFactor != 1.0f) {
4875 // Rec.709 luma coefficients
4876 float3 luminance{0.213f, 0.715f, 0.072f};
4877 luminance *= 1.0f - mGlobalSaturationFactor;
4878 mat4 saturationMatrix = mat4(
4879 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4880 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4881 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4882 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4883 );
4884 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4885 } else {
4886 colorMatrix = mClientColorMatrix * mDaltonizer();
4887 }
4888
4889 if (mCurrentState.colorMatrix != colorMatrix) {
4890 mCurrentState.colorMatrix = colorMatrix;
4891 mCurrentState.colorMatrixChanged = true;
4892 setTransactionFlags(eTransactionNeeded);
4893 }
4894}
4895
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004896status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897#pragma clang diagnostic push
4898#pragma clang diagnostic error "-Wswitch-enum"
4899 switch (static_cast<ISurfaceComposerTag>(code)) {
4900 // These methods should at minimum make sure that the client requested
4901 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004902 case BOOT_FINISHED:
4903 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 case CREATE_DISPLAY:
4905 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004906 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 case GET_ACTIVE_COLOR_MODE:
4908 case GET_ANIMATION_FRAME_STATS:
4909 case GET_HDR_CAPABILITIES:
4910 case SET_ACTIVE_CONFIG:
4911 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004912 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004913 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004914 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004915 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4916 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004917 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4918 IPCThreadState* ipc = IPCThreadState::self();
4919 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4920 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004921 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 }
Robert Carr1db73f62016-12-21 12:58:51 -08004923 return OK;
4924 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004926 IPCThreadState* ipc = IPCThreadState::self();
4927 const int pid = ipc->getCallingPid();
4928 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4930 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004931 return PERMISSION_DENIED;
4932 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004933 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004934 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004935 // Used by apps to hook Choreographer to SurfaceFlinger.
4936 case CREATE_DISPLAY_EVENT_CONNECTION:
4937 // The following calls are currently used by clients that do not
4938 // request necessary permissions. However, they do not expose any secret
4939 // information, so it is OK to pass them.
4940 case AUTHENTICATE_SURFACE:
4941 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004942 case GET_PHYSICAL_DISPLAY_IDS:
4943 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004944 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004945 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 case GET_DISPLAY_CONFIGS:
4947 case GET_DISPLAY_STATS:
4948 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4949 // Calling setTransactionState is safe, because you need to have been
4950 // granted a reference to Client* and Handle* to do anything with it.
4951 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004952 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004953 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004954 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004955 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004956 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957 return OK;
4958 }
4959 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004960 case CAPTURE_SCREEN:
4961 case ADD_REGION_SAMPLING_LISTENER:
4962 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004963 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004964 IPCThreadState* ipc = IPCThreadState::self();
4965 const int pid = ipc->getCallingPid();
4966 const int uid = ipc->getCallingUid();
4967 if ((uid != AID_GRAPHICS) &&
4968 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4969 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4970 return PERMISSION_DENIED;
4971 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972 return OK;
4973 }
4974 // The following codes are deprecated and should never be allowed to access SF.
4975 case CONNECT_DISPLAY_UNUSED:
4976 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4977 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4978 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004979 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981
4982 // These codes are used for the IBinder protocol to either interrogate the recipient
4983 // side of the transaction for its canonical interface descriptor or to dump its state.
4984 // We let them pass by default.
4985 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4986 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4987 code == IBinder::SYSPROPS_TRANSACTION) {
4988 return OK;
4989 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004990 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004992 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004993 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4994 return OK;
4995 }
4996 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4997 return PERMISSION_DENIED;
4998#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004999}
5000
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5002 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005003 status_t credentialCheck = CheckTransactCodeCredentials(code);
5004 if (credentialCheck != OK) {
5005 return credentialCheck;
5006 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005007
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5009 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005010 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005011 IPCThreadState* ipc = IPCThreadState::self();
5012 const int uid = ipc->getCallingUid();
5013 if (CC_UNLIKELY(uid != AID_SYSTEM
5014 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005015 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005016 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005017 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 return PERMISSION_DENIED;
5019 }
5020 int n;
5021 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005022 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005023 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 return NO_ERROR;
5025 case 1002: // SHOW_UPDATES
5026 n = data.readInt32();
5027 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005028 invalidateHwcGeometry();
5029 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005030 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005032 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005033 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005034 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005035 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005036 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005037 setTransactionFlags(
5038 eTransactionNeeded|
5039 eDisplayTransactionNeeded|
5040 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005041 return NO_ERROR;
5042 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005043 case 1006:{ // send empty update
5044 signalRefresh();
5045 return NO_ERROR;
5046 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005047 case 1008: // toggle use of hw composer
5048 n = data.readInt32();
5049 mDebugDisableHWC = n ? 1 : 0;
5050 invalidateHwcGeometry();
5051 repaintEverything();
5052 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005053 case 1009: // toggle use of transform hint
5054 n = data.readInt32();
5055 mDebugDisableTransformHint = n ? 1 : 0;
5056 invalidateHwcGeometry();
5057 repaintEverything();
5058 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005060 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005061 reply->writeInt32(0);
5062 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005063 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005064 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065 return NO_ERROR;
5066 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005067 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005068 if (!display) {
5069 return NAME_NOT_FOUND;
5070 }
5071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005072 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005073 return NO_ERROR;
5074 }
5075 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005076 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005077 // daltonize
5078 n = data.readInt32();
5079 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005080 case 1:
5081 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5082 break;
5083 case 2:
5084 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5085 break;
5086 case 3:
5087 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5088 break;
5089 default:
5090 mDaltonizer.setType(ColorBlindnessType::None);
5091 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005092 }
5093 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005094 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005095 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005096 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005097 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005098
5099 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005102 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005103 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005104 // apply a color matrix
5105 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005106 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005107 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005108 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005109 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005110 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005111 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005112 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005113 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005115 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005116
5117 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5118 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005119 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005120 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5121 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5122 }
5123
Chia-I Wu28f320b2018-05-03 11:02:56 -07005124 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005125 return NO_ERROR;
5126 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005127 // This is an experimental interface
5128 // Needs to be shifted to proper binder interface when we productize
5129 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005130 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005131 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005132 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005133 return NO_ERROR;
5134 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005135 case 1017: {
5136 n = data.readInt32();
5137 mForceFullDamage = static_cast<bool>(n);
5138 return NO_ERROR;
5139 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005140 case 1018: { // Modify Choreographer's phase offset
5141 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005142 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005143 return NO_ERROR;
5144 }
5145 case 1019: { // Modify SurfaceFlinger's phase offset
5146 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005147 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005148 return NO_ERROR;
5149 }
Irvel468051e2016-06-13 16:44:44 -07005150 case 1020: { // Layer updates interceptor
5151 n = data.readInt32();
5152 if (n) {
5153 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005154 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005155 }
5156 else{
5157 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005158 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005159 }
5160 return NO_ERROR;
5161 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005162 case 1021: { // Disable HWC virtual displays
5163 n = data.readInt32();
5164 mUseHwcVirtualDisplays = !n;
5165 return NO_ERROR;
5166 }
Romain Guy0147a172017-06-01 13:53:56 -07005167 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005168 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005169 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005170
Chia-I Wu28f320b2018-05-03 11:02:56 -07005171 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005172 return NO_ERROR;
5173 }
Romain Guy54f154a2017-10-24 21:40:32 +01005174 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005175 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005176 invalidateHwcGeometry();
5177 repaintEverything();
5178 return NO_ERROR;
5179 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005180 // Deprecate, use 1030 to check whether the device is color managed.
5181 case 1024: {
5182 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005183 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005184 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005185 n = data.readInt32();
5186 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005187 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005188 mTracing.enable();
5189 doTracing("tracing.enable");
5190 reply->writeInt32(NO_ERROR);
5191 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005192 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005193 status_t err = mTracing.disable();
5194 reply->writeInt32(err);
5195 }
5196 return NO_ERROR;
5197 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005198 case 1026: { // Get layer tracing status
5199 reply->writeBool(mTracing.isEnabled());
5200 return NO_ERROR;
5201 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005202 // Is a DisplayColorSetting supported?
5203 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005204 const auto display = getDefaultDisplayDevice();
5205 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005206 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005207 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005208
5209 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5210 switch (setting) {
5211 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005212 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005213 break;
5214 case DisplayColorSetting::UNMANAGED:
5215 reply->writeBool(true);
5216 break;
5217 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005218 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005219 break;
5220 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005221 reply->writeBool(
5222 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005223 break;
5224 }
5225 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005226 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005227 // Is VrFlinger active?
5228 case 1028: {
5229 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005230 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005231 return NO_ERROR;
5232 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005233 // Is device color managed?
5234 case 1030: {
5235 reply->writeBool(useColorManagement);
5236 return NO_ERROR;
5237 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005238 // Override default composition data space
5239 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5240 // && adb shell stop zygote && adb shell start zygote
5241 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5242 // adb shell stop zygote && adb shell start zygote
5243 case 1031: {
5244 Mutex::Autolock _l(mStateLock);
5245 n = data.readInt32();
5246 if (n) {
5247 n = data.readInt32();
5248 if (n) {
5249 Dataspace dataspace = static_cast<Dataspace>(n);
5250 if (!validateCompositionDataspace(dataspace)) {
5251 return BAD_VALUE;
5252 }
5253 mDefaultCompositionDataspace = dataspace;
5254 }
5255 n = data.readInt32();
5256 if (n) {
5257 Dataspace dataspace = static_cast<Dataspace>(n);
5258 if (!validateCompositionDataspace(dataspace)) {
5259 return BAD_VALUE;
5260 }
5261 mWideColorGamutCompositionDataspace = dataspace;
5262 }
5263 } else {
5264 // restore composition data space.
5265 mDefaultCompositionDataspace = defaultCompositionDataspace;
5266 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5267 }
5268 return NO_ERROR;
5269 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005270 }
5271 }
5272 return err;
5273}
5274
Steven Thomas6d8110b2017-08-31 18:24:21 -07005275void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005276 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005277 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005278}
5279
Ana Krulec7d1d6832018-12-27 11:10:09 -08005280void SurfaceFlinger::repaintEverythingForHWC() {
5281 mRepaintEverything = true;
5282 mEventQueue->invalidateForHWC();
5283}
5284
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005285// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5286class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005287public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5289 ~WindowDisconnector() {
5290 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005291 }
5292
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005293private:
5294 ANativeWindow* mWindow;
5295 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005296};
5297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005298status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005299 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5300 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005301 uint32_t reqWidth, uint32_t reqHeight,
5302 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005303 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005304 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005305
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005306 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005307
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005308 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5309
Chia-I Wu20261cb2018-08-23 12:55:44 -07005310 sp<DisplayDevice> display;
5311 {
5312 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005313
Chia-I Wu20261cb2018-08-23 12:55:44 -07005314 display = getDisplayDeviceLocked(displayToken);
5315 if (!display) return BAD_VALUE;
5316
Chia-I Wucb023152018-08-28 12:57:23 -07005317 // set the requested width/height to the logical display viewport size
5318 // by default
5319 if (reqWidth == 0 || reqHeight == 0) {
5320 reqWidth = uint32_t(display->getViewport().width());
5321 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005322 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005323 }
5324
Peiyong Lin0e003c92018-09-17 11:09:51 -07005325 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5326 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005327
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005328 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5329 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005330 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5331 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005332}
5333
5334status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005335 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5336 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005337 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005338 ATRACE_CALL();
5339
5340 class LayerRenderArea : public RenderArea {
5341 public:
Robert Carr578038f2018-03-09 12:25:24 -08005342 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005343 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5344 bool childrenOnly)
5345 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005346 mLayer(layer),
5347 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005348 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005349 mFlinger(flinger),
5350 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005351 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005352 Rect getBounds() const override {
5353 const Layer::State& layerState(mLayer->getDrawingState());
5354 return mLayer->getBufferSize(layerState);
5355 }
Marissa Wall61c58622018-07-18 10:12:20 -07005356 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005357 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005358 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005359 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005360 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005361 }
chaviwa76b2712017-09-20 12:02:26 -07005362 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005363 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005364 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005365 Rect getSourceCrop() const override {
5366 if (mCrop.isEmpty()) {
5367 return getBounds();
5368 } else {
5369 return mCrop;
5370 }
5371 }
Robert Carr578038f2018-03-09 12:25:24 -08005372 class ReparentForDrawing {
5373 public:
5374 const sp<Layer>& oldParent;
5375 const sp<Layer>& newParent;
5376
Vishnu Nair4351ad52019-02-11 14:13:02 -08005377 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5378 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005379 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005380 // Compute and cache the bounds for the new parent layer.
5381 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005382 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005383 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005384 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005385 };
5386
5387 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005388 const Rect sourceCrop = getSourceCrop();
5389 // no need to check rotation because there is none
5390 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5391 sourceCrop.height() != getReqHeight();
5392
Robert Carr578038f2018-03-09 12:25:24 -08005393 if (!mChildrenOnly) {
5394 mTransform = mLayer->getTransform().inverse();
5395 drawLayers();
5396 } else {
5397 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005398 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005399 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5400 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005401
Vishnu Nair4351ad52019-02-11 14:13:02 -08005402 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005403 drawLayers();
5404 }
5405 }
chaviwa76b2712017-09-20 12:02:26 -07005406
chaviwa76b2712017-09-20 12:02:26 -07005407 private:
chaviw7206d492017-11-10 16:16:12 -08005408 const sp<Layer> mLayer;
5409 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005410
5411 // In the "childrenOnly" case we reparent the children to a screenshot
5412 // layer which has no properties set and which does not draw.
5413 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005414 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005415 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005416
5417 SurfaceFlinger* mFlinger;
5418 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005419 };
5420
5421 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5422 auto parent = layerHandle->owner.promote();
5423
Robert Carr2e102c92018-10-23 12:11:15 -07005424 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005425 ALOGE("captureLayers called with a removed parent");
5426 return NAME_NOT_FOUND;
5427 }
5428
Robert Carr578038f2018-03-09 12:25:24 -08005429 const int uid = IPCThreadState::self()->getCallingUid();
5430 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005431 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005432 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5433 return PERMISSION_DENIED;
5434 }
5435
chaviw7206d492017-11-10 16:16:12 -08005436 Rect crop(sourceCrop);
5437 if (sourceCrop.width() <= 0) {
5438 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005439 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005440 }
5441
5442 if (sourceCrop.height() <= 0) {
5443 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005444 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005445 }
5446
5447 int32_t reqWidth = crop.width() * frameScale;
5448 int32_t reqHeight = crop.height() * frameScale;
5449
Chia-I Wu20261cb2018-08-23 12:55:44 -07005450 // really small crop or frameScale
5451 if (reqWidth <= 0) {
5452 reqWidth = 1;
5453 }
5454 if (reqHeight <= 0) {
5455 reqHeight = 1;
5456 }
5457
Peiyong Lin0e003c92018-09-17 11:09:51 -07005458 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005459
Robert Carr578038f2018-03-09 12:25:24 -08005460 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005461 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5462 if (!layer->isVisible()) {
5463 return;
Robert Carr578038f2018-03-09 12:25:24 -08005464 } else if (childrenOnly && layer == parent.get()) {
5465 return;
chaviwa76b2712017-09-20 12:02:26 -07005466 }
5467 visitor(layer);
5468 });
5469 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005470 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005471}
5472
5473status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5474 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005475 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005476 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005477 bool useIdentityTransform) {
5478 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005479
Peiyong Lin0e003c92018-09-17 11:09:51 -07005480 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005481 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5482 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005483 *outBuffer =
5484 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5485 static_cast<android_pixel_format>(reqPixelFormat), 1,
5486 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005487
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005488 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
Dan Stozaec460082018-12-17 15:35:09 -08005489}
5490
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005491status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5492 TraverseLayersFunction traverseLayers,
5493 const sp<GraphicBuffer>& buffer,
5494 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005495 // This mutex protects syncFd and captureResult for communication of the return values from the
5496 // main thread back to this Binder thread
5497 std::mutex captureMutex;
5498 std::condition_variable captureCondition;
5499 std::unique_lock<std::mutex> captureLock(captureMutex);
5500 int syncFd = -1;
5501 std::optional<status_t> captureResult;
5502
Robert Carr03480e22018-01-04 16:02:06 -08005503 const int uid = IPCThreadState::self()->getCallingUid();
5504 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5505
Dominik Laskowski8c001672018-05-30 16:52:06 -07005506 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507 // If there is a refresh pending, bug out early and tell the binder thread to try again
5508 // after the refresh.
5509 if (mRefreshPending) {
5510 ATRACE_NAME("Skipping screenshot for now");
5511 std::unique_lock<std::mutex> captureLock(captureMutex);
5512 captureResult = std::make_optional<status_t>(EAGAIN);
5513 captureCondition.notify_one();
5514 return;
5515 }
5516
5517 status_t result = NO_ERROR;
5518 int fd = -1;
5519 {
5520 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005521 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005522 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005523 useIdentityTransform, forSystem, &fd);
5524 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005525 }
5526
5527 {
5528 std::unique_lock<std::mutex> captureLock(captureMutex);
5529 syncFd = fd;
5530 captureResult = std::make_optional<status_t>(result);
5531 captureCondition.notify_one();
5532 }
5533 });
5534
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005535 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005536 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005537 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005538 while (*captureResult == EAGAIN) {
5539 captureResult.reset();
5540 result = postMessageAsync(message);
5541 if (result != NO_ERROR) {
5542 return result;
5543 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005544 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005545 }
5546 result = *captureResult;
5547 }
5548
5549 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005550 sync_wait(syncFd, -1);
5551 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005552 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005553
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005554 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005555}
5556
chaviwa76b2712017-09-20 12:02:26 -07005557void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005558 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005559 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5560 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005561 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005562
chaviwa76b2712017-09-20 12:02:26 -07005563 const auto reqWidth = renderArea.getReqWidth();
5564 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005565 const auto sourceCrop = renderArea.getSourceCrop();
5566 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005567
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005568 renderengine::DisplaySettings clientCompositionDisplay;
5569 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005570
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005571 // assume that bounds are never offset, and that they are the same as the
5572 // buffer bounds.
5573 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5574 ui::Transform transform = renderArea.getTransform();
5575 mat4 m;
5576 m[0][0] = transform[0][0];
5577 m[0][1] = transform[0][1];
5578 m[0][3] = transform[0][2];
5579 m[1][0] = transform[1][0];
5580 m[1][1] = transform[1][1];
5581 m[1][3] = transform[1][2];
5582 m[3][0] = transform[2][0];
5583 m[3][1] = transform[2][1];
5584 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005585
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005586 clientCompositionDisplay.globalTransform = m;
5587 mat4 rotMatrix;
5588 // Displacement for repositioning the clipping rectangle after rotating it
5589 // with the rotation hint.
5590 int displacementX = 0;
5591 int displacementY = 0;
5592 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5593 switch (rotation) {
5594 case ui::Transform::ROT_90:
5595 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5596 displacementX = reqWidth;
5597 break;
5598 case ui::Transform::ROT_180:
5599 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5600 displacementX = reqWidth;
5601 displacementY = reqHeight;
5602 break;
5603 case ui::Transform::ROT_270:
5604 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5605 displacementY = reqHeight;
5606 break;
5607 default:
5608 break;
5609 }
5610 // We need to transform the clipping window into the right spot.
5611 // First, rotate the clipping rectangle by the rotation hint to get the
5612 // right orientation
5613 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5614 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5615 const vec4 rotClipTL = rotMatrix * clipTL;
5616 const vec4 rotClipBR = rotMatrix * clipBR;
5617 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5618 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5619 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5620 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5621
5622 // Now reposition the clipping rectangle with the displacement vector
5623 // computed above.
5624 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5625
5626 clientCompositionDisplay.clip =
5627 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5628 newClipRight + displacementX, newClipBottom + displacementY);
5629
5630 // We need to perform the same transformation in layer space, so propagate
5631 // it to the global transform.
5632 mat4 clipTransform = displacementMat * rotMatrix;
5633 clientCompositionDisplay.globalTransform *= clipTransform;
5634 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5635 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005636
chaviw50da5042018-04-09 13:49:37 -07005637 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005638
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005639 renderengine::LayerSettings fillLayer;
5640 fillLayer.source.buffer.buffer = nullptr;
5641 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5642 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5643 fillLayer.alpha = half(alpha);
5644 clientCompositionLayers.push_back(fillLayer);
5645
5646 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005647 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005648 renderengine::LayerSettings layerSettings;
5649 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5650 layerSettings);
5651 if (prepared) {
5652 clientCompositionLayers.push_back(layerSettings);
5653 }
chaviwa76b2712017-09-20 12:02:26 -07005654 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005655
5656 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005657 // Use an empty fence for the buffer fence, since we just created the buffer so
5658 // there is no need for synchronization with the GPU.
5659 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005660 base::unique_fd drawFence;
5661 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005662 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005663
5664 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005665}
5666
chaviwa76b2712017-09-20 12:02:26 -07005667status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5668 TraverseLayersFunction traverseLayers,
5669 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005670 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005671 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005672 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005673 ATRACE_CALL();
5674
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005675 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005676
5677 traverseLayers([&](Layer* layer) {
5678 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5679 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005680
Robert Carr03480e22018-01-04 16:02:06 -08005681 // We allow the system server to take screenshots of secure layers for
5682 // use in situations like the Screen-rotation animation and place
5683 // the impetus on WindowManager to not persist them.
5684 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005685 ALOGW("FB is protected: PERMISSION_DENIED");
5686 return PERMISSION_DENIED;
5687 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005688 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005689 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005690}
5691
chaviw95ef3c42019-02-14 10:55:09 -08005692void SurfaceFlinger::setInputWindowsFinished() {
5693 Mutex::Autolock _l(mStateLock);
5694
5695 mPendingSyncInputWindows = false;
5696 mTransactionCV.broadcast();
5697}
chaviw5f21a5e2019-02-14 10:00:34 -08005698
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005699// ---------------------------------------------------------------------------
5700
Dan Stoza412903f2017-04-27 13:42:17 -07005701void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5702 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005703}
5704
Dan Stoza412903f2017-04-27 13:42:17 -07005705void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5706 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005707}
5708
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005709void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005710 const LayerVector::Visitor& visitor) {
5711 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005712 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005713 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005714 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005715 continue;
5716 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005717 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005718 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005719 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005720 return;
5721 }
chaviwa76b2712017-09-20 12:02:26 -07005722 if (!layer->isVisible()) {
5723 return;
5724 }
5725 visitor(layer);
5726 });
5727 }
5728}
5729
chaviw291d88a2019-02-14 10:33:58 -08005730// ----------------------------------------------------------------------------
5731
5732void SetInputWindowsListener::onSetInputWindowsFinished() {
5733 mFlinger->setInputWindowsFinished();
5734}
5735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005736}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005737
Lloyd Pique074e8122018-07-26 12:57:23 -07005738
Mathias Agopian3f844832013-08-07 21:24:32 -07005739#if defined(__gl_h_)
5740#error "don't include gl/gl.h in this file"
5741#endif
5742
5743#if defined(__gl2_h_)
5744#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005745#endif