blob: ff6660cd73173b2aaf4213efc7d73cb425b49270 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080065#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700113#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900115#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
chaviw1d044282017-09-27 12:19:28 -0700117#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900118#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700121
Jaesoo Lee43518572017-01-23 19:03:16 +0900122using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800125
Yiwei Zhang5434a782018-12-05 18:06:32 -0800126using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700127using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700128using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800129using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700130using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700131using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
134
Steven Thomasb02664d2017-07-26 18:48:28 -0700135namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700136
137#pragma clang diagnostic push
138#pragma clang diagnostic error "-Wswitch-enum"
139
140bool isWideColorMode(const ColorMode colorMode) {
141 switch (colorMode) {
142 case ColorMode::DISPLAY_P3:
143 case ColorMode::ADOBE_RGB:
144 case ColorMode::DCI_P3:
145 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700146 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700147 case ColorMode::BT2100_PQ:
148 case ColorMode::BT2100_HLG:
149 return true;
150 case ColorMode::NATIVE:
151 case ColorMode::STANDARD_BT601_625:
152 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
153 case ColorMode::STANDARD_BT601_525:
154 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
155 case ColorMode::STANDARD_BT709:
156 case ColorMode::SRGB:
157 return false;
158 }
159 return false;
160}
161
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700162ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
163 switch (rotation) {
164 case ISurfaceComposer::eRotateNone:
165 return ui::Transform::ROT_0;
166 case ISurfaceComposer::eRotate90:
167 return ui::Transform::ROT_90;
168 case ISurfaceComposer::eRotate180:
169 return ui::Transform::ROT_180;
170 case ISurfaceComposer::eRotate270:
171 return ui::Transform::ROT_270;
172 }
173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
174 return ui::Transform::ROT_0;
175}
176
Peiyong Linfca547f2018-07-09 13:03:33 -0700177#pragma clang diagnostic pop
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179class ConditionalLock {
180public:
181 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
182 if (lock) {
183 mMutex.lock();
184 }
185 }
186 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
187private:
188 Mutex& mMutex;
189 bool mLocked;
190};
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
Peiyong Lin9d846a52018-11-05 13:18:20 -0800192// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
193bool validateCompositionDataspace(Dataspace dataspace) {
194 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
195}
196
Steven Thomasb02664d2017-07-26 18:48:28 -0700197} // namespace anonymous
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Mathias Agopian99b49842011-06-27 16:05:52 -0700201const String16 sHardwareTest("android.permission.HARDWARE_TEST");
202const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
203const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
204const String16 sDump("android.permission.DUMP");
205
Daniel Solomon42d04562019-01-20 21:03:19 -0800206constexpr float kSrgbRedX = 0.4123f;
207constexpr float kSrgbRedY = 0.2126f;
208constexpr float kSrgbRedZ = 0.0193f;
209constexpr float kSrgbGreenX = 0.3576f;
210constexpr float kSrgbGreenY = 0.7152f;
211constexpr float kSrgbGreenZ = 0.1192f;
212constexpr float kSrgbBlueX = 0.1805f;
213constexpr float kSrgbBlueY = 0.0722f;
214constexpr float kSrgbBlueZ = 0.9506f;
215constexpr float kSrgbWhiteX = 0.9505f;
216constexpr float kSrgbWhiteY = 1.0000f;
217constexpr float kSrgbWhiteZ = 1.0891f;
218
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800219constexpr float kDefaultRefreshRate = 60.f;
220constexpr float kPerformanceRefreshRate = 90.f;
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700230int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700231bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700232bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700233Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
235Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
254 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
David Sodmanbc815282017-11-05 18:57:52 -0800266SurfaceFlingerBE::SurfaceFlingerBE()
267 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800268 mFrameBuckets(),
269 mTotalTime(0),
270 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800271 mComposerSequenceId(0) {
272}
273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
275 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800276 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700278 mTransactionPending(false),
279 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700280 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700281 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800283 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800285 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800286 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800287 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700289 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700290 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700291 mDebugInTransaction(0),
292 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700293 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800294 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800300 mCompositionEngine{getFactory().createCompositionEngine()} {
301 mSetInputWindowsListener = new SetInputWindowsListener(this);
302}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800303
Lloyd Pique90c115d2018-09-18 21:39:42 -0700304SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
305 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800306 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800315
Steven Thomas050b2c82017-03-06 11:45:16 -0800316 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 mDefaultCompositionDataspace =
326 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
327 mWideColorGamutCompositionDataspace =
328 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
329 defaultCompositionDataspace = mDefaultCompositionDataspace;
330 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
331 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
332 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
333 wideColorGamutCompositionPixelFormat =
334 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
339 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
340 switch (tmpPrimaryDisplayOrientation) {
341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
353 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800355
Daniel Solomon42d04562019-01-20 21:03:19 -0800356 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
357 if (surfaceFlingerConfigsServiceV1_2) {
358 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
359 [&](auto tmpPrimaries) {
360 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
361 });
362 } else {
363 initDefaultDisplayNativePrimaries();
364 }
365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 // debugging stuff...
367 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700370 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 property_get("debug.sf.showupdates", value, "0");
373 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700375 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000376
377 // DDMS debugging deprecated (b/120782499)
378 property_get("debug.sf.ddms", value, "0");
379 int debugDdms = atoi(value);
380 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700381
382 property_get("debug.sf.disable_backpressure", value, "0");
383 mPropagateBackpressure = !atoi(value);
384 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700385
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800386 property_get("debug.sf.enable_hwc_vds", value, "0");
387 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800388 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800389
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800390 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800391 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800392 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700393
Yiwei Zhang243b3782018-05-15 17:40:04 -0700394 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700395 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
396 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
397
Ana Krulecc2870422019-01-29 19:00:58 -0800398 property_get("debug.sf.use_90Hz", value, "0");
399 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800400
Ana Krulecba13ab32019-02-20 14:14:12 -0800401 property_get("debug.sf.use_smart_90_for_video", value, "0");
402 mUseSmart90ForVideo = atoi(value);
403
Ana Krulec757f63a2019-01-25 10:46:18 -0800404 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
405 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700406
Romain Guy11d63f42017-07-20 12:47:14 -0700407 // We should be reading 'persist.sys.sf.color_saturation' here
408 // but since /data may be encrypted, we need to wait until after vold
409 // comes online to attempt to read the property. The property is
410 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800411
412 if (useTrebleTestingOverride()) {
413 // Without the override SurfaceFlinger cannot connect to HIDL
414 // services that are not listed in the manifests. Considered
415 // deriving the setting from the set service name, but it
416 // would be brittle if the name that's not 'default' is used
417 // for production purposes later on.
418 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
419 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800420}
421
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422void SurfaceFlinger::onFirstRef()
423{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800424 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427SurfaceFlinger::~SurfaceFlinger()
428{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429}
430
Dan Stozac7014012014-02-14 15:03:43 -0800431void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432{
433 // the window manager died on us. prepare its eulogy.
434
Andy McFadden13a082e2012-08-24 10:16:42 -0700435 // restore initial conditions (default device unblank, etc)
436 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437
438 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700439 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440}
441
Robert Carr1db73f62016-12-21 12:58:51 -0800442static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700443 status_t err = client->initCheck();
444 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446 }
Robert Carr1db73f62016-12-21 12:58:51 -0800447 return nullptr;
448}
449
450sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
451 return initClient(new Client(this));
452}
453
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700454sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
455 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456{
457 class DisplayToken : public BBinder {
458 sp<SurfaceFlinger> flinger;
459 virtual ~DisplayToken() {
460 // no more references, this display must be terminated
461 Mutex::Autolock _l(flinger->mStateLock);
462 flinger->mCurrentState.displays.removeItem(this);
463 flinger->setTransactionFlags(eDisplayTransactionNeeded);
464 }
465 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700466 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700467 : flinger(flinger) {
468 }
469 };
470
471 sp<BBinder> token = new DisplayToken(this);
472
473 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700474 // Display ID is assigned when virtual display is allocated by HWC.
475 DisplayDeviceState state;
476 state.isSecure = secure;
477 state.displayName = displayName;
478 mCurrentState.displays.add(token, state);
479 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480 return token;
481}
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 Mutex::Autolock _l(mStateLock);
485
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
487 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700488 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 return;
490 }
491
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
493 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 ALOGE("destroyDisplay called for non-virtual display");
495 return;
496 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497 mInterceptor->saveDisplayDeletion(state.sequenceId);
498 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700499 setTransactionFlags(eDisplayTransactionNeeded);
500}
501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
503 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 const auto internalDisplayId = getInternalDisplayIdLocked();
506 if (!internalDisplayId) {
507 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700508 }
509
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800510 std::vector<PhysicalDisplayId> displayIds;
511 displayIds.reserve(mPhysicalDisplayTokens.size());
512 displayIds.push_back(internalDisplayId->value);
513
514 for (const auto& [id, token] : mPhysicalDisplayTokens) {
515 if (id != *internalDisplayId) {
516 displayIds.push_back(id.value);
517 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800520 return displayIds;
521}
522
523sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
524 Mutex::Autolock lock(mStateLock);
525 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700526}
527
Ady Abraham37965d42018-11-01 13:43:32 -0700528status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
529 if (!outGetColorManagement) {
530 return BAD_VALUE;
531 }
532 *outGetColorManagement = useColorManagement;
533 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700534}
535
Lloyd Pique441d5042018-10-18 16:49:51 -0700536HWComposer& SurfaceFlinger::getHwComposer() const {
537 return mCompositionEngine->getHwComposer();
538}
539
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700540renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
541 return mCompositionEngine->getRenderEngine();
542}
543
Lloyd Pique70d91362018-10-18 16:02:55 -0700544compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
545 return *mCompositionEngine.get();
546}
547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548void SurfaceFlinger::bootFinished()
549{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700550 if (mStartPropertySetThread->join() != NO_ERROR) {
551 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800552 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553 const nsecs_t now = systemTime();
554 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000555 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556
557 // wait patiently for the window manager death
558 const String16 name("window");
559 sp<IBinder> window(defaultServiceManager()->getService(name));
560 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700561 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 }
Robert Carr720e5062018-07-30 17:45:14 -0700563 sp<IBinder> input(defaultServiceManager()->getService(
564 String16("inputflinger")));
565 if (input == nullptr) {
566 ALOGE("Failed to link to input service");
567 } else {
568 mInputFlinger = interface_cast<IInputFlinger>(input);
569 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570
Steven Thomas050b2c82017-03-06 11:45:16 -0800571 if (mVrFlinger) {
572 mVrFlinger->OnBootFinished();
573 }
574
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700576 // formerly we would just kill the process, but we now ask it to exit so it
577 // can choose where to stop the animation.
578 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700579
580 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
581 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
582 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700583
Ana Krulecbd6654b2019-02-15 15:18:15 -0800584 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 readPersistentProperties();
586 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587
588 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
589 // away and it should be controlled by flipping the switch in setting. The switch in
590 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
591 // The boot must be complete before we can set the active config.
592
593 if (mUse90Hz) {
594 mPhaseOffsets->setRefreshRateType(
595 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
596 setRefreshRateTo(RefreshRateType::PERFORMANCE);
597 } else {
598 mPhaseOffsets->setRefreshRateType(
599 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
600 setRefreshRateTo(RefreshRateType::DEFAULT);
601 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800602 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800603}
604
Dan Stoza436ccf32018-06-21 12:10:12 -0700605uint32_t SurfaceFlinger::getNewTexture() {
606 {
607 std::lock_guard lock(mTexturePoolMutex);
608 if (!mTexturePool.empty()) {
609 uint32_t name = mTexturePool.back();
610 mTexturePool.pop_back();
611 ATRACE_INT("TexturePoolSize", mTexturePool.size());
612 return name;
613 }
614
615 // The pool was too small, so increase it for the future
616 ++mTexturePoolSize;
617 }
618
619 // The pool was empty, so we need to get a new texture name directly using a
620 // blocking call to the main thread
621 uint32_t name = 0;
622 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
623 return name;
624}
625
Mathias Agopian3f844832013-08-07 21:24:32 -0700626void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700627 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700628}
629
Wei Wangf9b05ee2017-07-19 20:59:39 -0700630// Do not call property_set on main thread which will be blocked by init
631// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700633 ALOGI( "SurfaceFlinger's main thread ready to run. "
634 "Initializing graphics H/W...");
635
Ana Krulec757f63a2019-01-25 10:46:18 -0800636 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900637
Steven Thomasb02664d2017-07-26 18:48:28 -0700638 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700639 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800640 mScheduler =
641 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
642 auto resyncCallback =
643 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800644
Ana Krulecc2870422019-01-29 19:00:58 -0800645 mAppConnectionHandle =
646 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
647 resyncCallback,
648 impl::EventThread::InterceptVSyncsCallback());
649 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
650 resyncCallback, [this](nsecs_t timestamp) {
651 mInterceptor->saveVSyncEvent(timestamp);
652 });
653
654 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
655 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
656 mSfConnectionHandle.get());
657
Steven Thomasb02664d2017-07-26 18:48:28 -0700658 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700659 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700660 renderEngineFeature |= (useColorManagement ?
661 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700662 renderEngineFeature |= (useContextPriority ?
663 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700664
665 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700666 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700667 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700668 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700669
670 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
671 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700672 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
673 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800674 // Process any initial hotplug and resulting display changes.
675 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700676 const auto display = getDefaultDisplayDeviceLocked();
677 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700678 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800680
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700682 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700683 // This callback is called from the vr flinger dispatch thread. We
684 // need to call signalTransaction(), which requires holding
685 // mStateLock when we're not on the main thread. Acquiring
686 // mStateLock from the vr flinger dispatch thread might trigger a
687 // deadlock in surface flinger (see b/66916578), so post a message
688 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700689 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700690 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
691 mVrFlingerRequestsDisplay = requestDisplay;
692 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800694 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700695 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
696 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700697 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 .value_or(0),
699 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 if (!mVrFlinger) {
701 ALOGE("Failed to start vrflinger");
702 }
703 }
704
Mathias Agopian92a979a2012-08-02 18:32:23 -0700705 // initialize our drawing state
706 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700707
Andy McFadden13a082e2012-08-24 10:16:42 -0700708 // set initial conditions (e.g. unblank default device)
709 initializeDisplays();
710
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700711 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700712
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700714
715 const bool presentFenceReliable =
716 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
717 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718
719 if (mStartPropertySetThread->Start() != NO_ERROR) {
720 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800721 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800722
Kevin DuBois36233132019-02-19 14:08:55 -0800723 if (mUse90Hz) {
724 mScheduler->setExpiredIdleTimerCallback([this] {
725 Mutex::Autolock lock(mStateLock);
726 setRefreshRateTo(RefreshRateType::DEFAULT);
727 });
728 mScheduler->setResetIdleTimerCallback([this] {
729 Mutex::Autolock lock(mStateLock);
730 setRefreshRateTo(RefreshRateType::PERFORMANCE);
731 });
732 }
Ana Krulecc2870422019-01-29 19:00:58 -0800733 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
734 *display->getId()),
735 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800736
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800752
753 property_get("persist.sys.sf.color_mode", value, "0");
754 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700755}
756
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Start boot animation service by setting a property mailbox
759 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700762 if (mStartPropertySetThread->join() != NO_ERROR) {
763 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800764 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700765}
766
Mathias Agopian875d8e12013-06-07 15:35:48 -0700767size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700768 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700769}
770
Mathias Agopian875d8e12013-06-07 15:35:48 -0700771size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700772 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700773}
774
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800775// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800776
Jamie Gennis582270d2011-08-17 18:19:00 -0700777bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800779 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800780 return authenticateSurfaceTextureLocked(bufferProducer);
781}
782
783bool SurfaceFlinger::authenticateSurfaceTextureLocked(
784 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800785 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800786 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800787}
788
Brian Anderson6b376712017-04-04 10:51:39 -0700789status_t SurfaceFlinger::getSupportedFrameTimestamps(
790 std::vector<FrameEvent>* outSupported) const {
791 *outSupported = {
792 FrameEvent::REQUESTED_PRESENT,
793 FrameEvent::ACQUIRE,
794 FrameEvent::LATCH,
795 FrameEvent::FIRST_REFRESH_START,
796 FrameEvent::LAST_REFRESH_START,
797 FrameEvent::GPU_COMPOSITION_DONE,
798 FrameEvent::DEQUEUE_READY,
799 FrameEvent::RELEASE,
800 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700801 ConditionalLock _l(mStateLock,
802 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700803 if (!getHwComposer().hasCapability(
804 HWC2::Capability::PresentFenceIsNotReliable)) {
805 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
806 }
807 return NO_ERROR;
808}
809
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800810status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
811 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700812 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 return BAD_VALUE;
814 }
815
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800816 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700817 if (!displayId) {
818 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 // TODO: Not sure if display density should handled by SF any longer
822 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700823 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700825 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800826 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700827 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 }
829 return density;
830 }
831 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 return getDensityFromProperty("ro.sf.lcd_density"); }
836 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700839
Dominik Laskowski075d3172018-05-24 15:50:06 -0700840 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 DisplayInfo info = DisplayInfo();
842
Dan Stoza9e56aa02015-11-02 13:00:03 -0800843 float xdpi = hwConfig->getDpiX();
844 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700845
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700846 info.w = hwConfig->getWidth();
847 info.h = hwConfig->getHeight();
848 // Default display viewport to display width and height
849 info.viewportW = info.w;
850 info.viewportH = info.h;
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700853 // The density of the device is provided by a build property
854 float density = Density::getBuildDensity() / 160.0f;
855 if (density == 0) {
856 // the build doesn't provide a density -- this is wrong!
857 // use xdpi instead
858 ALOGE("ro.sf.lcd_density must be defined as a build property");
859 density = xdpi / 160.0f;
860 }
861 if (Density::getEmuDensity()) {
862 // if "qemu.sf.lcd_density" is specified, it overrides everything
863 xdpi = ydpi = density = Density::getEmuDensity();
864 density /= 160.0f;
865 }
866 info.density = density;
867
868 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700869 const auto display = getDefaultDisplayDeviceLocked();
870 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700871
872 // This is for screenrecord
873 const Rect viewport = display->getViewport();
874 if (viewport.isValid()) {
875 info.viewportW = uint32_t(viewport.getWidth());
876 info.viewportH = uint32_t(viewport.getHeight());
877 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 } else {
879 // TODO: where should this value come from?
880 static const int TV_DENSITY = 213;
881 info.density = TV_DENSITY / 160.0f;
882 info.orientation = 0;
883 }
884
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 info.xdpi = xdpi;
886 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800888 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889
Andy McFadden91b2ca82014-06-13 14:04:23 -0700890 // This is how far in advance a buffer must be queued for
891 // presentation at a given time. If you want a buffer to appear
892 // on the screen at time N, you must submit the buffer before
893 // (N - presentationDeadline).
894 //
895 // Normally it's one full refresh period (to give SF a chance to
896 // latch the buffer), but this can be reduced by configuring a
897 // DispSync offset. Any additional delays introduced by the hardware
898 // composer or panel must be accounted for here.
899 //
900 // We add an additional 1ms to allow for processing time and
901 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800902 info.presentationDeadline =
903 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700904
905 // All non-virtual displays are currently considered secure.
906 info.secure = true;
907
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800908 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700909 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800910 std::swap(info.w, info.h);
911 }
912
Michael Wright28f24d02016-07-12 13:30:53 -0700913 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 }
915
Dan Stoza7f7da322014-05-02 15:26:25 -0700916 return NO_ERROR;
917}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
920 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700921 return BAD_VALUE;
922 }
923
Ana Krulecc2870422019-01-29 19:00:58 -0800924 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700925 return NO_ERROR;
926}
927
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700928int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
929 const auto display = getDisplayDevice(displayToken);
930 if (!display) {
931 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800932 return BAD_VALUE;
933 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700936}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700937
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
939 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800940
Ana Krulec7d1d6832018-12-27 11:10:09 -0800941 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942 // Lock is acquired by setRefreshRateTo.
943 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
945 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
946 return;
947 }
948
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 // Lock is acquired by setRefreshRateTo.
950 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800951 if (!display) {
952 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
953 displayToken.get());
954 return;
955 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700956 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800957 ALOGW("Attempt to set active config %d for virtual display", mode);
958 return;
959 }
960 int currentDisplayPowerMode = display->getPowerMode();
961 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
962 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700963 return;
964 }
965
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966 // Don't check against the current mode yet. Worst case we set the desired
967 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 std::lock_guard<std::mutex> lock(mActiveConfigLock);
969 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
970
971 if (!mDesiredActiveConfigChanged) {
972 // This is the first time we set the desired
973 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
974
975 // This will trigger HWC refresh without resetting the idle timer.
976 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 mDesiredActiveConfigChanged = true;
979 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980}
981
982status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
983 ATRACE_CALL();
984 postMessageSync(new LambdaMessage(
985 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
986 return NO_ERROR;
987}
988
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989void SurfaceFlinger::setActiveConfigInternal() {
990 ATRACE_CALL();
991
992 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800993 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994
995 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
996 display->setActiveConfig(mUpcomingActiveConfig.configId);
997
Ana Krulecc2870422019-01-29 19:00:58 -0800998 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1000}
1001
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
1003 // we may be in the process of changing the active state
1004 if (mWaitForNextInvalidate) {
1005 mWaitForNextInvalidate = false;
1006
1007 repaintEverythingForHWC();
1008 // We do not want to give another frame to HWC while we are transitioning.
1009 return true;
1010 }
1011
1012 if (mCheckPendingFence) {
1013 if (mPreviousPresentFence != Fence::NO_FENCE &&
1014 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1015 // fence has not signaled yet. wait for the next invalidate
1016 repaintEverythingForHWC();
1017 return true;
1018 }
1019
1020 // We received the present fence from the HWC, so we assume it successfully updated
1021 // the config, hence we update SF.
1022 mCheckPendingFence = false;
1023 setActiveConfigInternal();
1024 }
1025
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001026 // Store the local variable to release the lock.
1027 ActiveConfigInfo desiredActiveConfig;
1028 {
1029 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 if (!mDesiredActiveConfigChanged) {
1031 return false;
1032 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001033 desiredActiveConfig = mDesiredActiveConfig;
1034 }
1035
1036 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1038 // display is not valid or we are already in the requested mode
1039 // on both cases there is nothing left to do
1040 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1041 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1042 mDesiredActiveConfigChanged = false;
1043 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1044 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001045 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046
1047 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1048 mUpcomingActiveConfig = desiredActiveConfig;
1049 const auto displayId = display->getId();
1050 LOG_ALWAYS_FATAL_IF(!displayId);
1051
1052 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1053 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1054
1055 // we need to submit an empty frame to HWC to start the process
1056 mWaitForNextInvalidate = true;
1057 mCheckPendingFence = true;
1058
1059 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001060}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001061
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1063 Vector<ColorMode>* outColorModes) {
1064 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001065 return BAD_VALUE;
1066 }
1067
Peiyong Lina52f0292018-03-14 17:26:31 -07001068 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001070 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1071
1072 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1073 if (!displayId) {
1074 return NAME_NOT_FOUND;
1075 }
1076
Dominik Laskowski075d3172018-05-24 15:50:06 -07001077 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001078 }
Michael Wright28f24d02016-07-12 13:30:53 -07001079 outColorModes->clear();
1080 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1081
1082 return NO_ERROR;
1083}
1084
Daniel Solomon42d04562019-01-20 21:03:19 -08001085status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1086 ui::DisplayPrimaries &primaries) {
1087 if (!displayToken) {
1088 return BAD_VALUE;
1089 }
1090
1091 // Currently we only support this API for a single internal display.
1092 if (getInternalDisplayToken() != displayToken) {
1093 return BAD_VALUE;
1094 }
1095
1096 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1097 return NO_ERROR;
1098}
1099
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1101 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001102 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001103 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001104 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001105}
1106
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001108 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 Vector<ColorMode> modes;
1110 getDisplayColorModes(displayToken, &modes);
1111 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1112 if (mode < ColorMode::NATIVE || !exists) {
1113 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1114 decodeColorMode(mode).c_str(), mode, displayToken.get());
1115 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001116 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001117 const auto display = getDisplayDevice(displayToken);
1118 if (!display) {
1119 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1120 decodeColorMode(mode).c_str(), mode, displayToken.get());
1121 } else if (display->isVirtual()) {
1122 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1123 decodeColorMode(mode).c_str(), mode);
1124 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001125 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1126 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127 }
1128 }));
1129
Michael Wright28f24d02016-07-12 13:30:53 -07001130 return NO_ERROR;
1131}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001132
Svetoslavd85084b2014-03-20 10:28:31 -07001133status_t SurfaceFlinger::clearAnimationFrameStats() {
1134 Mutex::Autolock _l(mStateLock);
1135 mAnimFrameTracker.clearStats();
1136 return NO_ERROR;
1137}
1138
1139status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1140 Mutex::Autolock _l(mStateLock);
1141 mAnimFrameTracker.getStats(outStats);
1142 return NO_ERROR;
1143}
1144
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001145status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1146 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001147 Mutex::Autolock _l(mStateLock);
1148
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149 const auto display = getDisplayDeviceLocked(displayToken);
1150 if (!display) {
1151 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001152 return BAD_VALUE;
1153 }
1154
Peiyong Linfb069302018-04-25 14:34:31 -07001155 // At this point the DisplayDeivce should already be set up,
1156 // meaning the luminance information is already queried from
1157 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001158 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001159 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1160 capabilities.getDesiredMaxLuminance(),
1161 capabilities.getDesiredMaxAverageLuminance(),
1162 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001163
1164 return NO_ERROR;
1165}
1166
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001167status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1168 ui::PixelFormat* outFormat,
1169 ui::Dataspace* outDataspace,
1170 uint8_t* outComponentMask) const {
1171 if (!outFormat || !outDataspace || !outComponentMask) {
1172 return BAD_VALUE;
1173 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001174 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001175 if (!display || !display->getId()) {
1176 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1177 return BAD_VALUE;
1178 }
1179 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1180 outDataspace, outComponentMask);
1181}
1182
Kevin DuBois74e53772018-11-19 10:52:38 -08001183status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1184 bool enable, uint8_t componentMask,
1185 uint64_t maxFrames) const {
1186 const auto display = getDisplayDevice(displayToken);
1187 if (!display || !display->getId()) {
1188 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1189 return BAD_VALUE;
1190 }
1191
1192 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1193 componentMask, maxFrames);
1194}
1195
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001196status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1197 uint64_t maxFrames, uint64_t timestamp,
1198 DisplayedFrameStats* outStats) const {
1199 const auto display = getDisplayDevice(displayToken);
1200 if (!display || !display->getId()) {
1201 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1202 return BAD_VALUE;
1203 }
1204
1205 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1206 outStats);
1207}
1208
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001209status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1210 if (!outSupported) {
1211 return BAD_VALUE;
1212 }
1213 *outSupported = getRenderEngine().supportsProtectedContent();
1214 return NO_ERROR;
1215}
1216
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001217status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1218 bool* outIsWideColorDisplay) const {
1219 if (!displayToken || !outIsWideColorDisplay) {
1220 return BAD_VALUE;
1221 }
1222 Mutex::Autolock _l(mStateLock);
1223 const auto display = getDisplayDeviceLocked(displayToken);
1224 if (!display) {
1225 return BAD_VALUE;
1226 }
1227 *outIsWideColorDisplay = display->hasWideColorGamut();
1228 return NO_ERROR;
1229}
1230
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001231status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001232 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001234
Chia-I Wu90f669f2017-10-05 14:24:41 -07001235 if (mInjectVSyncs == enable) {
1236 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001237 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001238
Ana Krulecc2870422019-01-29 19:00:58 -08001239 auto resyncCallback =
1240 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001241
Ana Krulec98b5b242018-08-10 15:03:23 -07001242 // TODO(akrulec): Part of the Injector should be refactored, so that it
1243 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001244 if (enable) {
1245 ALOGV("VSync Injections enabled");
1246 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001247 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001248 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001249 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001250 impl::EventThread::InterceptVSyncsCallback(),
1251 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001253 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001254 } else {
1255 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001256 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1257 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258 }
1259
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001260 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001261 }));
1262
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001263 return NO_ERROR;
1264}
1265
1266status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001267 Mutex::Autolock _l(mStateLock);
1268
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001269 if (!mInjectVSyncs) {
1270 ALOGE("VSync Injections not enabled");
1271 return BAD_VALUE;
1272 }
1273 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1274 ALOGV("Injecting VSync inside SurfaceFlinger");
1275 mVSyncInjector->onInjectSyncEvent(when);
1276 }
1277 return NO_ERROR;
1278}
1279
Lloyd Pique755e3192018-01-31 16:46:15 -08001280status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1281 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001282 // Try to acquire a lock for 1s, fail gracefully
1283 const status_t err = mStateLock.timedLock(s2ns(1));
1284 const bool locked = (err == NO_ERROR);
1285 if (!locked) {
1286 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1287 return TIMED_OUT;
1288 }
1289
1290 outLayers->clear();
1291 mCurrentState.traverseInZOrder([&](Layer* layer) {
1292 outLayers->push_back(layer->getLayerDebugInfo());
1293 });
1294
1295 mStateLock.unlock();
1296 return NO_ERROR;
1297}
1298
Peiyong Linc6780972018-10-28 15:24:08 -07001299status_t SurfaceFlinger::getCompositionPreference(
1300 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1301 Dataspace* outWideColorGamutDataspace,
1302 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001303 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001304 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001305 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001306 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001307 return NO_ERROR;
1308}
1309
Dan Stoza84ab9372018-12-17 15:27:57 -08001310status_t SurfaceFlinger::addRegionSamplingListener(
1311 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1312 const sp<IRegionSamplingListener>& /*listener*/) {
1313 return NO_ERROR;
1314}
1315
1316status_t SurfaceFlinger::removeRegionSamplingListener(
1317 const sp<IRegionSamplingListener>& /*listener*/) {
1318 return NO_ERROR;
1319}
1320
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001321// ----------------------------------------------------------------------------
1322
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001323sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1324 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001325 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001326 Mutex::Autolock lock(mStateLock);
1327 return getVsyncPeriod();
1328 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001329
Ana Krulecc2870422019-01-29 19:00:58 -08001330 const auto& handle =
1331 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001332
Ana Krulecc2870422019-01-29 19:00:58 -08001333 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001334}
1335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001336// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001337
1338void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001339 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001340}
1341
1342void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001343 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344}
1345
1346void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001347 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001348}
1349
1350void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001351 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001352 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001353}
1354
1355status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001356 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001357 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358}
1359
1360status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001361 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001362 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001363 if (res == NO_ERROR) {
1364 msg->wait();
1365 }
1366 return res;
1367}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001368
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001369void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001370 do {
1371 waitForEvent();
1372 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001373}
1374
Dominik Laskowski83b88212018-12-11 13:34:06 -08001375nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001376 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001377 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1378 return 0;
1379 }
1380
1381 const auto config = getHwComposer().getActiveConfig(*displayId);
1382 return config ? config->getVsyncPeriod() : 0;
1383}
1384
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001385void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1386 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001387 ATRACE_NAME("SF onVsync");
1388
Steven Thomas3cfac282017-02-06 12:29:30 -08001389 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001391 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 return;
1393 }
1394
Dominik Laskowski075d3172018-05-24 15:50:06 -07001395 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001396 return;
1397 }
1398
Dominik Laskowski075d3172018-05-24 15:50:06 -07001399 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001400 // For now, we don't do anything with external display vsyncs.
1401 return;
1402 }
1403
Ana Krulecc2870422019-01-29 19:00:58 -08001404 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001405}
1406
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001408 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1409 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001410}
1411
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001412void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1413 mPhaseOffsets->setRefreshRateType(refreshRate);
1414
1415 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1416 mVsyncModulator.setPhaseOffsets(early, gl, late);
1417
1418 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001419 return;
1420 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001421
Ana Krulec7d1d6832018-12-27 11:10:09 -08001422 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1423 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1424 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1425 // refresh cycle.
1426
1427 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001428 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001429 if (currentVsyncPeriod == 0) {
1430 return;
1431 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001432
Ana Krulec7d1d6832018-12-27 11:10:09 -08001433 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1434 // floating numbers.
1435 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001436 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1437 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001438 if (std::abs(currentFps - newFps) <= 1) {
1439 return;
1440 }
1441
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001442 const auto displayId = getInternalDisplayIdLocked();
1443 LOG_ALWAYS_FATAL_IF(!displayId);
1444
1445 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001446 for (int i = 0; i < configs.size(); i++) {
1447 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1448 if (vsyncPeriod == 0) {
1449 continue;
1450 }
1451 const float fps = 1e9 / vsyncPeriod;
1452 // TODO(b/113612090): There should be a better way at determining which config
1453 // has the right refresh rate.
1454 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001455 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 }
1457 }
1458}
1459
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001461 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001462 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001463 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001464
Lloyd Piqueba04e622017-12-14 17:11:26 -08001465 // Ignore events that do not have the right sequenceId.
1466 if (sequenceId != getBE().mComposerSequenceId) {
1467 return;
1468 }
1469
Steven Thomasb02664d2017-07-26 18:48:28 -07001470 // Only lock if we're not on the main thread. This function is normally
1471 // called on a hwbinder thread, but for the primary display it's called on
1472 // the main thread with the state lock already held, so don't attempt to
1473 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001474 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001475
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001476 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001477
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001478 if (std::this_thread::get_id() == mMainThreadId) {
1479 // Process all pending hot plug events immediately if we are on the main thread.
1480 processDisplayHotplugEventsLocked();
1481 }
1482
Lloyd Piqueba04e622017-12-14 17:11:26 -08001483 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001484}
1485
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001486void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001487 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001488 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001490 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001491 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001492}
1493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001494void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001495 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001497 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 getHwComposer().setVsyncEnabled(*displayId,
1499 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1500 }
Mathias Agopian86303202012-07-24 22:46:10 -07001501}
1502
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001504void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001505 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001506 // Clear the drawing state so that the logic inside of
1507 // handleTransactionLocked will fire. It will determine the delta between
1508 // mCurrentState and mDrawingState and re-apply all changes when we make the
1509 // transition.
1510 mDrawingState.displays.clear();
1511 mDisplays.clear();
1512}
1513
Steven Thomas050b2c82017-03-06 11:45:16 -08001514void SurfaceFlinger::updateVrFlinger() {
1515 if (!mVrFlinger)
1516 return;
1517 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001518 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001519 return;
1520 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001521
Lloyd Pique441d5042018-10-18 16:49:51 -07001522 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 ALOGE("Vr flinger is only supported for remote hardware composer"
1524 " service connections. Ignoring request to transition to vr"
1525 " flinger.");
1526 mVrFlingerRequestsDisplay = false;
1527 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001528 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001529
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomas0123ac62018-07-12 11:32:34 -07001532 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001533 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001534
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001535 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001536
1537 // Clear out all the output layers from the composition engine for all
1538 // displays before destroying the hardware composer interface. This ensures
1539 // any HWC layers are destroyed through that interface before it becomes
1540 // invalid.
1541 for (const auto& [token, displayDevice] : mDisplays) {
1542 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1543 compositionengine::Output::OutputLayers());
1544 }
1545
Steven Thomas0123ac62018-07-12 11:32:34 -07001546 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1547 // called below. Clear the reference now so we don't accidentally use it
1548 // later.
1549 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001550
Steven Thomasb02664d2017-07-26 18:48:28 -07001551 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001554
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 // Delete the current instance before creating the new one
1557 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1558 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1559 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1560 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561
Lloyd Pique441d5042018-10-18 16:49:51 -07001562 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001563 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001564
1565 if (vrFlingerRequestsDisplay) {
1566 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568
1569 mVisibleRegionsDirty = true;
1570 invalidateHwcGeometry();
1571
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001572 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001573 display = getDefaultDisplayDeviceLocked();
1574 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001575 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001576
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001578 const nsecs_t vsyncPeriod = getVsyncPeriod();
1579 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001580
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581 // The present fences returned from vr_hwc are not an accurate
1582 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001583 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Use phase of 0 since phase is not known.
1586 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001587 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001588 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001589
Ana Krulecc2870422019-01-29 19:00:58 -08001590 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001591
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001592 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001593 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594}
1595
Mathias Agopian4fec8732012-06-29 14:12:52 -07001596void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001597 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001598 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001599 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001600 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001601 break;
1602 }
1603
Ana Krulecba13ab32019-02-20 14:14:12 -08001604 if (mUse90Hz && mUseSmart90ForVideo) {
1605 // This call is made each time SF wakes up and creates a new frame. It is part
1606 // of video detection feature.
1607 mScheduler->incrementFrameCounter();
1608 }
Ana Krulecc2870422019-01-29 19:00:58 -08001609
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001610 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1611 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001612 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001613 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001614 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001615 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001616 if (mPropagateBackpressure) {
1617 signalLayerUpdate();
1618 break;
1619 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001620 }
Dan Stoza50182882016-07-08 12:02:20 -07001621
Steven Thomas050b2c82017-03-06 11:45:16 -08001622 // Now that we're going to make it to the handleMessageTransaction()
1623 // call below it's safe to call updateVrFlinger(), which will
1624 // potentially trigger a display handoff.
1625 updateVrFlinger();
1626
Dan Stoza6b9454d2014-11-07 16:00:59 -08001627 bool refreshNeeded = handleMessageTransaction();
1628 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001629
1630 updateCursorAsync();
1631 updateInputFlinger();
1632
Dan Stoza58784442014-12-02 16:58:17 -08001633 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001634 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001635 // Signal a refresh if a transaction modified the window state,
1636 // a new buffer was latched, or if HWC has requested a full
1637 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001638 signalRefresh();
1639 }
1640 break;
1641 }
1642 case MessageQueue::REFRESH: {
1643 handleMessageRefresh();
1644 break;
1645 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001646 }
1647}
1648
Dan Stoza6b9454d2014-11-07 16:00:59 -08001649bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001650 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001651
1652 // Apply any ready transactions in the queues if there are still transactions that have not been
1653 // applied, wake up during the next vsync period and check again
1654 bool transactionNeeded = false;
1655 if (!flushTransactionQueues()) {
1656 transactionNeeded = true;
1657 }
1658
Mathias Agopian4fec8732012-06-29 14:12:52 -07001659 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001660 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001661 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001662
1663 if (transactionNeeded) {
1664 setTransactionFlags(eTransactionNeeded);
1665 }
1666
1667 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001668}
1669
Mathias Agopian4fec8732012-06-29 14:12:52 -07001670void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001672
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001673 mRefreshPending = false;
1674
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001675 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001676 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001677 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001678 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001679 for (const auto& [token, display] : mDisplays) {
1680 beginFrame(display);
1681 prepareFrame(display);
1682 doDebugFlashRegions(display, repaintEverything);
1683 doComposition(display, repaintEverything);
1684 }
1685
Adrian Roos1e1a1282017-11-01 19:05:31 +01001686 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001687 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001688
1689 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001690 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001691
Dan Stozabfbffeb2016-07-21 14:49:33 -07001692 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001693 for (const auto& [token, displayDevice] : mDisplays) {
1694 auto display = displayDevice->getCompositionDisplay();
1695 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001696 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001697 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001698 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001699
Jorim Jaggi90535212018-05-23 23:44:06 +02001700 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001701
David Sodman7e4ae112018-02-09 15:02:28 -08001702 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001703
1704 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706
David Sodmanfa9b2af2017-12-24 13:28:59 -08001707
1708bool SurfaceFlinger::handleMessageInvalidate() {
1709 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001710 bool refreshNeeded = handlePageFlip();
1711
Vishnu Nair4351ad52019-02-11 14:13:02 -08001712 if (mVisibleRegionsDirty) {
1713 computeLayerBounds();
1714 }
1715
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001716 for (auto& layer : mLayersPendingRefresh) {
1717 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001718 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001719 invalidateLayerStack(layer, visibleReg);
1720 }
1721 mLayersPendingRefresh.clear();
1722 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001723}
1724
David Sodman79bba0e2018-08-05 18:07:49 -07001725void SurfaceFlinger::calculateWorkingSet() {
1726 ATRACE_CALL();
1727 ALOGV(__FUNCTION__);
1728
David Sodman79bba0e2018-08-05 18:07:49 -07001729 // build the h/w work list
1730 if (CC_UNLIKELY(mGeometryInvalid)) {
1731 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001732 for (const auto& [token, displayDevice] : mDisplays) {
1733 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001734 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001735 if (!displayId) {
1736 continue;
1737 }
David Sodman79bba0e2018-08-05 18:07:49 -07001738
Lloyd Pique32cbe282018-10-19 13:09:22 -07001739 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001740 for (size_t i = 0; i < currentLayers.size(); i++) {
1741 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001742
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001743 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001744 layer->forceClientComposition(displayDevice);
1745 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001746 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747
Lloyd Pique32cbe282018-10-19 13:09:22 -07001748 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001750 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001751 }
David Sodman79bba0e2018-08-05 18:07:49 -07001752 }
1753 }
1754 }
1755
1756 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001757 for (const auto& [token, displayDevice] : mDisplays) {
1758 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001759 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001760 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001761 continue;
1762 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001763 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001764
1765 if (mDrawingState.colorMatrixChanged) {
1766 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001767 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001768 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001769 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001770 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001771 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1772 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001773 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001774 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001775 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1776 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001777 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001778 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001779 }
1780
Peiyong Lind3788632018-09-18 16:01:31 -07001781 // TODO(b/111562338) remove when composer 2.3 is shipped.
1782 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001783 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001784 }
1785
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001786 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001787 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001788 }
1789
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001790 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001791 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001792 layer->setCompositionType(displayDevice,
1793 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001794 continue;
1795 }
1796
Lloyd Pique32cbe282018-10-19 13:09:22 -07001797 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001798 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001799 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001800 }
1801
Peiyong Lin13effd12018-07-24 17:01:47 -07001802 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001803 ColorMode colorMode;
1804 Dataspace dataSpace;
1805 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001806 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001807 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001808 }
1809 }
1810
1811 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001812
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001813 for (const auto& [token, displayDevice] : mDisplays) {
1814 auto display = displayDevice->getCompositionDisplay();
1815 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001816 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001817 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1818 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1819 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001820 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001821 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001822 }
1823 }
David Sodman79bba0e2018-08-05 18:07:49 -07001824}
1825
Lloyd Pique32cbe282018-10-19 13:09:22 -07001826void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1827 bool repaintEverything) {
1828 auto display = displayDevice->getCompositionDisplay();
1829 const auto& displayState = display->getState();
1830
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831 // is debugging enabled
1832 if (CC_LIKELY(!mDebugRegion))
1833 return;
1834
Lloyd Pique32cbe282018-10-19 13:09:22 -07001835 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001837 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001838 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001839 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001840 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001841 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001842
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001843 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844 }
1845 }
1846
Lloyd Pique32cbe282018-10-19 13:09:22 -07001847 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001848
1849 if (mDebugRegion > 1) {
1850 usleep(mDebugRegion * 1000);
1851 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001852
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854}
1855
Adrian Roos1e1a1282017-11-01 19:05:31 +01001856void SurfaceFlinger::doTracing(const char* where) {
1857 ATRACE_CALL();
1858 ATRACE_NAME(where);
1859 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001860 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001861 }
1862}
1863
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001864void SurfaceFlinger::logLayerStats() {
1865 ATRACE_CALL();
1866 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001867 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001868 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001869 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001870 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001871 }
1872 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001873
1874 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001875 }
1876}
1877
David Sodman2b406362017-12-15 13:33:47 -08001878void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 ATRACE_CALL();
1881 ALOGV("preComposition");
1882
David Sodman2b406362017-12-15 13:33:47 -08001883 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1884
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001886 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001887 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 needExtraInvalidate = true;
1889 }
Robert Carr2047fae2016-11-28 14:09:09 -08001890 });
1891
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892 if (needExtraInvalidate) {
1893 signalLayerUpdate();
1894 }
1895}
1896
Ana Krulece588e312018-09-18 12:32:24 -07001897void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1898 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 // Update queue of past composite+present times and determine the
1900 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001901 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001903 while (!getBE().mCompositePresentTimes.empty()) {
1904 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 // Cached values should have been updated before calling this method,
1906 // which helps avoid duplicate syscalls.
1907 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1908 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1909 break;
1910 }
1911 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001912 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001913 }
1914
1915 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001916 while (getBE().mCompositePresentTimes.size() > 16) {
1917 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001918 }
1919
Ana Krulece588e312018-09-18 12:32:24 -07001920 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001921}
1922
Ana Krulece588e312018-09-18 12:32:24 -07001923void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1924 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925 // Integer division and modulo round toward 0 not -inf, so we need to
1926 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001927 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1928 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1929 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930
Ana Krulec757f63a2019-01-25 10:46:18 -08001931 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001932 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001933 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001934 }
1935
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936 // Snap the latency to a value that removes scheduling jitter from the
1937 // composition and present times, which often have >1ms of jitter.
1938 // Reducing jitter is important if an app attempts to extrapolate
1939 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001940 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001942 nsecs_t bias = stats.vsyncPeriod / 2;
1943 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1944 nsecs_t snappedCompositeToPresentLatency =
1945 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946
David Sodman99974d22017-11-28 12:04:33 -08001947 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001948 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1949 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001950 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951}
1952
Ady Abraham8164d482019-01-11 14:47:59 -08001953// debug patch for b/119477596 - add stack guards to catch stack
1954// corruptions and disable clang optimizations.
1955// The code below is temporary and planned to be removed once stack
1956// corruptions are found.
1957#pragma clang optimize off
1958class StackGuard {
1959public:
1960 StackGuard(const char* name, const char* func, int line) {
1961 guarders.reserve(MIN_CAPACITY);
1962 guarders.push_back({this, name, func, line});
1963 validate();
1964 }
1965 ~StackGuard() {
1966 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1967 if (i->guard == this) {
1968 guarders.erase(i);
1969 break;
1970 }
1971 }
1972 }
1973
1974 static void validate() {
1975 for (const auto& guard : guarders) {
1976 if (guard.guard->cookie != COOKIE_VALUE) {
1977 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1978 CallStack stack(LOG_TAG);
1979 abort();
1980 }
1981 }
1982 }
1983
1984private:
1985 uint64_t cookie = COOKIE_VALUE;
1986 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1987 static constexpr size_t MIN_CAPACITY = 16;
1988
1989 struct GuarderElement {
1990 StackGuard* guard;
1991 const char* name;
1992 const char* func;
1993 int line;
1994 };
1995
1996 static std::vector<GuarderElement> guarders;
1997};
1998std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1999
2000#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2001
2002#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002003void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004{
Ady Abraham8164d482019-01-11 14:47:59 -08002005 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 ATRACE_CALL();
2007 ALOGV("postComposition");
2008
Brian Anderson3546a3f2016-07-14 11:51:14 -07002009 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002010 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002011 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002013 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002014 }
Ady Abraham8164d482019-01-11 14:47:59 -08002015 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002016
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002017 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002018 const auto displayDevice = getDefaultDisplayDeviceLocked();
2019 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020
David Sodman73beded2017-11-15 11:56:06 -08002021 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002023 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2024
Lloyd Pique32cbe282018-10-19 13:09:22 -07002025 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002027 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2028 ->getRenderSurface()
2029 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002030 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002031 } else {
2032 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2033 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034
Ady Abraham8164d482019-01-11 14:47:59 -08002035 ASSERT_ON_STACK_GUARD();
2036
David Sodman73beded2017-11-15 11:56:06 -08002037 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002038 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2039 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002040 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002041 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043
Ana Krulece588e312018-09-18 12:32:24 -07002044 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002045 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002046 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047
Ady Abraham8164d482019-01-11 14:47:59 -08002048 ASSERT_ON_STACK_GUARD();
2049
David Sodman2b406362017-12-15 13:33:47 -08002050 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 // when we started doing work for this frame, but that should be okay
2052 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002053 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002054 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002055 DEFINE_STACK_GUARD(compositorTiming);
2056
Brian Andersond0010582017-03-07 13:20:31 -08002057 {
David Sodman99974d22017-11-28 12:04:33 -08002058 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002059 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002060 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002061
2062 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002063 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064
Robert Carr2047fae2016-11-28 14:09:09 -08002065 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002066 bool frameLatched =
2067 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2068 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002069 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002070 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002071 recordBufferingStats(layer->getName().string(),
2072 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002073 }
Ady Abraham8164d482019-01-11 14:47:59 -08002074 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002075 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002076
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002077 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002078 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002079 mScheduler->addPresentFence(presentFenceTime);
2080 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002081 }
2082
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002083 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2085 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002086 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002087 }
2088 }
2089
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
2091
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 if (mAnimCompositionPending) {
2093 mAnimCompositionPending = false;
2094
Brian Anderson4e606e32017-03-16 15:34:57 -07002095 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002096 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002097 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002098
2099 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002100 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002101 // The HWC doesn't support present fences, so use the refresh
2102 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002103 const nsecs_t presentTime =
2104 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002105 DEFINE_STACK_GUARD(presentTime);
2106
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002107 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002108 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002109 }
2110 mAnimFrameTracker.advanceFrame();
2111 }
Dan Stozab90cf072015-03-05 11:05:59 -08002112
Ady Abraham8164d482019-01-11 14:47:59 -08002113 ASSERT_ON_STACK_GUARD();
2114
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002115 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002116 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002117 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002118 }
2119
Ady Abraham8164d482019-01-11 14:47:59 -08002120 ASSERT_ON_STACK_GUARD();
2121
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002122 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002123
Ady Abraham8164d482019-01-11 14:47:59 -08002124 ASSERT_ON_STACK_GUARD();
2125
Lloyd Pique32cbe282018-10-19 13:09:22 -07002126 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2127 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002128 return;
2129 }
2130
2131 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002132 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002133 if (mHasPoweredOff) {
2134 mHasPoweredOff = false;
2135 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002136 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002137 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002138 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002139 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002140 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2141 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002142 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002143 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002144 }
David Sodman4a36e932017-11-07 14:29:47 -08002145 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002146
2147 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002148 }
David Sodman4a36e932017-11-07 14:29:47 -08002149 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002150 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002151
2152 {
2153 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002155 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002156 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002157 if (refillCount > 0) {
2158 const size_t offset = mTexturePool.size();
2159 mTexturePool.resize(mTexturePoolSize);
2160 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2161 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2162 }
Ady Abraham8164d482019-01-11 14:47:59 -08002163 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002164 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002165
Marissa Wallfda30bb2018-10-12 11:34:28 -07002166 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002167 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002168
2169 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170}
Ady Abraham8164d482019-01-11 14:47:59 -08002171#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002172
Vishnu Nair4351ad52019-02-11 14:13:02 -08002173void SurfaceFlinger::computeLayerBounds() {
2174 for (const auto& pair : mDisplays) {
2175 const auto& displayDevice = pair.second;
2176 const auto display = displayDevice->getCompositionDisplay();
2177 for (const auto& layer : mDrawingState.layersSortedByZ) {
2178 // only consider the layers on the given layer stack
2179 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002180 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002181 }
2182
2183 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2184 }
2185 }
2186}
2187
Mathias Agopiancd60f992012-08-16 16:28:27 -07002188void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 ATRACE_CALL();
2190 ALOGV("rebuildLayerStacks");
2191
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002192 // We need to clear these out now as these may be holding on to a
2193 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2194 // also holds a reference. When the set of visible layers is recomputed,
2195 // some layers may be destroyed if the only thing keeping them alive was
2196 // that list of visible layers associated with each display. The layer
2197 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2198 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2199 for (const auto& [token, display] : mDisplays) {
2200 getBE().mCompositionInfo[token].clear();
2201 }
2202
Mathias Agopiancd60f992012-08-16 16:28:27 -07002203 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002205 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002206 mVisibleRegionsDirty = false;
2207 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002208
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002209 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002210 const auto& displayDevice = pair.second;
2211 auto display = displayDevice->getCompositionDisplay();
2212 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002213 Region opaqueRegion;
2214 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002215 compositionengine::Output::OutputLayers layersSortedByZ;
2216 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002217 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002218 const ui::Transform& tr = displayState.transform;
2219 const Rect bounds = displayState.bounds;
2220 if (displayState.isEnabled) {
2221 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002222
Jeff Sharkey76488112017-02-27 14:15:18 -07002223 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002224 auto compositionLayer = layer->getCompositionLayer();
2225 if (compositionLayer == nullptr) {
2226 return;
2227 }
2228
Lloyd Pique32cbe282018-10-19 13:09:22 -07002229 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002230 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2231 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2232
Lloyd Pique07e33212018-12-18 16:33:37 -08002233 bool needsOutputLayer = false;
2234
Lloyd Piqueef36b002019-01-23 17:52:04 -08002235 if (display->belongsInOutput(layer->getLayerStack(),
2236 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002237 Region drawRegion(tr.transform(
2238 layer->visibleNonTransparentRegion));
2239 drawRegion.andSelf(bounds);
2240 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002241 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002242 }
Chia-I Wu83806892017-11-16 10:50:20 -08002243 }
2244
Lloyd Pique07e33212018-12-18 16:33:37 -08002245 if (needsOutputLayer) {
2246 layersSortedByZ.emplace_back(
2247 display->getOrCreateOutputLayer(displayId, compositionLayer,
2248 layerFE));
2249 deprecated_layersSortedByZ.add(layer);
2250
2251 auto& outputLayerState = layersSortedByZ.back()->editState();
2252 outputLayerState.visibleRegion =
2253 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2254 } else if (displayId) {
2255 // For layers that are being removed from a HWC display,
2256 // and that have queued frames, add them to a a list of
2257 // released layers so we can properly set a fence.
2258 bool hasExistingOutputLayer =
2259 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2260 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2261 mLayersWithQueuedFrames.cend(),
2262 layer) != mLayersWithQueuedFrames.cend();
2263
2264 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002265 layersNeedingFences.add(layer);
2266 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002267 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002268 });
2269 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002270
2271 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2272
2273 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002274 displayDevice->setLayersNeedingFences(layersNeedingFences);
2275
2276 Region undefinedRegion{bounds};
2277 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2278
2279 display->editState().undefinedRegion = undefinedRegion;
2280 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002281 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002282 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002283}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002284
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002285// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002287// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002289// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002290// The returned HDR data space is one of
2291// - Dataspace::UNKNOWN
2292// - Dataspace::BT2020_HLG
2293// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002294Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2295 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002296 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002297 *outHdrDataSpace = Dataspace::UNKNOWN;
2298
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002299 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002300 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301 case Dataspace::V0_SCRGB:
2302 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002303 case Dataspace::BT2020:
2304 case Dataspace::BT2020_ITU:
2305 case Dataspace::BT2020_LINEAR:
2306 case Dataspace::DISPLAY_BT2020:
2307 bestDataSpace = Dataspace::DISPLAY_BT2020;
2308 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002309 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002310 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002312 case Dataspace::BT2020_PQ:
2313 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002314 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002317 case Dataspace::BT2020_HLG:
2318 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002319 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320 // When there's mixed PQ content and HLG content, we set the HDR
2321 // data space to be BT2020_PQ and convert HLG to PQ.
2322 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2323 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002324 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325 break;
2326 default:
2327 break;
2328 }
Romain Guy54f154a2017-10-24 21:40:32 +01002329 }
2330
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002332}
2333
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2336 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2338 *outMode = ColorMode::NATIVE;
2339 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002340 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002342 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002343
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002344 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002347 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2348
Peiyong Lina3ea5592019-02-10 14:45:00 -08002349 switch (mForceColorMode) {
2350 case ColorMode::SRGB:
2351 bestDataSpace = Dataspace::V0_SRGB;
2352 break;
2353 case ColorMode::DISPLAY_P3:
2354 bestDataSpace = Dataspace::DISPLAY_P3;
2355 break;
2356 default:
2357 break;
2358 }
2359
Peiyong Lindfde5112018-06-05 10:58:41 -07002360 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002361 const bool isHdr =
2362 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002363 if (isHdr) {
2364 bestDataSpace = hdrDataSpace;
2365 }
2366
Chia-I Wu0d711262018-05-21 15:19:35 -07002367 RenderIntent intent;
2368 switch (mDisplayColorSetting) {
2369 case DisplayColorSetting::MANAGED:
2370 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002371 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002372 break;
2373 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002374 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002375 break;
2376 default: // vendor display color setting
2377 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2378 break;
2379 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002380
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002381 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002382}
2383
Lloyd Pique32cbe282018-10-19 13:09:22 -07002384void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2385 auto display = displayDevice->getCompositionDisplay();
2386 const auto& displayState = display->getState();
2387
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002388 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2390 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002391
David Sodmanfa9b2af2017-12-24 13:28:59 -08002392 // If nothing has changed (!dirty), don't recompose.
2393 // If something changed, but we don't currently have any visible layers,
2394 // and didn't when we last did a composition, then skip it this time.
2395 // The second rule does two things:
2396 // - When all layers are removed from a display, we'll emit one black
2397 // frame, then nothing more until we get new layers.
2398 // - When a display is created with a private layer stack, we won't
2399 // emit any black frames until a layer is added to the layer stack.
2400 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002401
Dominik Laskowski075d3172018-05-24 15:50:06 -07002402 const char flagPrefix[] = {'-', '+'};
2403 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2405 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2406 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2407 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002408
Lloyd Pique31cb2942018-10-19 17:23:03 -07002409 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002410
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002412 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002413 }
2414}
2415
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2417 auto display = displayDevice->getCompositionDisplay();
2418 const auto& displayState = display->getState();
2419
2420 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002421 return;
David Sodman2b406362017-12-15 13:33:47 -08002422 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002423
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002424 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002426 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002427}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002428
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002430 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002431 ALOGV("doComposition");
2432
Lloyd Pique32cbe282018-10-19 13:09:22 -07002433 auto display = displayDevice->getCompositionDisplay();
2434 const auto& displayState = display->getState();
2435
2436 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002438 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002439
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002444 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002445 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002447}
2448
David Sodmanfa9b2af2017-12-24 13:28:59 -08002449void SurfaceFlinger::postFrame()
2450{
2451 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 const auto display = getDefaultDisplayDeviceLocked();
2453 if (display && getHwComposer().isConnected(*display->getId())) {
2454 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002455 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2456 logFrameStats();
2457 }
2458 }
2459}
2460
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002462 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002463 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002464
Lloyd Pique32cbe282018-10-19 13:09:22 -07002465 auto display = displayDevice->getCompositionDisplay();
2466 const auto& displayState = display->getState();
2467 const auto displayId = display->getId();
2468
David Sodmanfa9b2af2017-12-24 13:28:59 -08002469 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 if (displayId) {
2473 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002474 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002475 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002476 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002477 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002478
Chia-I Wu7b549592017-11-15 09:14:57 -08002479 // The layer buffer from the previous frame (if any) is released
2480 // by HWC only when the release fence from this frame (if any) is
2481 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002482 if (displayId && layer->hasHwcLayer(displayDevice)) {
2483 releaseFence =
2484 getHwComposer().getLayerReleaseFence(*displayId,
2485 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002486 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002487
2488 // If the layer was client composited in the previous frame, we
2489 // need to merge with the previous client target acquire fence.
2490 // Since we do not track that, always merge with the current
2491 // client target acquire fence when it is available, even though
2492 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002493 if (layer->getCompositionType(displayDevice) ==
2494 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002495 releaseFence =
2496 Fence::merge("LayerRelease", releaseFence,
2497 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002498 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002499
David Sodman15094112018-10-11 09:39:37 -07002500 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 }
Chia-I Wu83806892017-11-16 10:50:20 -08002502
2503 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002505 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002506 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002507 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002508 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002509 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002510 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002511 }
2512 }
2513
Dominik Laskowski075d3172018-05-24 15:50:06 -07002514 if (displayId) {
2515 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002516 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002517 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518}
2519
Mathias Agopian87baae12012-07-31 12:38:26 -07002520void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521{
Mathias Agopian841cde52012-03-01 15:44:37 -08002522 ATRACE_CALL();
2523
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002524 // here we keep a copy of the drawing state (that is the state that's
2525 // going to be overwritten by handleTransactionLocked()) outside of
2526 // mStateLock so that the side-effects of the State assignment
2527 // don't happen with mStateLock held (which can cause deadlocks).
2528 State drawingState(mDrawingState);
2529
Mathias Agopianca4d3602011-05-19 15:38:14 -07002530 Mutex::Autolock _l(mStateLock);
2531 const nsecs_t now = systemTime();
2532 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533
Mathias Agopianca4d3602011-05-19 15:38:14 -07002534 // Here we're guaranteed that some transaction flags are set
2535 // so we can call handleTransactionLocked() unconditionally.
2536 // We call getTransactionFlags(), which will also clear the flags,
2537 // with mStateLock held to guarantee that mCurrentState won't change
2538 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002539
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002540 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002541 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002542 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002543
Mathias Agopianca4d3602011-05-19 15:38:14 -07002544 mLastTransactionTime = systemTime() - now;
2545 mDebugInTransaction = 0;
2546 invalidateHwcGeometry();
2547 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002548}
2549
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2551 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 const std::optional<DisplayIdentificationInfo> info =
2553 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002556 continue;
2557 }
2558
Lloyd Piqueba04e622017-12-14 17:11:26 -08002559 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002561 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 mPhysicalDisplayTokens[info->id] = new BBinder();
2563 DisplayDeviceState state;
2564 state.displayId = info->id;
2565 state.isSecure = true; // All physical displays are currently considered secure.
2566 state.displayName = info->name;
2567 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2568 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002569 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002570 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002571 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002572
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2574 if (index >= 0) {
2575 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2576 mInterceptor->saveDisplayDeletion(state.sequenceId);
2577 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002578 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002580 }
2581
2582 processDisplayChangesLocked();
2583 }
2584
2585 mPendingHotplugEvents.clear();
2586}
2587
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002588void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002589 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2590 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002591}
2592
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002595 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 const sp<IGraphicBufferProducer>& producer) {
2597 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002598 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002600 creationArgs.isSecure = state.isSecure;
2601 creationArgs.displaySurface = dispSurface;
2602 creationArgs.hasWideColorGamut = false;
2603 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002604
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002605 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 creationArgs.isPrimary = isInternalDisplay;
2607
2608 if (useColorManagement && displayId) {
2609 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002611 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002612 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002614
Dominik Laskowski7e045462018-05-30 13:02:02 -07002615 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002616 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002617 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618 }
tangrobin6753a022018-08-10 10:58:54 +08002619 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620
Dominik Laskowski075d3172018-05-24 15:50:06 -07002621 if (displayId) {
2622 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002623 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002625 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626
Lloyd Pique90c115d2018-09-18 21:39:42 -07002627 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002629 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630
Lloyd Pique99d3da52018-01-22 17:48:03 -08002631 // Make sure that composition can never be stalled by a virtual display
2632 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002633 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002634 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2636 }
2637
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 creationArgs.displayInstallOrientation =
2639 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002640
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002642 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643
Lloyd Pique90c115d2018-09-18 21:39:42 -07002644 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002645
2646 if (maxFrameBufferAcquiredBuffers >= 3) {
2647 nativeWindowSurface->preallocateBuffers();
2648 }
2649
2650 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002651 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002652 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002654 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002656 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2657 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002658 if (!state.isVirtual()) {
2659 LOG_ALWAYS_FATAL_IF(!displayId);
2660 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002661 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002662
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002663 display->setLayerStack(state.layerStack);
2664 display->setProjection(state.orientation, state.viewport, state.frame);
2665 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002667 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002668}
2669
Lloyd Pique347200f2017-12-14 17:00:15 -08002670void SurfaceFlinger::processDisplayChangesLocked() {
2671 // here we take advantage of Vector's copy-on-write semantics to
2672 // improve performance by skipping the transaction entirely when
2673 // know that the lists are identical
2674 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2675 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2676 if (!curr.isIdenticalTo(draw)) {
2677 mVisibleRegionsDirty = true;
2678 const size_t cc = curr.size();
2679 size_t dc = draw.size();
2680
2681 // find the displays that were removed
2682 // (ie: in drawing state but not in current state)
2683 // also handle displays that changed
2684 // (ie: displays that are in both lists)
2685 for (size_t i = 0; i < dc;) {
2686 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2687 if (j < 0) {
2688 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002690 // Save display ID before disconnecting.
2691 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002692 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002693
2694 if (!display->isVirtual()) {
2695 LOG_ALWAYS_FATAL_IF(!displayId);
2696 dispatchDisplayHotplugEvent(displayId->value, false);
2697 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002698 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002699
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 } else {
2702 // this display is in both lists. see if something changed.
2703 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2706 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2707 if (state_binder != draw_binder) {
2708 // changing the surface is like destroying and
2709 // recreating the DisplayDevice, so we just remove it
2710 // from the drawing state, so that it get re-added
2711 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002713 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002715 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002716 mDrawingState.displays.removeItemsAt(i);
2717 dc--;
2718 // at this point we must loop to the next item
2719 continue;
2720 }
2721
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002724 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 }
2726 if ((state.orientation != draw[i].orientation) ||
2727 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 }
2730 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 }
2733 }
2734 }
2735 ++i;
2736 }
2737
2738 // find displays that were added
2739 // (ie: in current state but not in drawing state)
2740 for (size_t i = 0; i < cc; i++) {
2741 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2742 const DisplayDeviceState& state(curr[i]);
2743
Lloyd Pique542307f2018-10-19 13:24:08 -07002744 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 sp<IGraphicBufferProducer> producer;
2746 sp<IGraphicBufferProducer> bqProducer;
2747 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002748 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749
Dominik Laskowski075d3172018-05-24 15:50:06 -07002750 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002751 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 // Virtual displays without a surface are dormant:
2753 // they have external state (layer stack, projection,
2754 // etc.) but no internal state (i.e. a DisplayDevice).
2755 if (state.surface != nullptr) {
2756 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002757 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 int width = 0;
2759 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2760 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2761 int height = 0;
2762 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2763 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2764 int intFormat = 0;
2765 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2766 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002767 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 displayId =
2770 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 }
2772
2773 // TODO: Plumb requested format back up to consumer
2774
2775 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 bqProducer, bqConsumer,
2778 state.displayName);
2779
2780 dispSurface = vds;
2781 producer = vds;
2782 }
2783 } else {
2784 ALOGE_IF(state.surface != nullptr,
2785 "adding a supported display, but rendering "
2786 "surface is provided (%p), ignoring it",
2787 state.surface.get());
2788
Dominik Laskowski075d3172018-05-24 15:50:06 -07002789 displayId = state.displayId;
2790 LOG_ALWAYS_FATAL_IF(!displayId);
2791 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 producer = bqProducer;
2793 }
2794
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002795 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002796 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002797 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002798 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002799 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002800 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002801 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002802 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002803 }
2804 }
2805 }
2806 }
2807 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002808
2809 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002810}
2811
Mathias Agopian87baae12012-07-31 12:38:26 -07002812void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002813{
Dan Stoza7dde5992015-05-22 09:51:44 -07002814 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002815 mCurrentState.traverseInZOrder([](Layer* layer) {
2816 layer->notifyAvailableFrames();
2817 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002818
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819 /*
2820 * Traversal of the children
2821 * (perform the transaction for each of them if needed)
2822 */
2823
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002825 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002827 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
2829 const uint32_t flags = layer->doTransaction(0);
2830 if (flags & Layer::eVisibleRegion)
2831 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002832
2833 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002834 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002835 }
Robert Carr2047fae2016-11-28 14:09:09 -08002836 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837 }
2838
2839 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002840 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 */
2842
Mathias Agopiane57f2922012-08-09 16:29:12 -07002843 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002844 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002845 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002846 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002848 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002849 // The transform hint might have changed for some layers
2850 // (either because a display has changed, or because a layer
2851 // as changed).
2852 //
2853 // Walk through all the layers in currentLayers,
2854 // and update their transform hint.
2855 //
2856 // If a layer is visible only on a single display, then that
2857 // display is used to calculate the hint, otherwise we use the
2858 // default display.
2859 //
2860 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2861 // the hint is set before we acquire a buffer from the surface texture.
2862 //
2863 // NOTE: layer transactions have taken place already, so we use their
2864 // drawing state. However, SurfaceFlinger's own transaction has not
2865 // happened yet, so we must use the current state layer list
2866 // (soon to become the drawing state list).
2867 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002869 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002870 bool first = true;
2871 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002872 // NOTE: we rely on the fact that layers are sorted by
2873 // layerStack first (so we don't have to traverse the list
2874 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002875 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002876 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002877 currentlayerStack = layerStack;
2878 // figure out if this layerstack is mirrored
2879 // (more than one display) if so, pick the default display,
2880 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 hintDisplay = nullptr;
2882 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002883 if (display->getCompositionDisplay()
2884 ->belongsInOutput(layer->getLayerStack(),
2885 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002886 if (hintDisplay) {
2887 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002888 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002889 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002890 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002891 }
2892 }
2893 }
2894 }
Chet Haase91d25932013-04-11 15:24:55 -07002895
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002897 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2898 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002899
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002900 // could be null when this layer is using a layerStack
2901 // that is not visible on any display. Also can occur at
2902 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002904 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002905
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002907 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002908 if (hintDisplay) {
2909 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002910 }
Robert Carr2047fae2016-11-28 14:09:09 -08002911
2912 first = false;
2913 });
Mathias Agopian84300952012-11-21 16:02:13 -08002914 }
2915
2916
Mathias Agopian3559b072012-08-15 13:46:03 -07002917 /*
2918 * Perform our own transaction if needed
2919 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920
2921 if (mLayersAdded) {
2922 mLayersAdded = false;
2923 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002924 mVisibleRegionsDirty = true;
2925 }
2926
2927 // some layers might have been removed, so
2928 // we need to update the regions they're exposing.
2929 if (mLayersRemoved) {
2930 mLayersRemoved = false;
2931 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002932 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002933 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002934 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002936 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002937 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002938 }
Robert Carr2047fae2016-11-28 14:09:09 -08002939 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940 }
2941
Vishnu Nairec0ab382019-02-13 15:32:56 -08002942 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002944}
2945
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002946void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002947 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002948 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002949 return;
2950 }
2951
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002952 if (mVisibleRegionsDirty || mInputInfoChanged) {
2953 mInputInfoChanged = false;
2954 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002955 } else if (mInputWindowCommands.syncInputWindows) {
2956 // If the caller requested to sync input windows, but there are no
2957 // changes to input windows, notify immediately.
2958 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002959 }
2960
2961 executeInputWindowCommands();
2962}
2963
2964void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002965 Vector<InputWindowInfo> inputHandles;
2966
2967 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2968 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002969 // When calculating the screen bounds we ignore the transparent region since it may
2970 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002971 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002972 }
2973 });
chaviw291d88a2019-02-14 10:33:58 -08002974
2975 mInputFlinger->setInputWindows(inputHandles,
2976 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2977 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002978}
2979
Vishnu Nairec0ab382019-02-13 15:32:56 -08002980void SurfaceFlinger::commitInputWindowCommands() {
2981 mInputWindowCommands.merge(mPendingInputWindowCommands);
2982 mPendingInputWindowCommands.clear();
2983}
2984
chaviwfbe5d9c2018-12-26 12:23:37 -08002985void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002986 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2987 if (transferTouchFocusCommand.fromToken != nullptr &&
2988 transferTouchFocusCommand.toToken != nullptr &&
2989 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2990 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2991 transferTouchFocusCommand.toToken);
2992 }
2993 }
2994
2995 mInputWindowCommands.clear();
2996}
2997
Riley Andrews03414a12014-07-01 14:22:59 -07002998void SurfaceFlinger::updateCursorAsync()
2999{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003000 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003001 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003002 continue;
3003 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003004
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003005 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3006 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003007 }
3008 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009}
3010
chaviw61626f22018-11-15 16:26:27 -08003011void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3012 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003013 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003014 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003015 }
3016 layer->releasePendingBuffer(systemTime());
3017}
3018
Mathias Agopian4fec8732012-06-29 14:12:52 -07003019void SurfaceFlinger::commitTransaction()
3020{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003021 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003022 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003023 for (const auto& l : mLayersPendingRemoval) {
3024 recordBufferingStats(l->getName().string(),
3025 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003026
Lloyd Pique07e33212018-12-18 16:33:37 -08003027 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003028 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003029 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003030 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003031 }
3032 mLayersPendingRemoval.clear();
3033 }
3034
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003035 // If this transaction is part of a window animation then the next frame
3036 // we composite should be considered an animation as well.
3037 mAnimCompositionPending = mAnimTransactionPending;
3038
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003040 // clear the "changed" flags in current state
3041 mCurrentState.colorMatrixChanged = false;
3042
Robert Carr1f0a16a2016-10-24 16:27:39 -07003043 mDrawingState.traverseInZOrder([](Layer* layer) {
3044 layer->commitChildList();
3045 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003046 mTransactionPending = false;
3047 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003048 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049}
3050
Lloyd Pique32cbe282018-10-19 13:09:22 -07003051void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003052 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003053 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003055
Lloyd Pique32cbe282018-10-19 13:09:22 -07003056 auto display = displayDevice->getCompositionDisplay();
3057
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 Region aboveOpaqueLayers;
3059 Region aboveCoveredLayers;
3060 Region dirty;
3061
Mathias Agopian87baae12012-07-31 12:38:26 -07003062 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063
Robert Carr2047fae2016-11-28 14:09:09 -08003064 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003065 // start with the whole surface at its current location
3066 const Layer::State& s(layer->getDrawingState());
3067
Jesse Hall01e29052013-02-19 16:13:35 -08003068 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003069 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003070 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003071 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003072
Mathias Agopianab028732010-03-16 16:41:46 -07003073 /*
3074 * opaqueRegion: area of a surface that is fully opaque.
3075 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003077
3078 /*
3079 * visibleRegion: area of a surface that is visible on screen
3080 * and not fully transparent. This is essentially the layer's
3081 * footprint minus the opaque regions above it.
3082 * Areas covered by a translucent surface are considered visible.
3083 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003085
3086 /*
3087 * coveredRegion: area of a surface that is covered by all
3088 * visible regions above it (which includes the translucent areas).
3089 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003091
Jesse Halla8026d22012-09-25 13:25:04 -07003092 /*
3093 * transparentRegion: area of a surface that is hinted to be completely
3094 * transparent. This is only used to tell when the layer has no visible
3095 * non-transparent regions and can be removed from the layer list. It
3096 * does not affect the visibleRegion of this layer or any layers
3097 * beneath it. The hint may not be correct if apps don't respect the
3098 * SurfaceView restrictions (which, sadly, some don't).
3099 */
3100 Region transparentRegion;
3101
Mathias Agopianab028732010-03-16 16:41:46 -07003102
3103 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003104 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003105 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003106 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003109 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003110 if (!visibleRegion.isEmpty()) {
3111 // Remove the transparent area from the visible region
3112 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003113 if (tr.preserveRects()) {
3114 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003115 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003117 // transformation too complex, can't do the
3118 // transparent region optimization.
3119 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003120 }
Mathias Agopianab028732010-03-16 16:41:46 -07003121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122
Mathias Agopianab028732010-03-16 16:41:46 -07003123 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003125 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003126 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003127 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003128 // the opaque region is the layer's footprint
3129 opaqueRegion = visibleRegion;
3130 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 }
3132 }
3133
Robert Carre5f4f692018-01-12 13:12:28 -08003134 if (visibleRegion.isEmpty()) {
3135 layer->clearVisibilityRegions();
3136 return;
3137 }
3138
Mathias Agopianab028732010-03-16 16:41:46 -07003139 // Clip the covered region to the visible region
3140 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3141
3142 // Update aboveCoveredLayers for next (lower) layer
3143 aboveCoveredLayers.orSelf(visibleRegion);
3144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 // subtract the opaque region covered by the layers above us
3146 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147
3148 // compute this layer's dirty region
3149 if (layer->contentDirty) {
3150 // we need to invalidate the whole region
3151 dirty = visibleRegion;
3152 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 layer->contentDirty = false;
3155 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003156 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003157 * the exposed region consists of two components:
3158 * 1) what's VISIBLE now and was COVERED before
3159 * 2) what's EXPOSED now less what was EXPOSED before
3160 *
3161 * note that (1) is conservative, we start with the whole
3162 * visible region but only keep what used to be covered by
3163 * something -- which mean it may have been exposed.
3164 *
3165 * (2) handles areas that were not covered by anything but got
3166 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003167 */
Mathias Agopianab028732010-03-16 16:41:46 -07003168 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003169 const Region oldVisibleRegion = layer->visibleRegion;
3170 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003171 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3172 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173 }
3174 dirty.subtractSelf(aboveOpaqueLayers);
3175
3176 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003177 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178
Mathias Agopianab028732010-03-16 16:41:46 -07003179 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003181
Jesse Halla8026d22012-09-25 13:25:04 -07003182 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 layer->setVisibleRegion(visibleRegion);
3184 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003185 layer->setVisibleNonTransparentRegion(
3186 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003187 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188
Mathias Agopian87baae12012-07-31 12:38:26 -07003189 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190}
3191
Chia-I Wuab0c3192017-08-01 11:29:00 -07003192void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003193 for (const auto& [token, displayDevice] : mDisplays) {
3194 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003195 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003196 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003197 }
3198 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003199}
3200
Daniel Solomon42d04562019-01-20 21:03:19 -08003201void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3202 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3203 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3204 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3205 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3206 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3207 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3208 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3209 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3210 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3211 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3212 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3213 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3214}
3215
Dan Stoza6b9454d2014-11-07 16:00:59 -08003216bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003218 ALOGV("handlePageFlip");
3219
Brian Andersond6927fb2016-07-23 23:37:30 -07003220 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221
Mathias Agopian4fec8732012-06-29 14:12:52 -07003222 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003223 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003224 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003225
3226 // Store the set of layers that need updates. This set must not change as
3227 // buffers are being latched, as this could result in a deadlock.
3228 // Example: Two producers share the same command stream and:
3229 // 1.) Layer 0 is latched
3230 // 2.) Layer 0 gets a new frame
3231 // 2.) Layer 1 gets a new frame
3232 // 3.) Layer 1 is latched.
3233 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3234 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003235 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003236 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003237 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003238 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003239 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003240 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003241 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003242 } else {
3243 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003244 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003245 } else {
3246 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003247 }
Robert Carr2047fae2016-11-28 14:09:09 -08003248 });
3249
Lloyd Piquef2c79392018-12-20 16:23:33 -08003250 if (!mLayersWithQueuedFrames.empty()) {
3251 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3252 // writes to Layer current state. See also b/119481871
3253 Mutex::Autolock lock(mStateLock);
3254
3255 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003256 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003257 mLayersPendingRefresh.push_back(layer);
3258 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003259 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003260 if (layer->isBufferLatched()) {
3261 newDataLatched = true;
3262 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003263 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003264 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003265
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003266 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267
3268 // If we will need to wake up at some time in the future to deal with a
3269 // queued frame that shouldn't be displayed during this vsync period, wake
3270 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003271 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003272 signalLayerUpdate();
3273 }
3274
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003275 // enter boot animation on first buffer latch
3276 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3277 ALOGI("Enter boot animation");
3278 mBootStage = BootStage::BOOTANIMATION;
3279 }
3280
Dan Stoza6b9454d2014-11-07 16:00:59 -08003281 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003282 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283}
3284
Mathias Agopianad456f92011-01-13 17:53:01 -08003285void SurfaceFlinger::invalidateHwcGeometry()
3286{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003287 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003288}
3289
Lloyd Pique32cbe282018-10-19 13:09:22 -07003290void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003291 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003292 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003293 // We only need to actually compose the display if:
3294 // 1) It is being handled by hardware composer, which may need this to
3295 // keep its virtual display state machine in sync, or
3296 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003297 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003299 return;
3300 }
3301
Dan Stoza9e56aa02015-11-02 13:00:03 -08003302 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003303 base::unique_fd readyFence;
3304 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003305
3306 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003307 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003308}
3309
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003310bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3311 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003312 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003313 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003314
Lloyd Pique32cbe282018-10-19 13:09:22 -07003315 auto display = displayDevice->getCompositionDisplay();
3316 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003317 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003318
3319 const Region bounds(displayState.bounds);
3320 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003321 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003322 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003323
Peiyong Lind3788632018-09-18 16:01:31 -07003324 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003325 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003326
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003327 renderengine::DisplaySettings clientCompositionDisplay;
3328 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3329 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003330
Dan Stoza9e56aa02015-11-02 13:00:03 -08003331 if (hasClientComposition) {
3332 ALOGV("hasClientComposition");
3333
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003334 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003335
3336 if (buf == nullptr) {
3337 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3338 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003339 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003340 return false;
3341 }
3342
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003343 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3344 clientCompositionDisplay.clip = displayState.scissor;
3345 const ui::Transform& displayTransform = displayState.transform;
3346 mat4 m;
3347 m[0][0] = displayTransform[0][0];
3348 m[0][1] = displayTransform[0][1];
3349 m[0][3] = displayTransform[0][2];
3350 m[1][0] = displayTransform[1][0];
3351 m[1][1] = displayTransform[1][1];
3352 m[1][3] = displayTransform[1][2];
3353 m[3][0] = displayTransform[2][0];
3354 m[3][1] = displayTransform[2][1];
3355 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003356
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003357 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003358
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003359 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003360 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003361 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003362 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003363 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003364 clientCompositionDisplay.outputDataspace = outputDataspace;
3365 clientCompositionDisplay.maxLuminance =
3366 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003367
Lloyd Pique441d5042018-10-18 16:49:51 -07003368 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003369 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003370 getHwComposer()
3371 .hasDisplayCapability(displayId,
3372 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003373
Peiyong Lind3788632018-09-18 16:01:31 -07003374 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003375 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3376 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003377 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003378 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003379 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003380
Mathias Agopian85d751c2012-08-29 16:59:24 -07003381 /*
3382 * and then, render the layers targeted at the framebuffer
3383 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003384
Dan Stoza9e56aa02015-11-02 13:00:03 -08003385 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003386 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003387 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003388 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003389 const Region viewportRegion(displayState.viewport);
3390 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003391 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003392 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003393 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003394 switch (layer->getCompositionType(displayDevice)) {
3395 case Hwc2::IComposerClient::Composition::CURSOR:
3396 case Hwc2::IComposerClient::Composition::DEVICE:
3397 case Hwc2::IComposerClient::Composition::SIDEBAND:
3398 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003399 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003400 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003401 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003402 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003403 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003404 // never clear the very first layer since we're
3405 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003406 renderengine::LayerSettings layerSettings;
3407 Region dummyRegion;
3408 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3409 layerSettings);
3410
3411 if (prepared) {
3412 layerSettings.source.buffer.buffer = nullptr;
3413 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3414 layerSettings.alpha = half(0.0);
3415 layerSettings.disableBlending = true;
3416 clientCompositionLayers.push_back(layerSettings);
3417 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003418 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003419 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003420 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003421 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003422 renderengine::LayerSettings layerSettings;
3423 bool prepared =
3424 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3425 if (prepared) {
3426 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003427 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003428 break;
3429 }
3430 default:
3431 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003432 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 } else {
3434 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003435 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003436 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003437 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003438
Alec Mouri820c7402019-01-23 13:02:39 -08003439 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003440 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003441 clientCompositionDisplay.clearRegion = clearRegion;
3442 if (!debugRegion.isEmpty()) {
3443 Region::const_iterator it = debugRegion.begin();
3444 Region::const_iterator end = debugRegion.end();
3445 while (it != end) {
3446 const Rect& rect = *it++;
3447 renderengine::LayerSettings layerSettings;
3448 layerSettings.source.buffer.buffer = nullptr;
3449 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3450 layerSettings.geometry.boundaries = rect.toFloatRect();
3451 layerSettings.alpha = half(1.0);
3452 clientCompositionLayers.push_back(layerSettings);
3453 }
3454 }
3455 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3456 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003457 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003458 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003459}
3460
Chia-I Wu28e3a252018-09-07 12:05:02 -07003461void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003462 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003463 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003464}
3465
Dan Stoza7d89d062015-04-30 13:29:25 -07003466status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003467 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003468 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003469 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003470 const sp<Layer>& parent,
3471 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003472{
Dan Stoza7d89d062015-04-30 13:29:25 -07003473 // add this layer to the current state list
3474 {
3475 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003476 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003477 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3478 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003479 return NO_MEMORY;
3480 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003481 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003482 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003483 } else if (parent == nullptr) {
3484 lbc->onRemovedFromCurrentState();
3485 } else if (parent->isRemovedFromCurrentState()) {
3486 parent->addChild(lbc);
3487 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003488 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003489 parent->addChild(lbc);
3490 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003491
Yiwei Zhang243b3782018-05-15 17:40:04 -07003492 if (gbc != nullptr) {
3493 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3494 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3495 mMaxGraphicBufferProducerListSize,
3496 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3497 mGraphicBufferProducerList.size(),
3498 mMaxGraphicBufferProducerListSize, mNumLayers);
3499 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003500 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003501 }
3502
Mathias Agopian96f08192010-06-02 23:28:45 -07003503 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003504 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003505
Dan Stoza7d89d062015-04-30 13:29:25 -07003506 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003507}
3508
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003509uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003510 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003511}
3512
Mathias Agopian3f844832013-08-07 21:24:32 -07003513uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003514 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515}
3516
Mathias Agopian3f844832013-08-07 21:24:32 -07003517uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003518 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003519}
3520
3521uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003522 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003523 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003524 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003526 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527 }
3528 return old;
3529}
3530
Marissa Wall713b63f2018-10-17 15:42:43 -07003531bool SurfaceFlinger::flushTransactionQueues() {
3532 Mutex::Autolock _l(mStateLock);
3533 auto it = mTransactionQueues.begin();
3534 while (it != mTransactionQueues.end()) {
3535 auto& [applyToken, transactionQueue] = *it;
3536
3537 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003538 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3539 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003540 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003541 break;
3542 }
Robert Carr14167e02019-02-13 13:50:55 -08003543 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003544 transactionQueue.pop();
3545 }
3546
3547 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3548 }
3549 return mTransactionQueues.empty();
3550}
3551
chaviwca27f252018-02-06 16:46:39 -08003552bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3553 for (const ComposerState& state : states) {
3554 // Here we need to check that the interface we're given is indeed
3555 // one of our own. A malicious client could give us a nullptr
3556 // IInterface, or one of its own or even one of our own but a
3557 // different type. All these situations would cause us to crash.
3558 if (state.client == nullptr) {
3559 return true;
3560 }
3561
3562 sp<IBinder> binder = IInterface::asBinder(state.client);
3563 if (binder == nullptr) {
3564 return true;
3565 }
3566
3567 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3568 return true;
3569 }
3570 }
3571 return false;
3572}
3573
Marissa Wall17b4e452018-12-26 16:32:34 -08003574bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3575 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003576 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003577 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3578 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3579 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3580 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3581 return false;
3582 }
3583
Marissa Wall713b63f2018-10-17 15:42:43 -07003584 for (const ComposerState& state : states) {
3585 const layer_state_t& s = state.state;
3586 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3587 continue;
3588 }
3589 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003590 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003591 }
3592 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003593 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003594}
3595
3596void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3597 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003598 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003599 const InputWindowCommands& inputWindowCommands,
3600 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003601 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003602
3603 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3604
Mathias Agopian698c0872011-06-28 19:09:31 -07003605 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003606
chaviwca27f252018-02-06 16:46:39 -08003607 if (containsAnyInvalidClientState(states)) {
3608 return;
3609 }
3610
Marissa Wall713b63f2018-10-17 15:42:43 -07003611 // If its TransactionQueue already has a pending TransactionState or if it is pending
3612 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003613 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003614 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3615 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003616 setTransactionFlags(eTransactionNeeded);
3617 return;
3618 }
3619
Robert Carr14167e02019-02-13 13:50:55 -08003620 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003621}
3622
3623void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003624 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003625 const InputWindowCommands& inputWindowCommands,
3626 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003627 uint32_t transactionFlags = 0;
3628
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003629 if (flags & eAnimation) {
3630 // For window updates that are part of an animation we must wait for
3631 // previous animation "frames" to be handled.
3632 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003633 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003634 if (CC_UNLIKELY(err != NO_ERROR)) {
3635 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003636 // caller after a few seconds.
3637 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3638 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003639 mAnimTransactionPending = false;
3640 break;
3641 }
3642 }
3643 }
3644
chaviwca27f252018-02-06 16:46:39 -08003645 for (const DisplayState& display : displays) {
3646 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003647 }
3648
Marissa Walle2ffb422018-10-12 11:33:52 -07003649 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003650 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003651 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003652 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003653 // If the state doesn't require a traversal and there are callbacks, send them now
3654 if (!(clientStateFlags & eTraversalNeeded)) {
3655 mTransactionCompletedThread.sendCallbacks();
3656 }
3657 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003658
chaviw273171b2018-12-26 11:46:30 -08003659 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3660
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003661 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3662 // anyway. This can be used as a flush mechanism for previous async transactions.
3663 // Empty animation transaction can be used to simulate back-pressure, so also force a
3664 // transaction for empty animation transactions.
3665 if (transactionFlags == 0 &&
3666 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003667 transactionFlags = eTransactionNeeded;
3668 }
3669
Mathias Agopian386aa982011-11-07 21:58:03 -08003670 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003671 if (mInterceptor->isEnabled()) {
3672 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003673 }
Irvel468051e2016-06-13 16:44:44 -07003674
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003676 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3677 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003678 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003679
3680 // if this is a synchronous transaction, wait for it to take effect
3681 // before returning.
3682 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003683 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003684 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003685 if (flags & eAnimation) {
3686 mAnimTransactionPending = true;
3687 }
chaviw95ef3c42019-02-14 10:55:09 -08003688
3689 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3690 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003691 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3692 if (CC_UNLIKELY(err != NO_ERROR)) {
3693 // just in case something goes wrong in SF, return to the
3694 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003695 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3696 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003697 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003698 break;
3699 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003700 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701 }
3702}
3703
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003704uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3705 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3706 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003707
Mathias Agopiane57f2922012-08-09 16:29:12 -07003708 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003709 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3710
3711 const uint32_t what = s.what;
3712 if (what & DisplayState::eSurfaceChanged) {
3713 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3714 state.surface = s.surface;
3715 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003716 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003717 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003718 if (what & DisplayState::eLayerStackChanged) {
3719 if (state.layerStack != s.layerStack) {
3720 state.layerStack = s.layerStack;
3721 flags |= eDisplayTransactionNeeded;
3722 }
3723 }
3724 if (what & DisplayState::eDisplayProjectionChanged) {
3725 if (state.orientation != s.orientation) {
3726 state.orientation = s.orientation;
3727 flags |= eDisplayTransactionNeeded;
3728 }
3729 if (state.frame != s.frame) {
3730 state.frame = s.frame;
3731 flags |= eDisplayTransactionNeeded;
3732 }
3733 if (state.viewport != s.viewport) {
3734 state.viewport = s.viewport;
3735 flags |= eDisplayTransactionNeeded;
3736 }
3737 }
3738 if (what & DisplayState::eDisplaySizeChanged) {
3739 if (state.width != s.width) {
3740 state.width = s.width;
3741 flags |= eDisplayTransactionNeeded;
3742 }
3743 if (state.height != s.height) {
3744 state.height = s.height;
3745 flags |= eDisplayTransactionNeeded;
3746 }
3747 }
3748
Mathias Agopiane57f2922012-08-09 16:29:12 -07003749 return flags;
3750}
3751
Robert Carr14167e02019-02-13 13:50:55 -08003752bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003753 IPCThreadState* ipc = IPCThreadState::self();
3754 const int pid = ipc->getCallingPid();
3755 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003756 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003757 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003758 return false;
3759 }
3760 return true;
3761}
3762
Robert Carr14167e02019-02-13 13:50:55 -08003763uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3764 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003765 const layer_state_t& s = composerState.state;
3766 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3767
Mathias Agopian13127d82013-03-05 17:47:11 -08003768 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003769 if (layer == nullptr) {
3770 return 0;
3771 }
3772
chaviw8b3871a2017-11-01 17:41:01 -07003773 uint32_t flags = 0;
3774
Garfield Tan8a3083e2018-12-03 13:21:07 -08003775 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003776 bool geometryAppliesWithResize =
3777 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003778
3779 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3780 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003781 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003782 layer->pushPendingState();
3783 }
3784
chaviw8b3871a2017-11-01 17:41:01 -07003785 if (what & layer_state_t::ePositionChanged) {
3786 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3787 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003788 }
chaviw8b3871a2017-11-01 17:41:01 -07003789 }
3790 if (what & layer_state_t::eLayerChanged) {
3791 // NOTE: index needs to be calculated before we update the state
3792 const auto& p = layer->getParent();
3793 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003794 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003795 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003796 mCurrentState.layersSortedByZ.removeAt(idx);
3797 mCurrentState.layersSortedByZ.add(layer);
3798 // we need traversal (state changed)
3799 // AND transaction (list changed)
3800 flags |= eTransactionNeeded|eTraversalNeeded;
3801 }
chaviw8b3871a2017-11-01 17:41:01 -07003802 } else {
3803 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003804 flags |= eTransactionNeeded|eTraversalNeeded;
3805 }
3806 }
chaviw8b3871a2017-11-01 17:41:01 -07003807 }
3808 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003809 // NOTE: index needs to be calculated before we update the state
3810 const auto& p = layer->getParent();
3811 if (p == nullptr) {
3812 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3813 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3814 mCurrentState.layersSortedByZ.removeAt(idx);
3815 mCurrentState.layersSortedByZ.add(layer);
3816 // we need traversal (state changed)
3817 // AND transaction (list changed)
3818 flags |= eTransactionNeeded|eTraversalNeeded;
3819 }
3820 } else {
3821 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3822 flags |= eTransactionNeeded|eTraversalNeeded;
3823 }
chaviw8b3871a2017-11-01 17:41:01 -07003824 }
3825 }
3826 if (what & layer_state_t::eSizeChanged) {
3827 if (layer->setSize(s.w, s.h)) {
3828 flags |= eTraversalNeeded;
3829 }
3830 }
3831 if (what & layer_state_t::eAlphaChanged) {
3832 if (layer->setAlpha(s.alpha))
3833 flags |= eTraversalNeeded;
3834 }
3835 if (what & layer_state_t::eColorChanged) {
3836 if (layer->setColor(s.color))
3837 flags |= eTraversalNeeded;
3838 }
Peiyong Lind3788632018-09-18 16:01:31 -07003839 if (what & layer_state_t::eColorTransformChanged) {
3840 if (layer->setColorTransform(s.colorTransform)) {
3841 flags |= eTraversalNeeded;
3842 }
3843 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003844 if (what & layer_state_t::eBackgroundColorChanged) {
3845 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3846 flags |= eTraversalNeeded;
3847 }
3848 }
chaviw8b3871a2017-11-01 17:41:01 -07003849 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003850 // TODO: b/109894387
3851 //
3852 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3853 // rotation. To see the problem observe that if we have a square parent, and a child
3854 // of the same size, then we rotate the child 45 degrees around it's center, the child
3855 // must now be cropped to a non rectangular 8 sided region.
3856 //
3857 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3858 // private API, and the WindowManager only uses rotation in one case, which is on a top
3859 // level layer in which cropping is not an issue.
3860 //
3861 // However given that abuse of rotation matrices could lead to surfaces extending outside
3862 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3863 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3864 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003865 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003866 flags |= eTraversalNeeded;
3867 }
3868 if (what & layer_state_t::eTransparentRegionChanged) {
3869 if (layer->setTransparentRegionHint(s.transparentRegion))
3870 flags |= eTraversalNeeded;
3871 }
3872 if (what & layer_state_t::eFlagsChanged) {
3873 if (layer->setFlags(s.flags, s.mask))
3874 flags |= eTraversalNeeded;
3875 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003876 if (what & layer_state_t::eCropChanged_legacy) {
3877 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003878 flags |= eTraversalNeeded;
3879 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003880 if (what & layer_state_t::eCornerRadiusChanged) {
3881 if (layer->setCornerRadius(s.cornerRadius))
3882 flags |= eTraversalNeeded;
3883 }
chaviw8b3871a2017-11-01 17:41:01 -07003884 if (what & layer_state_t::eLayerStackChanged) {
3885 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3886 // We only allow setting layer stacks for top level layers,
3887 // everything else inherits layer stack from its parent.
3888 if (layer->hasParent()) {
3889 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3890 layer->getName().string());
3891 } else if (idx < 0) {
3892 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3893 "that also does not appear in the top level layer list. Something"
3894 " has gone wrong.", layer->getName().string());
3895 } else if (layer->setLayerStack(s.layerStack)) {
3896 mCurrentState.layersSortedByZ.removeAt(idx);
3897 mCurrentState.layersSortedByZ.add(layer);
3898 // we need traversal (state changed)
3899 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003900 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003901 }
3902 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003903 if (what & layer_state_t::eDeferTransaction_legacy) {
3904 if (s.barrierHandle_legacy != nullptr) {
3905 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3906 } else if (s.barrierGbp_legacy != nullptr) {
3907 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003908 if (authenticateSurfaceTextureLocked(gbp)) {
3909 const auto& otherLayer =
3910 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003911 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003912 } else {
3913 ALOGE("Attempt to defer transaction to to an"
3914 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003915 }
3916 }
chaviw8b3871a2017-11-01 17:41:01 -07003917 // We don't trigger a traversal here because if no other state is
3918 // changed, we don't want this to cause any more work
3919 }
3920 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003921 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003922 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003923 if (!hadParent) {
3924 mCurrentState.layersSortedByZ.remove(layer);
3925 }
chaviw8b3871a2017-11-01 17:41:01 -07003926 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003927 }
chaviw8b3871a2017-11-01 17:41:01 -07003928 }
3929 if (what & layer_state_t::eReparentChildren) {
3930 if (layer->reparentChildren(s.reparentHandle)) {
3931 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003932 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003933 }
chaviw8b3871a2017-11-01 17:41:01 -07003934 if (what & layer_state_t::eDetachChildren) {
3935 layer->detachChildren();
3936 }
3937 if (what & layer_state_t::eOverrideScalingModeChanged) {
3938 layer->setOverrideScalingMode(s.overrideScalingMode);
3939 // We don't trigger a traversal here because if no other state is
3940 // changed, we don't want this to cause any more work
3941 }
Marissa Wall61c58622018-07-18 10:12:20 -07003942 if (what & layer_state_t::eTransformChanged) {
3943 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3946 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3947 flags |= eTraversalNeeded;
3948 }
3949 if (what & layer_state_t::eCropChanged) {
3950 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3951 }
Marissa Wall861616d2018-10-22 12:52:23 -07003952 if (what & layer_state_t::eFrameChanged) {
3953 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3954 }
Marissa Wall61c58622018-07-18 10:12:20 -07003955 if (what & layer_state_t::eAcquireFenceChanged) {
3956 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3957 }
3958 if (what & layer_state_t::eDataspaceChanged) {
3959 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3960 }
3961 if (what & layer_state_t::eHdrMetadataChanged) {
3962 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3963 }
3964 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3965 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3966 }
3967 if (what & layer_state_t::eApiChanged) {
3968 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3969 }
3970 if (what & layer_state_t::eSidebandStreamChanged) {
3971 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3972 }
Robert Carr720e5062018-07-30 17:45:14 -07003973 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003974 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3975 layer->setInputInfo(s.inputInfo);
3976 flags |= eTraversalNeeded;
3977 } else {
3978 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3979 }
Robert Carr720e5062018-07-30 17:45:14 -07003980 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003981 if (what & layer_state_t::eMetadataChanged) {
3982 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3983 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003984 std::vector<sp<CallbackHandle>> callbackHandles;
3985 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3986 mTransactionCompletedThread.run();
3987 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3988 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3989 }
3990 }
Marissa Wall73411622019-01-25 10:45:41 -08003991
3992 if (what & layer_state_t::eBufferChanged) {
3993 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3994 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3995 s.buffer);
3996 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003997 if (what & layer_state_t::eCachedBufferChanged) {
3998 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003999 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4000 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004001 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4002 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004003 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4004 // Do not put anything that updates layer state or modifies flags after
4005 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004006 return flags;
4007}
4008
chaviw273171b2018-12-26 11:46:30 -08004009uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4010 uint32_t flags = 0;
4011 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4012 flags |= eTraversalNeeded;
4013 }
4014
chaviwa911b102019-02-14 10:18:33 -08004015 if (inputWindowCommands.syncInputWindows) {
4016 flags |= eTraversalNeeded;
4017 }
4018
Vishnu Nairec0ab382019-02-13 15:32:56 -08004019 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004020 return flags;
4021}
4022
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004023status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4024 uint32_t h, PixelFormat format, uint32_t flags,
4025 LayerMetadata metadata, sp<IBinder>* handle,
4026 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004027 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004028 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004029 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004030 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004031 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004032
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004033 status_t result = NO_ERROR;
4034
4035 sp<Layer> layer;
4036
Cody Northropbc755282017-03-31 12:00:08 -06004037 String8 uniqueName = getUniqueLayerName(name);
4038
Mathias Agopian3165cc22012-08-08 19:42:09 -07004039 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004040 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004041 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4042 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004043
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004044 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004045 case ISurfaceComposerClient::eFXSurfaceBufferState:
4046 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4047 break;
chaviw13fdc492017-06-27 12:40:18 -07004048 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004049 // check if buffer size is set for color layer.
4050 if (w > 0 || h > 0) {
4051 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4052 int(w), int(h));
4053 return BAD_VALUE;
4054 }
4055
chaviw13fdc492017-06-27 12:40:18 -07004056 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004057 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004058 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004059 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004060 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004061 // check if buffer size is set for container layer.
4062 if (w > 0 || h > 0) {
4063 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4064 int(w), int(h));
4065 return BAD_VALUE;
4066 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004067 result = createContainerLayer(client,
4068 uniqueName, w, h, flags,
4069 handle, &layer);
4070 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004071 default:
4072 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004073 break;
4074 }
4075
Dan Stoza7d89d062015-04-30 13:29:25 -07004076 if (result != NO_ERROR) {
4077 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004079
Chia-I Wuab0c3192017-08-01 11:29:00 -07004080 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4081 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004082 if (metadata.has(METADATA_WINDOW_TYPE)) {
4083 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4084 if (windowType == 441731) {
4085 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4086 layer->setPrimaryDisplayOnly();
4087 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004088 }
4089
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004090 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004091
Robert Carrb89ea9d2018-12-10 13:01:14 -08004092 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4093 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4094 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004095 if (result != NO_ERROR) {
4096 return result;
4097 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004098 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004099
4100 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004101 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102}
4103
Cody Northropbc755282017-03-31 12:00:08 -06004104String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4105{
4106 bool matchFound = true;
4107 uint32_t dupeCounter = 0;
4108
4109 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4110 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4111
Dan Stoza436ccf32018-06-21 12:10:12 -07004112 // Grab the state lock since we're accessing mCurrentState
4113 Mutex::Autolock lock(mStateLock);
4114
Cody Northropbc755282017-03-31 12:00:08 -06004115 // Loop over layers until we're sure there is no matching name
4116 while (matchFound) {
4117 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004118 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004119 if (layer->getName() == uniqueName) {
4120 matchFound = true;
4121 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4122 }
4123 });
4124 }
4125
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004126 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4127 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004128
4129 return uniqueName;
4130}
4131
Marissa Wallfd668622018-05-10 10:21:13 -07004132status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4133 uint32_t w, uint32_t h, uint32_t flags,
4134 PixelFormat& format, sp<IBinder>* handle,
4135 sp<IGraphicBufferProducer>* gbp,
4136 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004137 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004138 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004139 case PIXEL_FORMAT_TRANSPARENT:
4140 case PIXEL_FORMAT_TRANSLUCENT:
4141 format = PIXEL_FORMAT_RGBA_8888;
4142 break;
4143 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004144 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004145 break;
4146 }
4147
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004148 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004149 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004150 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004151 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004152 *handle = layer->getHandle();
4153 *gbp = layer->getProducer();
4154 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004156
Marissa Wallfd668622018-05-10 10:21:13 -07004157 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004158 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004159}
4160
Marissa Wall61c58622018-07-18 10:12:20 -07004161status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4162 uint32_t w, uint32_t h, uint32_t flags,
4163 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004164 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004165 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004166 *handle = layer->getHandle();
4167 *outLayer = layer;
4168
4169 return NO_ERROR;
4170}
4171
chaviw13fdc492017-06-27 12:40:18 -07004172status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004173 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004174 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004175{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004176 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004177 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004178 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004179}
4180
Robert Carr6b3f6c52018-08-13 13:05:17 -07004181status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4182 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4183 sp<IBinder>* handle, sp<Layer>* outLayer)
4184{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004185 *outLayer =
4186 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004187 *handle = (*outLayer)->getHandle();
4188 return NO_ERROR;
4189}
4190
4191
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004192void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004193 mLayersPendingRemoval.add(layer);
4194 mLayersRemoved = true;
4195 setTransactionFlags(eTransactionNeeded);
4196}
4197
Robert Carr695d5282018-12-18 15:27:58 -08004198void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004199{
Robert Carr2e102c92018-10-23 12:11:15 -07004200 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004201 // If a layer has a parent, we allow it to out-live it's handle
4202 // with the idea that the parent holds a reference and will eventually
4203 // be cleaned up. However no one cleans up the top-level so we do so
4204 // here.
4205 if (layer->getParent() == nullptr) {
4206 mCurrentState.layersSortedByZ.remove(layer);
4207 }
4208 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004209 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004210}
4211
Mathias Agopianb60314a2012-04-10 22:09:54 -07004212// ---------------------------------------------------------------------------
4213
Andy McFadden13a082e2012-08-24 10:16:42 -07004214void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004215 const auto display = getDefaultDisplayDeviceLocked();
4216 if (!display) return;
4217
4218 const sp<IBinder> token = display->getDisplayToken().promote();
4219 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004220
Jesse Hall01e29052013-02-19 16:13:35 -08004221 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004222 Vector<ComposerState> state;
4223 Vector<DisplayState> displays;
4224 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004225 d.what = DisplayState::eDisplayProjectionChanged |
4226 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004227 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004228 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004229 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004230 d.frame.makeInvalid();
4231 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004232 d.width = 0;
4233 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004234 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004235 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004236
Dominik Laskowskie9774092018-12-11 10:04:24 -08004237 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004238
Dominik Laskowski83b88212018-12-11 13:34:06 -08004239 const nsecs_t vsyncPeriod = getVsyncPeriod();
4240 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004241
Brian Andersond0010582017-03-07 13:20:31 -08004242 // Use phase of 0 since phase is not known.
4243 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004244 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004245 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004246}
4247
4248void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004249 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004250 postMessageAsync(
4251 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004252}
4253
Dominik Laskowskie9774092018-12-11 10:04:24 -08004254void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004255 if (display->isVirtual()) {
4256 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004257 return;
4258 }
4259
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 const auto displayId = display->getId();
4261 LOG_ALWAYS_FATAL_IF(!displayId);
4262
Dominik Laskowski34157762018-10-31 13:07:19 -07004263 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264
4265 int currentMode = display->getPowerMode();
4266 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004267 return;
4268 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004270 display->setPowerMode(mode);
4271
Lloyd Pique4dccc412018-01-22 17:21:36 -08004272 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004273 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004274 }
4275
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004276 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004277 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004278 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004280 mScheduler->onScreenAcquired(mAppConnectionHandle);
4281 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004282 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004283
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004284 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004285 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004286 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004287
4288 struct sched_param param = {0};
4289 param.sched_priority = 1;
4290 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4291 ALOGW("Couldn't set SCHED_FIFO on display on");
4292 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004293 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004294 // Turn off the display
4295 struct sched_param param = {0};
4296 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4297 ALOGW("Couldn't set SCHED_OTHER on display off");
4298 }
4299
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004301 mScheduler->disableHardwareVsync(true);
4302 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004303 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004304
Dominik Laskowski075d3172018-05-24 15:50:06 -07004305 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004306 mVisibleRegionsDirty = true;
4307 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004308 } else if (mode == HWC_POWER_MODE_DOZE ||
4309 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004310 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004313 mScheduler->onScreenAcquired(mAppConnectionHandle);
4314 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004315 }
4316 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4317 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004318 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004319 mScheduler->disableHardwareVsync(true);
4320 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004321 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004322 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004324 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004326 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004328 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004329 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004330 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004331 // Update refresh rate stats.
4332 mRefreshRateStats->setPowerMode(mode);
4333 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004334 }
4335
Dominik Laskowski34157762018-10-31 13:07:19 -07004336 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004337}
4338
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004339void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004340 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004341 const auto display = getDisplayDevice(displayToken);
4342 if (!display) {
4343 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4344 displayToken.get());
4345 } else if (display->isVirtual()) {
4346 ALOGW("Attempt to set power mode %d for virtual display", mode);
4347 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004348 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004349 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004350 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004351}
4352
4353// ---------------------------------------------------------------------------
4354
Dominik Laskowskic2867142019-01-21 11:33:38 -08004355status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4356 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004358
Mathias Agopianbd115332013-04-18 16:41:04 -07004359 IPCThreadState* ipc = IPCThreadState::self();
4360 const int pid = ipc->getCallingPid();
4361 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004362
Mathias Agopianbd115332013-04-18 16:41:04 -07004363 if ((uid != AID_SHELL) &&
4364 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004365 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4366 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004367 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004368 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004369 // (this would indicate SF is stuck, but we want to be able to
4370 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004371 status_t err = mStateLock.timedLock(s2ns(1));
4372 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004373 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004374 StringAppendF(&result,
4375 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4376 "(no locks held)\n",
4377 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004378 }
4379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004381
Dominik Laskowskic2867142019-01-21 11:33:38 -08004382 static const std::unordered_map<std::string, Dumper> dumpers = {
4383 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4384 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4385 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004386 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004387 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004388 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4390 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004391 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4392 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4393 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4394 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4395 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4396 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004397 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004398 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4399 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004400
Dominik Laskowskic2867142019-01-21 11:33:38 -08004401 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004402
Dominik Laskowskic2867142019-01-21 11:33:38 -08004403 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4404 (it->second)(args, asProto, result);
4405 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004406 if (asProto) {
4407 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4408 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4409 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004410 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004411 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004412 }
4413
Mathias Agopian9795c422009-08-26 16:36:26 -07004414 if (locked) {
4415 mStateLock.unlock();
4416 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004417 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004418 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419 return NO_ERROR;
4420}
4421
Dominik Laskowskic2867142019-01-21 11:33:38 -08004422void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 mCurrentState.traverseInZOrder(
4424 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004425}
4426
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004428 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004429
Dominik Laskowskic2867142019-01-21 11:33:38 -08004430 if (args.size() > 1) {
4431 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004432 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004433 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004434 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004435 }
Robert Carr2047fae2016-11-28 14:09:09 -08004436 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437 } else {
4438 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004439 }
4440}
4441
Dominik Laskowskic2867142019-01-21 11:33:38 -08004442void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004443 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004444 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004445 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004446 }
Robert Carr2047fae2016-11-28 14:09:09 -08004447 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004448
Svetoslavd85084b2014-03-20 10:28:31 -07004449 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004450}
4451
Dominik Laskowskic2867142019-01-21 11:33:38 -08004452void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4453 mTimeStats->parseArgs(asProto, args, result);
4454}
4455
Jamie Gennis6547ff42013-07-16 20:12:42 -07004456// This should only be called from the main thread. Otherwise it would need
4457// the lock and should use mCurrentState rather than mDrawingState.
4458void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004459 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004460 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004461 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004462
4463 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4464}
4465
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004467 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004468
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004469 if (isLayerTripleBufferingDisabled())
4470 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004471
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4473 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4474 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4475 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4476 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4477 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004478 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004479}
4480
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004481void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004482 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004483 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004484 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004485 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004486
Ana Krulecba13ab32019-02-20 14:14:12 -08004487 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4488 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4489 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004490 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004491}
4492
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4494 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004495 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4496 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004497 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004498 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004500 }
David Sodman4a36e932017-11-07 14:29:47 -08004501 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004502 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004503 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4505 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004506}
4507
Dan Stozae77c7662016-05-13 11:37:28 -07004508void SurfaceFlinger::recordBufferingStats(const char* layerName,
4509 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004510 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4511 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004512 for (const auto& segment : history) {
4513 if (!segment.usedThirdBuffer) {
4514 stats.twoBufferTime += segment.totalTime;
4515 }
4516 if (segment.occupancyAverage < 1.0f) {
4517 stats.doubleBufferedTime += segment.totalTime;
4518 } else if (segment.occupancyAverage < 2.0f) {
4519 stats.tripleBufferedTime += segment.totalTime;
4520 }
4521 ++stats.numSegments;
4522 stats.totalTime += segment.totalTime;
4523 }
4524}
4525
Yiwei Zhang5434a782018-12-05 18:06:32 -08004526void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4527 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004528
4529 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4530 const size_t count = currentLayers.size();
4531 for (size_t i=0 ; i<count ; i++) {
4532 currentLayers[i]->dumpFrameEvents(result);
4533 }
4534}
4535
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004537 result.append("Buffering stats:\n");
4538 result.append(" [Layer name] <Active time> <Two buffer> "
4539 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004540 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004541 typedef std::tuple<std::string, float, float, float> BufferTuple;
4542 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004543 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004544 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004545 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004546 if (stats.numSegments == 0) {
4547 continue;
4548 }
4549 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4550 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4551 stats.totalTime;
4552 float doubleBufferRatio = static_cast<float>(
4553 stats.doubleBufferedTime) / stats.totalTime;
4554 float tripleBufferRatio = static_cast<float>(
4555 stats.tripleBufferedTime) / stats.totalTime;
4556 sorted.insert({activeTime, {name, twoBufferRatio,
4557 doubleBufferRatio, tripleBufferRatio}});
4558 }
4559 for (const auto& sortedPair : sorted) {
4560 float activeTime = sortedPair.first;
4561 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4563 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004564 }
4565 result.append("\n");
4566}
4567
Yiwei Zhang5434a782018-12-05 18:06:32 -08004568void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004569 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004570 const auto displayId = display->getId();
4571 if (!displayId) {
4572 continue;
4573 }
4574 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004575 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 continue;
4577 }
4578
Yiwei Zhang5434a782018-12-05 18:06:32 -08004579 StringAppendF(&result,
4580 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4581 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004582 uint8_t port;
4583 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004584 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004585 result.append("no identification data\n");
4586 continue;
4587 }
4588
4589 if (!isEdid(data)) {
4590 result.append("unknown identification data: ");
4591 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004592 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004593 }
4594 result.append("\n");
4595 continue;
4596 }
4597
4598 const auto edid = parseEdid(data);
4599 if (!edid) {
4600 result.append("invalid EDID: ");
4601 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004603 }
4604 result.append("\n");
4605 continue;
4606 }
4607
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 result.append(edid->displayName.data(), edid->displayName.length());
4610 result.append("\"\n");
4611 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004612}
4613
Yiwei Zhang5434a782018-12-05 18:06:32 -08004614void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4615 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4616 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4617 StringAppendF(&result, "DisplayColorSetting: %s\n",
4618 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004619
4620 // TODO: print out if wide-color mode is active or not
4621
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004622 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004623 const auto displayId = display->getId();
4624 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004625 continue;
4626 }
4627
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004632 }
4633
Lloyd Pique32cbe282018-10-19 13:09:22 -07004634 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result, " Current color mode: %s (%d)\n",
4636 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004637 }
4638 result.append("\n");
4639}
4640
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004641LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004642 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004643 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4644 const State& state = useDrawing ? mDrawingState : mCurrentState;
4645 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004646 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004647 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004648 });
4649
4650 return layersProto;
4651}
4652
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004653LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4654 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004655 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004656
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004657 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004658 resolution->set_w(displayDevice->getWidth());
4659 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004660
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004661 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004662 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004663
Lloyd Pique32cbe282018-10-19 13:09:22 -07004664 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4665 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4666 layersProto.set_global_transform(displayState.orientation);
4667
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004668 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004669 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004670 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004671 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004672 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004673 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004674 }
4675 });
4676
4677 return layersProto;
4678}
4679
Dominik Laskowskic2867142019-01-21 11:33:38 -08004680void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4681 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 Colorizer colorizer(colorize);
4683
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004684 // figure out if we're stuck somewhere
4685 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004686 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004687 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4688
4689 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004690 * Dump library configuration.
4691 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004692
4693 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004694 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004695 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004696 appendSfConfigString(result);
4697 appendUiConfigString(result);
4698 appendGuiConfigString(result);
4699 result.append("\n");
4700
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004701 result.append("\nDisplay identification data:\n");
4702 dumpDisplayIdentificationData(result);
4703
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004704 result.append("\nWide-Color information:\n");
4705 dumpWideColorInfo(result);
4706
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004708 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004709 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004710 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004711 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004712
Andy McFadden41d67d72014-04-25 16:58:34 -07004713 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004714 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004715 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004716 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004717 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004718
Dan Stozab90cf072015-03-05 11:05:59 -08004719 dumpStaticScreenStats(result);
4720 result.append("\n");
4721
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004723
Dan Stozae77c7662016-05-13 11:37:28 -07004724 dumpBufferingStats(result);
4725
Andy McFadden4803b742012-09-24 19:07:20 -07004726 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727 * Dump the visible layer list
4728 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004729 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4731 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4732 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004734
Chia-I Wu2f884132018-09-13 15:17:58 -07004735 {
4736 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4737 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004739 result.append("\n");
4740 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741
4742 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004743 * Dump Display state
4744 */
4745
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004746 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004747 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004749 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004750 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004751 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004752 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004753
4754 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004755 * Dump SurfaceFlinger global state
4756 */
4757
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004758 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004759 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004760 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004761
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004762 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004763
Dominik Laskowski075d3172018-05-24 15:50:06 -07004764 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004765 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4766 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4768 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004769 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770 StringAppendF(&result,
4771 " transaction-flags : %08x\n"
4772 " gpu_to_cpu_unsupported : %d\n",
4773 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004774
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004775 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004776 displayId && getHwComposer().isConnected(*displayId)) {
4777 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result,
4779 " refresh-rate : %f fps\n"
4780 " x-dpi : %f\n"
4781 " y-dpi : %f\n",
4782 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4783 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004784 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004785
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004787
Dan Stozae22aec72016-08-01 13:20:59 -07004788 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004789 * Tracing state
4790 */
4791 mTracing.dump(result);
4792 result.append("\n");
4793
4794 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004795 * HWC layer minidump
4796 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004797 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004798 const auto displayId = display->getId();
4799 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004800 continue;
4801 }
4802
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004804 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004805 const sp<DisplayDevice> displayDevice = display;
4806 mCurrentState.traverseInZOrder(
4807 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004808 result.append("\n");
4809 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004810
4811 /*
4812 * Dump HWComposer state
4813 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004814 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004815 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004816 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004817 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004819 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004820
4821 /*
4822 * Dump gralloc state
4823 */
4824 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4825 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004826
4827 /*
4828 * Dump VrFlinger state if in use.
4829 */
4830 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4831 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004832 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004833 result.append("\n");
4834 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004835
4836 /**
4837 * Scheduler dump state.
4838 */
Ana Krulecc2870422019-01-29 19:00:58 -08004839 result.append("\nScheduler state:\n");
4840 result.append(mScheduler->doDump() + "\n");
4841 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004842}
4843
Dominik Laskowski075d3172018-05-24 15:50:06 -07004844const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004845 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004846 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004847 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004848 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004849 }
4850 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004851
Dominik Laskowski34157762018-10-31 13:07:19 -07004852 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004853 static const Vector<sp<Layer>> empty;
4854 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004855}
4856
Chia-I Wu28f320b2018-05-03 11:02:56 -07004857void SurfaceFlinger::updateColorMatrixLocked() {
4858 mat4 colorMatrix;
4859 if (mGlobalSaturationFactor != 1.0f) {
4860 // Rec.709 luma coefficients
4861 float3 luminance{0.213f, 0.715f, 0.072f};
4862 luminance *= 1.0f - mGlobalSaturationFactor;
4863 mat4 saturationMatrix = mat4(
4864 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4865 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4866 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4867 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4868 );
4869 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4870 } else {
4871 colorMatrix = mClientColorMatrix * mDaltonizer();
4872 }
4873
4874 if (mCurrentState.colorMatrix != colorMatrix) {
4875 mCurrentState.colorMatrix = colorMatrix;
4876 mCurrentState.colorMatrixChanged = true;
4877 setTransactionFlags(eTransactionNeeded);
4878 }
4879}
4880
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004881status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882#pragma clang diagnostic push
4883#pragma clang diagnostic error "-Wswitch-enum"
4884 switch (static_cast<ISurfaceComposerTag>(code)) {
4885 // These methods should at minimum make sure that the client requested
4886 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004887 case BOOT_FINISHED:
4888 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 case CREATE_DISPLAY:
4890 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004891 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004892 case GET_ACTIVE_COLOR_MODE:
4893 case GET_ANIMATION_FRAME_STATS:
4894 case GET_HDR_CAPABILITIES:
4895 case SET_ACTIVE_CONFIG:
4896 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004897 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004898 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004899 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004900 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4901 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004902 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4903 IPCThreadState* ipc = IPCThreadState::self();
4904 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4905 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004906 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 }
Robert Carr1db73f62016-12-21 12:58:51 -08004908 return OK;
4909 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004911 IPCThreadState* ipc = IPCThreadState::self();
4912 const int pid = ipc->getCallingPid();
4913 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004914 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4915 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004916 return PERMISSION_DENIED;
4917 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004919 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004920 // Used by apps to hook Choreographer to SurfaceFlinger.
4921 case CREATE_DISPLAY_EVENT_CONNECTION:
4922 // The following calls are currently used by clients that do not
4923 // request necessary permissions. However, they do not expose any secret
4924 // information, so it is OK to pass them.
4925 case AUTHENTICATE_SURFACE:
4926 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004927 case GET_PHYSICAL_DISPLAY_IDS:
4928 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004930 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 case GET_DISPLAY_CONFIGS:
4932 case GET_DISPLAY_STATS:
4933 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4934 // Calling setTransactionState is safe, because you need to have been
4935 // granted a reference to Client* and Handle* to do anything with it.
4936 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004937 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004938 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004939 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004940 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004941 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 return OK;
4943 }
4944 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004945 case CAPTURE_SCREEN:
4946 case ADD_REGION_SAMPLING_LISTENER:
4947 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004948 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004949 IPCThreadState* ipc = IPCThreadState::self();
4950 const int pid = ipc->getCallingPid();
4951 const int uid = ipc->getCallingUid();
4952 if ((uid != AID_GRAPHICS) &&
4953 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4954 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4955 return PERMISSION_DENIED;
4956 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957 return OK;
4958 }
4959 // The following codes are deprecated and should never be allowed to access SF.
4960 case CONNECT_DISPLAY_UNUSED:
4961 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4962 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4963 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004965 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966
4967 // These codes are used for the IBinder protocol to either interrogate the recipient
4968 // side of the transaction for its canonical interface descriptor or to dump its state.
4969 // We let them pass by default.
4970 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4971 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4972 code == IBinder::SYSPROPS_TRANSACTION) {
4973 return OK;
4974 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004975 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004977 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004978 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4979 return OK;
4980 }
4981 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4982 return PERMISSION_DENIED;
4983#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004984}
4985
Ana Krulec13be8ad2018-08-21 02:43:56 +00004986status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4987 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004988 status_t credentialCheck = CheckTransactCodeCredentials(code);
4989 if (credentialCheck != OK) {
4990 return credentialCheck;
4991 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004992
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4994 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004995 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004996 IPCThreadState* ipc = IPCThreadState::self();
4997 const int uid = ipc->getCallingUid();
4998 if (CC_UNLIKELY(uid != AID_SYSTEM
4999 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005000 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005001 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005002 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return PERMISSION_DENIED;
5004 }
5005 int n;
5006 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005007 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005008 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 return NO_ERROR;
5010 case 1002: // SHOW_UPDATES
5011 n = data.readInt32();
5012 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005013 invalidateHwcGeometry();
5014 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005017 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005018 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005020 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005021 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005022 setTransactionFlags(
5023 eTransactionNeeded|
5024 eDisplayTransactionNeeded|
5025 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005026 return NO_ERROR;
5027 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005028 case 1006:{ // send empty update
5029 signalRefresh();
5030 return NO_ERROR;
5031 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005032 case 1008: // toggle use of hw composer
5033 n = data.readInt32();
5034 mDebugDisableHWC = n ? 1 : 0;
5035 invalidateHwcGeometry();
5036 repaintEverything();
5037 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005038 case 1009: // toggle use of transform hint
5039 n = data.readInt32();
5040 mDebugDisableTransformHint = n ? 1 : 0;
5041 invalidateHwcGeometry();
5042 repaintEverything();
5043 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005045 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 reply->writeInt32(0);
5047 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005048 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005049 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 return NO_ERROR;
5051 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005052 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005053 if (!display) {
5054 return NAME_NOT_FOUND;
5055 }
5056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005057 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005058 return NO_ERROR;
5059 }
5060 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005061 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005062 // daltonize
5063 n = data.readInt32();
5064 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005065 case 1:
5066 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5067 break;
5068 case 2:
5069 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5070 break;
5071 case 3:
5072 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5073 break;
5074 default:
5075 mDaltonizer.setType(ColorBlindnessType::None);
5076 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005077 }
5078 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005079 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005080 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005081 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005082 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083
5084 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005085 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005086 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005087 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005088 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005089 // apply a color matrix
5090 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005091 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005092 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005093 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005094 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005095 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005096 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005101
5102 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5103 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005105 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5106 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5107 }
5108
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005110 return NO_ERROR;
5111 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005112 // This is an experimental interface
5113 // Needs to be shifted to proper binder interface when we productize
5114 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005115 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005116 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005117 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005118 return NO_ERROR;
5119 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005120 case 1017: {
5121 n = data.readInt32();
5122 mForceFullDamage = static_cast<bool>(n);
5123 return NO_ERROR;
5124 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005125 case 1018: { // Modify Choreographer's phase offset
5126 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005127 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005128 return NO_ERROR;
5129 }
5130 case 1019: { // Modify SurfaceFlinger's phase offset
5131 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005132 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005133 return NO_ERROR;
5134 }
Irvel468051e2016-06-13 16:44:44 -07005135 case 1020: { // Layer updates interceptor
5136 n = data.readInt32();
5137 if (n) {
5138 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005139 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005140 }
5141 else{
5142 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005143 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005144 }
5145 return NO_ERROR;
5146 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005147 case 1021: { // Disable HWC virtual displays
5148 n = data.readInt32();
5149 mUseHwcVirtualDisplays = !n;
5150 return NO_ERROR;
5151 }
Romain Guy0147a172017-06-01 13:53:56 -07005152 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005153 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005154 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005155
Chia-I Wu28f320b2018-05-03 11:02:56 -07005156 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005157 return NO_ERROR;
5158 }
Romain Guy54f154a2017-10-24 21:40:32 +01005159 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005160 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005161 invalidateHwcGeometry();
5162 repaintEverything();
5163 return NO_ERROR;
5164 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005165 // Deprecate, use 1030 to check whether the device is color managed.
5166 case 1024: {
5167 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005168 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005169 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005170 n = data.readInt32();
5171 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005172 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005173 mTracing.enable();
5174 doTracing("tracing.enable");
5175 reply->writeInt32(NO_ERROR);
5176 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005177 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005178 status_t err = mTracing.disable();
5179 reply->writeInt32(err);
5180 }
5181 return NO_ERROR;
5182 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005183 case 1026: { // Get layer tracing status
5184 reply->writeBool(mTracing.isEnabled());
5185 return NO_ERROR;
5186 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005187 // Is a DisplayColorSetting supported?
5188 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005189 const auto display = getDefaultDisplayDevice();
5190 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005191 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005192 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005193
5194 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5195 switch (setting) {
5196 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005197 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005198 break;
5199 case DisplayColorSetting::UNMANAGED:
5200 reply->writeBool(true);
5201 break;
5202 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005203 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005204 break;
5205 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005206 reply->writeBool(
5207 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005208 break;
5209 }
5210 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005211 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005212 // Is VrFlinger active?
5213 case 1028: {
5214 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005215 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005216 return NO_ERROR;
5217 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005218 // Is device color managed?
5219 case 1030: {
5220 reply->writeBool(useColorManagement);
5221 return NO_ERROR;
5222 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005223 // Override default composition data space
5224 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5225 // && adb shell stop zygote && adb shell start zygote
5226 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5227 // adb shell stop zygote && adb shell start zygote
5228 case 1031: {
5229 Mutex::Autolock _l(mStateLock);
5230 n = data.readInt32();
5231 if (n) {
5232 n = data.readInt32();
5233 if (n) {
5234 Dataspace dataspace = static_cast<Dataspace>(n);
5235 if (!validateCompositionDataspace(dataspace)) {
5236 return BAD_VALUE;
5237 }
5238 mDefaultCompositionDataspace = dataspace;
5239 }
5240 n = data.readInt32();
5241 if (n) {
5242 Dataspace dataspace = static_cast<Dataspace>(n);
5243 if (!validateCompositionDataspace(dataspace)) {
5244 return BAD_VALUE;
5245 }
5246 mWideColorGamutCompositionDataspace = dataspace;
5247 }
5248 } else {
5249 // restore composition data space.
5250 mDefaultCompositionDataspace = defaultCompositionDataspace;
5251 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5252 }
5253 return NO_ERROR;
5254 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005255 }
5256 }
5257 return err;
5258}
5259
Steven Thomas6d8110b2017-08-31 18:24:21 -07005260void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005261 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005262 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005263}
5264
Ana Krulec7d1d6832018-12-27 11:10:09 -08005265void SurfaceFlinger::repaintEverythingForHWC() {
5266 mRepaintEverything = true;
5267 mEventQueue->invalidateForHWC();
5268}
5269
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005270// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5271class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005272public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005273 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5274 ~WindowDisconnector() {
5275 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005276 }
5277
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278private:
5279 ANativeWindow* mWindow;
5280 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005281};
5282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005283status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005284 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5285 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005286 uint32_t reqWidth, uint32_t reqHeight,
5287 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005288 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005291 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005292
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005293 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5294
Chia-I Wu20261cb2018-08-23 12:55:44 -07005295 sp<DisplayDevice> display;
5296 {
5297 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005298
Chia-I Wu20261cb2018-08-23 12:55:44 -07005299 display = getDisplayDeviceLocked(displayToken);
5300 if (!display) return BAD_VALUE;
5301
Chia-I Wucb023152018-08-28 12:57:23 -07005302 // set the requested width/height to the logical display viewport size
5303 // by default
5304 if (reqWidth == 0 || reqHeight == 0) {
5305 reqWidth = uint32_t(display->getViewport().width());
5306 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005307 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005308 }
5309
Peiyong Lin0e003c92018-09-17 11:09:51 -07005310 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5311 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005312
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005313 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5314 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005315 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5316 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005317}
5318
5319status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005320 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5321 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005322 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005323 ATRACE_CALL();
5324
5325 class LayerRenderArea : public RenderArea {
5326 public:
Robert Carr578038f2018-03-09 12:25:24 -08005327 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005328 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5329 bool childrenOnly)
5330 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005331 mLayer(layer),
5332 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005333 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005334 mFlinger(flinger),
5335 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005336 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005337 Rect getBounds() const override {
5338 const Layer::State& layerState(mLayer->getDrawingState());
5339 return mLayer->getBufferSize(layerState);
5340 }
Marissa Wall61c58622018-07-18 10:12:20 -07005341 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005342 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005343 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005344 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005345 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005346 }
chaviwa76b2712017-09-20 12:02:26 -07005347 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005348 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005349 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005350 Rect getSourceCrop() const override {
5351 if (mCrop.isEmpty()) {
5352 return getBounds();
5353 } else {
5354 return mCrop;
5355 }
5356 }
Robert Carr578038f2018-03-09 12:25:24 -08005357 class ReparentForDrawing {
5358 public:
5359 const sp<Layer>& oldParent;
5360 const sp<Layer>& newParent;
5361
Vishnu Nair4351ad52019-02-11 14:13:02 -08005362 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5363 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005364 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005365 // Compute and cache the bounds for the new parent layer.
5366 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005367 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005368 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005369 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005370 };
5371
5372 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005373 const Rect sourceCrop = getSourceCrop();
5374 // no need to check rotation because there is none
5375 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5376 sourceCrop.height() != getReqHeight();
5377
Robert Carr578038f2018-03-09 12:25:24 -08005378 if (!mChildrenOnly) {
5379 mTransform = mLayer->getTransform().inverse();
5380 drawLayers();
5381 } else {
5382 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005383 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005384 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5385 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005386
Vishnu Nair4351ad52019-02-11 14:13:02 -08005387 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005388 drawLayers();
5389 }
5390 }
chaviwa76b2712017-09-20 12:02:26 -07005391
chaviwa76b2712017-09-20 12:02:26 -07005392 private:
chaviw7206d492017-11-10 16:16:12 -08005393 const sp<Layer> mLayer;
5394 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005395
5396 // In the "childrenOnly" case we reparent the children to a screenshot
5397 // layer which has no properties set and which does not draw.
5398 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005399 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005400 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005401
5402 SurfaceFlinger* mFlinger;
5403 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005404 };
5405
5406 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5407 auto parent = layerHandle->owner.promote();
5408
Robert Carr2e102c92018-10-23 12:11:15 -07005409 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005410 ALOGE("captureLayers called with a removed parent");
5411 return NAME_NOT_FOUND;
5412 }
5413
Robert Carr578038f2018-03-09 12:25:24 -08005414 const int uid = IPCThreadState::self()->getCallingUid();
5415 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005416 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005417 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5418 return PERMISSION_DENIED;
5419 }
5420
chaviw7206d492017-11-10 16:16:12 -08005421 Rect crop(sourceCrop);
5422 if (sourceCrop.width() <= 0) {
5423 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005424 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005425 }
5426
5427 if (sourceCrop.height() <= 0) {
5428 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005429 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005430 }
5431
5432 int32_t reqWidth = crop.width() * frameScale;
5433 int32_t reqHeight = crop.height() * frameScale;
5434
Chia-I Wu20261cb2018-08-23 12:55:44 -07005435 // really small crop or frameScale
5436 if (reqWidth <= 0) {
5437 reqWidth = 1;
5438 }
5439 if (reqHeight <= 0) {
5440 reqHeight = 1;
5441 }
5442
Peiyong Lin0e003c92018-09-17 11:09:51 -07005443 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005444
Robert Carr578038f2018-03-09 12:25:24 -08005445 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005446 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5447 if (!layer->isVisible()) {
5448 return;
Robert Carr578038f2018-03-09 12:25:24 -08005449 } else if (childrenOnly && layer == parent.get()) {
5450 return;
chaviwa76b2712017-09-20 12:02:26 -07005451 }
5452 visitor(layer);
5453 });
5454 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005455 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005456}
5457
5458status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5459 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005460 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005461 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005462 bool useIdentityTransform) {
5463 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005464
Peiyong Lin0e003c92018-09-17 11:09:51 -07005465 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005466 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5467 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005468 *outBuffer =
5469 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5470 static_cast<android_pixel_format>(reqPixelFormat), 1,
5471 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005472
5473 // This mutex protects syncFd and captureResult for communication of the return values from the
5474 // main thread back to this Binder thread
5475 std::mutex captureMutex;
5476 std::condition_variable captureCondition;
5477 std::unique_lock<std::mutex> captureLock(captureMutex);
5478 int syncFd = -1;
5479 std::optional<status_t> captureResult;
5480
Robert Carr03480e22018-01-04 16:02:06 -08005481 const int uid = IPCThreadState::self()->getCallingUid();
5482 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5483
Dominik Laskowski8c001672018-05-30 16:52:06 -07005484 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005485 // If there is a refresh pending, bug out early and tell the binder thread to try again
5486 // after the refresh.
5487 if (mRefreshPending) {
5488 ATRACE_NAME("Skipping screenshot for now");
5489 std::unique_lock<std::mutex> captureLock(captureMutex);
5490 captureResult = std::make_optional<status_t>(EAGAIN);
5491 captureCondition.notify_one();
5492 return;
5493 }
5494
5495 status_t result = NO_ERROR;
5496 int fd = -1;
5497 {
5498 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005499 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005500 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5501 useIdentityTransform, forSystem, &fd);
5502 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 }
5504
5505 {
5506 std::unique_lock<std::mutex> captureLock(captureMutex);
5507 syncFd = fd;
5508 captureResult = std::make_optional<status_t>(result);
5509 captureCondition.notify_one();
5510 }
5511 });
5512
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005513 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005514 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005515 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005516 while (*captureResult == EAGAIN) {
5517 captureResult.reset();
5518 result = postMessageAsync(message);
5519 if (result != NO_ERROR) {
5520 return result;
5521 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005522 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005523 }
5524 result = *captureResult;
5525 }
5526
5527 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005528 sync_wait(syncFd, -1);
5529 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005530 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005531
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005532 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005533}
5534
chaviwa76b2712017-09-20 12:02:26 -07005535void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005536 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005537 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5538 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005539 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005540
chaviwa76b2712017-09-20 12:02:26 -07005541 const auto reqWidth = renderArea.getReqWidth();
5542 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005543 const auto sourceCrop = renderArea.getSourceCrop();
5544 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005545
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005546 renderengine::DisplaySettings clientCompositionDisplay;
5547 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005548
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549 // assume that bounds are never offset, and that they are the same as the
5550 // buffer bounds.
5551 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5552 ui::Transform transform = renderArea.getTransform();
5553 mat4 m;
5554 m[0][0] = transform[0][0];
5555 m[0][1] = transform[0][1];
5556 m[0][3] = transform[0][2];
5557 m[1][0] = transform[1][0];
5558 m[1][1] = transform[1][1];
5559 m[1][3] = transform[1][2];
5560 m[3][0] = transform[2][0];
5561 m[3][1] = transform[2][1];
5562 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005563
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005564 clientCompositionDisplay.globalTransform = m;
5565 mat4 rotMatrix;
5566 // Displacement for repositioning the clipping rectangle after rotating it
5567 // with the rotation hint.
5568 int displacementX = 0;
5569 int displacementY = 0;
5570 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5571 switch (rotation) {
5572 case ui::Transform::ROT_90:
5573 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5574 displacementX = reqWidth;
5575 break;
5576 case ui::Transform::ROT_180:
5577 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5578 displacementX = reqWidth;
5579 displacementY = reqHeight;
5580 break;
5581 case ui::Transform::ROT_270:
5582 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5583 displacementY = reqHeight;
5584 break;
5585 default:
5586 break;
5587 }
5588 // We need to transform the clipping window into the right spot.
5589 // First, rotate the clipping rectangle by the rotation hint to get the
5590 // right orientation
5591 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5592 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5593 const vec4 rotClipTL = rotMatrix * clipTL;
5594 const vec4 rotClipBR = rotMatrix * clipBR;
5595 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5596 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5597 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5598 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5599
5600 // Now reposition the clipping rectangle with the displacement vector
5601 // computed above.
5602 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5603
5604 clientCompositionDisplay.clip =
5605 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5606 newClipRight + displacementX, newClipBottom + displacementY);
5607
5608 // We need to perform the same transformation in layer space, so propagate
5609 // it to the global transform.
5610 mat4 clipTransform = displacementMat * rotMatrix;
5611 clientCompositionDisplay.globalTransform *= clipTransform;
5612 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5613 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005614
chaviw50da5042018-04-09 13:49:37 -07005615 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005616
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005617 renderengine::LayerSettings fillLayer;
5618 fillLayer.source.buffer.buffer = nullptr;
5619 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5620 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5621 fillLayer.alpha = half(alpha);
5622 clientCompositionLayers.push_back(fillLayer);
5623
5624 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005625 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005626 renderengine::LayerSettings layerSettings;
5627 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5628 layerSettings);
5629 if (prepared) {
5630 clientCompositionLayers.push_back(layerSettings);
5631 }
chaviwa76b2712017-09-20 12:02:26 -07005632 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633
5634 clientCompositionDisplay.clearRegion = clearRegion;
5635 base::unique_fd drawFence;
5636 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5637 &drawFence);
5638
5639 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005640}
5641
chaviwa76b2712017-09-20 12:02:26 -07005642status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5643 TraverseLayersFunction traverseLayers,
5644 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005645 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005646 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005647 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005648 ATRACE_CALL();
5649
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005650 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005651
5652 traverseLayers([&](Layer* layer) {
5653 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5654 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005655
Robert Carr03480e22018-01-04 16:02:06 -08005656 // We allow the system server to take screenshots of secure layers for
5657 // use in situations like the Screen-rotation animation and place
5658 // the impetus on WindowManager to not persist them.
5659 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005660 ALOGW("FB is protected: PERMISSION_DENIED");
5661 return PERMISSION_DENIED;
5662 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005663 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005664 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005665}
5666
chaviw95ef3c42019-02-14 10:55:09 -08005667void SurfaceFlinger::setInputWindowsFinished() {
5668 Mutex::Autolock _l(mStateLock);
5669
5670 mPendingSyncInputWindows = false;
5671 mTransactionCV.broadcast();
5672}
chaviw5f21a5e2019-02-14 10:00:34 -08005673
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005674// ---------------------------------------------------------------------------
5675
Dan Stoza412903f2017-04-27 13:42:17 -07005676void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5677 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005678}
5679
Dan Stoza412903f2017-04-27 13:42:17 -07005680void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5681 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005682}
5683
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005684void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005685 const LayerVector::Visitor& visitor) {
5686 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005687 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005688 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005689 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005690 continue;
5691 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005692 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005693 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005694 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005695 return;
5696 }
chaviwa76b2712017-09-20 12:02:26 -07005697 if (!layer->isVisible()) {
5698 return;
5699 }
5700 visitor(layer);
5701 });
5702 }
5703}
5704
chaviw291d88a2019-02-14 10:33:58 -08005705// ----------------------------------------------------------------------------
5706
5707void SetInputWindowsListener::onSetInputWindowsFinished() {
5708 mFlinger->setInputWindowsFinished();
5709}
5710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005711}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005712
Lloyd Pique074e8122018-07-26 12:57:23 -07005713
Mathias Agopian3f844832013-08-07 21:24:32 -07005714#if defined(__gl_h_)
5715#error "don't include gl/gl.h in this file"
5716#endif
5717
5718#if defined(__gl2_h_)
5719#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005720#endif