blob: f651bdf4ea59387bcf9872b9d2d7c919adf89aca [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080065#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700113#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900115#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
chaviw1d044282017-09-27 12:19:28 -0700117#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900118#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700121
Jaesoo Lee43518572017-01-23 19:03:16 +0900122using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800125
Yiwei Zhang5434a782018-12-05 18:06:32 -0800126using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700127using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700128using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800129using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700130using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700131using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
134
Steven Thomasb02664d2017-07-26 18:48:28 -0700135namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700136
137#pragma clang diagnostic push
138#pragma clang diagnostic error "-Wswitch-enum"
139
140bool isWideColorMode(const ColorMode colorMode) {
141 switch (colorMode) {
142 case ColorMode::DISPLAY_P3:
143 case ColorMode::ADOBE_RGB:
144 case ColorMode::DCI_P3:
145 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700146 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700147 case ColorMode::BT2100_PQ:
148 case ColorMode::BT2100_HLG:
149 return true;
150 case ColorMode::NATIVE:
151 case ColorMode::STANDARD_BT601_625:
152 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
153 case ColorMode::STANDARD_BT601_525:
154 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
155 case ColorMode::STANDARD_BT709:
156 case ColorMode::SRGB:
157 return false;
158 }
159 return false;
160}
161
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700162ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
163 switch (rotation) {
164 case ISurfaceComposer::eRotateNone:
165 return ui::Transform::ROT_0;
166 case ISurfaceComposer::eRotate90:
167 return ui::Transform::ROT_90;
168 case ISurfaceComposer::eRotate180:
169 return ui::Transform::ROT_180;
170 case ISurfaceComposer::eRotate270:
171 return ui::Transform::ROT_270;
172 }
173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
174 return ui::Transform::ROT_0;
175}
176
Peiyong Linfca547f2018-07-09 13:03:33 -0700177#pragma clang diagnostic pop
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179class ConditionalLock {
180public:
181 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
182 if (lock) {
183 mMutex.lock();
184 }
185 }
186 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
187private:
188 Mutex& mMutex;
189 bool mLocked;
190};
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
Peiyong Lin9d846a52018-11-05 13:18:20 -0800192// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
193bool validateCompositionDataspace(Dataspace dataspace) {
194 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
195}
196
Steven Thomasb02664d2017-07-26 18:48:28 -0700197} // namespace anonymous
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Mathias Agopian99b49842011-06-27 16:05:52 -0700201const String16 sHardwareTest("android.permission.HARDWARE_TEST");
202const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
203const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
204const String16 sDump("android.permission.DUMP");
205
Daniel Solomon42d04562019-01-20 21:03:19 -0800206constexpr float kSrgbRedX = 0.4123f;
207constexpr float kSrgbRedY = 0.2126f;
208constexpr float kSrgbRedZ = 0.0193f;
209constexpr float kSrgbGreenX = 0.3576f;
210constexpr float kSrgbGreenY = 0.7152f;
211constexpr float kSrgbGreenZ = 0.1192f;
212constexpr float kSrgbBlueX = 0.1805f;
213constexpr float kSrgbBlueY = 0.0722f;
214constexpr float kSrgbBlueZ = 0.9506f;
215constexpr float kSrgbWhiteX = 0.9505f;
216constexpr float kSrgbWhiteY = 1.0000f;
217constexpr float kSrgbWhiteZ = 1.0891f;
218
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800219constexpr float kDefaultRefreshRate = 60.f;
220constexpr float kPerformanceRefreshRate = 90.f;
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700230int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700231bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700232bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700233Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
235Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
254 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
David Sodmanbc815282017-11-05 18:57:52 -0800266SurfaceFlingerBE::SurfaceFlingerBE()
267 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800268 mFrameBuckets(),
269 mTotalTime(0),
270 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800271 mComposerSequenceId(0) {
272}
273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
275 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800276 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700278 mTransactionPending(false),
279 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700280 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700281 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800283 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800285 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800286 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800287 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700289 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700290 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700291 mDebugInTransaction(0),
292 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700293 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800294 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
chaviw291d88a2019-02-14 10:33:58 -0800300 mCompositionEngine{getFactory().createCompositionEngine()} {
301 mSetInputWindowsListener = new SetInputWindowsListener(this);
302}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800303
Lloyd Pique90c115d2018-09-18 21:39:42 -0700304SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
305 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800306 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800315
Steven Thomas050b2c82017-03-06 11:45:16 -0800316 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 mDefaultCompositionDataspace =
326 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
327 mWideColorGamutCompositionDataspace =
328 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
329 defaultCompositionDataspace = mDefaultCompositionDataspace;
330 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
331 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
332 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
333 wideColorGamutCompositionPixelFormat =
334 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
339 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
340 switch (tmpPrimaryDisplayOrientation) {
341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
353 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800355
Daniel Solomon42d04562019-01-20 21:03:19 -0800356 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
357 if (surfaceFlingerConfigsServiceV1_2) {
358 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
359 [&](auto tmpPrimaries) {
360 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
361 });
362 } else {
363 initDefaultDisplayNativePrimaries();
364 }
365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 // debugging stuff...
367 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700370 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 property_get("debug.sf.showupdates", value, "0");
373 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700375 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000376
377 // DDMS debugging deprecated (b/120782499)
378 property_get("debug.sf.ddms", value, "0");
379 int debugDdms = atoi(value);
380 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700381
382 property_get("debug.sf.disable_backpressure", value, "0");
383 mPropagateBackpressure = !atoi(value);
384 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700385
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800386 property_get("debug.sf.enable_hwc_vds", value, "0");
387 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800388 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800389
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800390 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800391 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800392 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700393
Yiwei Zhang243b3782018-05-15 17:40:04 -0700394 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700395 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
396 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
397
Ana Krulecc2870422019-01-29 19:00:58 -0800398 property_get("debug.sf.use_90Hz", value, "0");
399 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800400
Ana Krulecba13ab32019-02-20 14:14:12 -0800401 property_get("debug.sf.use_smart_90_for_video", value, "0");
402 mUseSmart90ForVideo = atoi(value);
403
Dan Stozaec460082018-12-17 15:35:09 -0800404 property_get("debug.sf.luma_sampling", value, "1");
405 mLumaSampling = atoi(value);
406
Ana Krulec757f63a2019-01-25 10:46:18 -0800407 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
408 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700409
Romain Guy11d63f42017-07-20 12:47:14 -0700410 // We should be reading 'persist.sys.sf.color_saturation' here
411 // but since /data may be encrypted, we need to wait until after vold
412 // comes online to attempt to read the property. The property is
413 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800414
415 if (useTrebleTestingOverride()) {
416 // Without the override SurfaceFlinger cannot connect to HIDL
417 // services that are not listed in the manifests. Considered
418 // deriving the setting from the set service name, but it
419 // would be brittle if the name that's not 'default' is used
420 // for production purposes later on.
421 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425void SurfaceFlinger::onFirstRef()
426{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800427 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430SurfaceFlinger::~SurfaceFlinger()
431{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Dan Stozac7014012014-02-14 15:03:43 -0800434void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435{
436 // the window manager died on us. prepare its eulogy.
437
Andy McFadden13a082e2012-08-24 10:16:42 -0700438 // restore initial conditions (default device unblank, etc)
439 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440
441 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700442 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443}
444
Robert Carr1db73f62016-12-21 12:58:51 -0800445static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700446 status_t err = client->initCheck();
447 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return nullptr;
451}
452
453sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
454 return initClient(new Client(this));
455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 // Display ID is assigned when virtual display is allocated by HWC.
478 DisplayDeviceState state;
479 state.isSecure = secure;
480 state.displayName = displayName;
481 mCurrentState.displays.add(token, state);
482 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
490 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
496 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 mInterceptor->saveDisplayDeletion(state.sequenceId);
501 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
506 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 const auto internalDisplayId = getInternalDisplayIdLocked();
509 if (!internalDisplayId) {
510 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 }
512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 std::vector<PhysicalDisplayId> displayIds;
514 displayIds.reserve(mPhysicalDisplayTokens.size());
515 displayIds.push_back(internalDisplayId->value);
516
517 for (const auto& [id, token] : mPhysicalDisplayTokens) {
518 if (id != *internalDisplayId) {
519 displayIds.push_back(id.value);
520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800523 return displayIds;
524}
525
526sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
527 Mutex::Autolock lock(mStateLock);
528 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
Ady Abraham37965d42018-11-01 13:43:32 -0700531status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
532 if (!outGetColorManagement) {
533 return BAD_VALUE;
534 }
535 *outGetColorManagement = useColorManagement;
536 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700537}
538
Lloyd Pique441d5042018-10-18 16:49:51 -0700539HWComposer& SurfaceFlinger::getHwComposer() const {
540 return mCompositionEngine->getHwComposer();
541}
542
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700543renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
544 return mCompositionEngine->getRenderEngine();
545}
546
Lloyd Pique70d91362018-10-18 16:02:55 -0700547compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
548 return *mCompositionEngine.get();
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551void SurfaceFlinger::bootFinished()
552{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700553 if (mStartPropertySetThread->join() != NO_ERROR) {
554 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556 const nsecs_t now = systemTime();
557 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000558 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559
560 // wait patiently for the window manager death
561 const String16 name("window");
562 sp<IBinder> window(defaultServiceManager()->getService(name));
563 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 }
Robert Carr720e5062018-07-30 17:45:14 -0700566 sp<IBinder> input(defaultServiceManager()->getService(
567 String16("inputflinger")));
568 if (input == nullptr) {
569 ALOGE("Failed to link to input service");
570 } else {
571 mInputFlinger = interface_cast<IInputFlinger>(input);
572 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 if (mVrFlinger) {
575 mVrFlinger->OnBootFinished();
576 }
577
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700579 // formerly we would just kill the process, but we now ask it to exit so it
580 // can choose where to stop the animation.
581 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700582
583 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
584 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
585 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700586
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
591 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
592 // away and it should be controlled by flipping the switch in setting. The switch in
593 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
594 // The boot must be complete before we can set the active config.
595
596 if (mUse90Hz) {
597 mPhaseOffsets->setRefreshRateType(
598 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Ady Abraham447052e2019-02-13 16:07:27 -0800599 setRefreshRateTo(RefreshRateType::PERFORMANCE, ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800600 } else {
601 mPhaseOffsets->setRefreshRateType(
602 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
Ady Abraham447052e2019-02-13 16:07:27 -0800603 setRefreshRateTo(RefreshRateType::DEFAULT, ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800604 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800605 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800606}
607
Dan Stoza436ccf32018-06-21 12:10:12 -0700608uint32_t SurfaceFlinger::getNewTexture() {
609 {
610 std::lock_guard lock(mTexturePoolMutex);
611 if (!mTexturePool.empty()) {
612 uint32_t name = mTexturePool.back();
613 mTexturePool.pop_back();
614 ATRACE_INT("TexturePoolSize", mTexturePool.size());
615 return name;
616 }
617
618 // The pool was too small, so increase it for the future
619 ++mTexturePoolSize;
620 }
621
622 // The pool was empty, so we need to get a new texture name directly using a
623 // blocking call to the main thread
624 uint32_t name = 0;
625 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
626 return name;
627}
628
Mathias Agopian3f844832013-08-07 21:24:32 -0700629void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700630 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700631}
632
Wei Wangf9b05ee2017-07-19 20:59:39 -0700633// Do not call property_set on main thread which will be blocked by init
634// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700636 ALOGI( "SurfaceFlinger's main thread ready to run. "
637 "Initializing graphics H/W...");
638
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700642 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800643 mScheduler =
644 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
645 auto resyncCallback =
646 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800647
Ana Krulecc2870422019-01-29 19:00:58 -0800648 mAppConnectionHandle =
649 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
650 resyncCallback,
651 impl::EventThread::InterceptVSyncsCallback());
652 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
653 resyncCallback, [this](nsecs_t timestamp) {
654 mInterceptor->saveVSyncEvent(timestamp);
655 });
656
657 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
658 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
659 mSfConnectionHandle.get());
660
Steven Thomasb02664d2017-07-26 18:48:28 -0700661 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700662 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700663 renderEngineFeature |= (useColorManagement ?
664 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700665 renderEngineFeature |= (useContextPriority ?
666 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700667
668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700669 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700670 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700671 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700672
673 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
674 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700675 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
676 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800677 // Process any initial hotplug and resulting display changes.
678 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700679 const auto display = getDefaultDisplayDeviceLocked();
680 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700681 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800683
Steven Thomas050b2c82017-03-06 11:45:16 -0800684 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700686 // This callback is called from the vr flinger dispatch thread. We
687 // need to call signalTransaction(), which requires holding
688 // mStateLock when we're not on the main thread. Acquiring
689 // mStateLock from the vr flinger dispatch thread might trigger a
690 // deadlock in surface flinger (see b/66916578), so post a message
691 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700692 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700693 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
694 mVrFlingerRequestsDisplay = requestDisplay;
695 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700696 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
699 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700700 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 .value_or(0),
702 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 if (!mVrFlinger) {
704 ALOGE("Failed to start vrflinger");
705 }
706 }
707
Mathias Agopian92a979a2012-08-02 18:32:23 -0700708 // initialize our drawing state
709 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700710
Andy McFadden13a082e2012-08-24 10:16:42 -0700711 // set initial conditions (e.g. unblank default device)
712 initializeDisplays();
713
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700714 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700715
Wei Wangf9b05ee2017-07-19 20:59:39 -0700716 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700717
718 const bool presentFenceReliable =
719 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
720 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700721
722 if (mStartPropertySetThread->Start() != NO_ERROR) {
723 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800725
Kevin DuBois36233132019-02-19 14:08:55 -0800726 if (mUse90Hz) {
727 mScheduler->setExpiredIdleTimerCallback([this] {
728 Mutex::Autolock lock(mStateLock);
Ady Abraham447052e2019-02-13 16:07:27 -0800729 setRefreshRateTo(RefreshRateType::DEFAULT, ConfigEvent::None);
Kevin DuBois36233132019-02-19 14:08:55 -0800730 });
731 mScheduler->setResetIdleTimerCallback([this] {
732 Mutex::Autolock lock(mStateLock);
Ady Abraham447052e2019-02-13 16:07:27 -0800733 setRefreshRateTo(RefreshRateType::PERFORMANCE, ConfigEvent::None);
Kevin DuBois36233132019-02-19 14:08:55 -0800734 });
735 }
Ana Krulecc2870422019-01-29 19:00:58 -0800736 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
737 *display->getId()),
738 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800739
Dan Stoza9e56aa02015-11-02 13:00:03 -0800740 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700741}
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700744 Mutex::Autolock _l(mStateLock);
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746 char value[PROPERTY_VALUE_MAX];
747
748 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800749 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100752
753 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700754 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800755
756 property_get("persist.sys.sf.color_mode", value, "0");
757 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700758}
759
Mathias Agopiana67e4182012-06-19 17:26:12 -0700760void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Start boot animation service by setting a property mailbox
762 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 if (mStartPropertySetThread->join() != NO_ERROR) {
766 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800767 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700771 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800779
Jamie Gennis582270d2011-08-17 18:19:00 -0700780bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800782 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800783 return authenticateSurfaceTextureLocked(bufferProducer);
784}
785
786bool SurfaceFlinger::authenticateSurfaceTextureLocked(
787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800788 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800789 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800790}
791
Brian Anderson6b376712017-04-04 10:51:39 -0700792status_t SurfaceFlinger::getSupportedFrameTimestamps(
793 std::vector<FrameEvent>* outSupported) const {
794 *outSupported = {
795 FrameEvent::REQUESTED_PRESENT,
796 FrameEvent::ACQUIRE,
797 FrameEvent::LATCH,
798 FrameEvent::FIRST_REFRESH_START,
799 FrameEvent::LAST_REFRESH_START,
800 FrameEvent::GPU_COMPOSITION_DONE,
801 FrameEvent::DEQUEUE_READY,
802 FrameEvent::RELEASE,
803 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700804 ConditionalLock _l(mStateLock,
805 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700806 if (!getHwComposer().hasCapability(
807 HWC2::Capability::PresentFenceIsNotReliable)) {
808 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
809 }
810 return NO_ERROR;
811}
812
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800813status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
814 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700815 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 return BAD_VALUE;
817 }
818
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800819 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700820 if (!displayId) {
821 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700822 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 // TODO: Not sure if display density should handled by SF any longer
825 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700828 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800829 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 }
832 return density;
833 }
834 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("ro.sf.lcd_density"); }
839 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Dominik Laskowski075d3172018-05-24 15:50:06 -0700843 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 DisplayInfo info = DisplayInfo();
845
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846 float xdpi = hwConfig->getDpiX();
847 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849 info.w = hwConfig->getWidth();
850 info.h = hwConfig->getHeight();
851 // Default display viewport to display width and height
852 info.viewportW = info.w;
853 info.viewportH = info.h;
854
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800855 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 // The density of the device is provided by a build property
857 float density = Density::getBuildDensity() / 160.0f;
858 if (density == 0) {
859 // the build doesn't provide a density -- this is wrong!
860 // use xdpi instead
861 ALOGE("ro.sf.lcd_density must be defined as a build property");
862 density = xdpi / 160.0f;
863 }
864 if (Density::getEmuDensity()) {
865 // if "qemu.sf.lcd_density" is specified, it overrides everything
866 xdpi = ydpi = density = Density::getEmuDensity();
867 density /= 160.0f;
868 }
869 info.density = density;
870
871 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872 const auto display = getDefaultDisplayDeviceLocked();
873 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700874
875 // This is for screenrecord
876 const Rect viewport = display->getViewport();
877 if (viewport.isValid()) {
878 info.viewportW = uint32_t(viewport.getWidth());
879 info.viewportH = uint32_t(viewport.getHeight());
880 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 } else {
882 // TODO: where should this value come from?
883 static const int TV_DENSITY = 213;
884 info.density = TV_DENSITY / 160.0f;
885 info.orientation = 0;
886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 info.xdpi = xdpi;
889 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800891 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892
Andy McFadden91b2ca82014-06-13 14:04:23 -0700893 // This is how far in advance a buffer must be queued for
894 // presentation at a given time. If you want a buffer to appear
895 // on the screen at time N, you must submit the buffer before
896 // (N - presentationDeadline).
897 //
898 // Normally it's one full refresh period (to give SF a chance to
899 // latch the buffer), but this can be reduced by configuring a
900 // DispSync offset. Any additional delays introduced by the hardware
901 // composer or panel must be accounted for here.
902 //
903 // We add an additional 1ms to allow for processing time and
904 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800905 info.presentationDeadline =
906 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700907
908 // All non-virtual displays are currently considered secure.
909 info.secure = true;
910
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800911 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700912 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800913 std::swap(info.w, info.h);
914 }
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700917 }
918
Dan Stoza7f7da322014-05-02 15:26:25 -0700919 return NO_ERROR;
920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
923 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return BAD_VALUE;
925 }
926
Ana Krulecc2870422019-01-29 19:00:58 -0800927 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700928 return NO_ERROR;
929}
930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
932 const auto display = getDisplayDevice(displayToken);
933 if (!display) {
934 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800935 return BAD_VALUE;
936 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700939}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700940
Ady Abraham447052e2019-02-13 16:07:27 -0800941void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode,
942 ConfigEvent event) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944
Ana Krulec7d1d6832018-12-27 11:10:09 -0800945 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 // Lock is acquired by setRefreshRateTo.
947 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
949 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
950 return;
951 }
952
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953 // Lock is acquired by setRefreshRateTo.
954 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800955 if (!display) {
956 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
957 displayToken.get());
958 return;
959 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700960 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 return;
963 }
964 int currentDisplayPowerMode = display->getPowerMode();
965 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
966 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700967 return;
968 }
969
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970 // Don't check against the current mode yet. Worst case we set the desired
971 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800972 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham447052e2019-02-13 16:07:27 -0800973 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, event};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800974
975 if (!mDesiredActiveConfigChanged) {
976 // This is the first time we set the desired
977 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
978
979 // This will trigger HWC refresh without resetting the idle timer.
980 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800982 mDesiredActiveConfigChanged = true;
983 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
986status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
987 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800988
989 std::vector<int32_t> allowedConfig;
990 allowedConfig.push_back(mode);
991
992 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993}
994
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995void SurfaceFlinger::setActiveConfigInternal() {
996 ATRACE_CALL();
997
998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800999 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001000
1001 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1002 display->setActiveConfig(mUpcomingActiveConfig.configId);
1003
Ana Krulecc2870422019-01-29 19:00:58 -08001004 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ady Abraham447052e2019-02-13 16:07:27 -08001006 if (mUpcomingActiveConfig.event != ConfigEvent::None) {
1007 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1008 mUpcomingActiveConfig.configId);
1009 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010}
1011
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001013 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 // we may be in the process of changing the active state
1015 if (mWaitForNextInvalidate) {
1016 mWaitForNextInvalidate = false;
1017
1018 repaintEverythingForHWC();
1019 // We do not want to give another frame to HWC while we are transitioning.
1020 return true;
1021 }
1022
1023 if (mCheckPendingFence) {
1024 if (mPreviousPresentFence != Fence::NO_FENCE &&
1025 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1026 // fence has not signaled yet. wait for the next invalidate
1027 repaintEverythingForHWC();
1028 return true;
1029 }
1030
1031 // We received the present fence from the HWC, so we assume it successfully updated
1032 // the config, hence we update SF.
1033 mCheckPendingFence = false;
1034 setActiveConfigInternal();
1035 }
1036
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001037 // Store the local variable to release the lock.
1038 ActiveConfigInfo desiredActiveConfig;
1039 {
1040 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 if (!mDesiredActiveConfigChanged) {
1042 return false;
1043 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001044 desiredActiveConfig = mDesiredActiveConfig;
1045 }
1046
1047 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1049 // display is not valid or we are already in the requested mode
1050 // on both cases there is nothing left to do
1051 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1052 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1053 mDesiredActiveConfigChanged = false;
1054 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1055 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001056 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001057
Ady Abraham838de062019-02-04 10:24:03 -08001058 // Desired active config was set, it is different than the config currently in use, however
1059 // allowed configs might have change by the time we process the refresh.
1060 // Make sure the desired config is still allowed
1061 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1062 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1063 mDesiredActiveConfig.configId = display->getActiveConfig();
1064 return false;
1065 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001066 mUpcomingActiveConfig = desiredActiveConfig;
1067 const auto displayId = display->getId();
1068 LOG_ALWAYS_FATAL_IF(!displayId);
1069
1070 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1071 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1072
1073 // we need to submit an empty frame to HWC to start the process
1074 mWaitForNextInvalidate = true;
1075 mCheckPendingFence = true;
1076
1077 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1081 Vector<ColorMode>* outColorModes) {
1082 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001083 return BAD_VALUE;
1084 }
1085
Peiyong Lina52f0292018-03-14 17:26:31 -07001086 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001087 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001088 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1089
1090 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1091 if (!displayId) {
1092 return NAME_NOT_FOUND;
1093 }
1094
Dominik Laskowski075d3172018-05-24 15:50:06 -07001095 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001096 }
Michael Wright28f24d02016-07-12 13:30:53 -07001097 outColorModes->clear();
1098 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1099
1100 return NO_ERROR;
1101}
1102
Daniel Solomon42d04562019-01-20 21:03:19 -08001103status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1104 ui::DisplayPrimaries &primaries) {
1105 if (!displayToken) {
1106 return BAD_VALUE;
1107 }
1108
1109 // Currently we only support this API for a single internal display.
1110 if (getInternalDisplayToken() != displayToken) {
1111 return BAD_VALUE;
1112 }
1113
1114 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1115 return NO_ERROR;
1116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1119 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001120 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001121 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001122 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001123}
1124
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001126 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127 Vector<ColorMode> modes;
1128 getDisplayColorModes(displayToken, &modes);
1129 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1130 if (mode < ColorMode::NATIVE || !exists) {
1131 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1132 decodeColorMode(mode).c_str(), mode, displayToken.get());
1133 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001134 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const auto display = getDisplayDevice(displayToken);
1136 if (!display) {
1137 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1138 decodeColorMode(mode).c_str(), mode, displayToken.get());
1139 } else if (display->isVirtual()) {
1140 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1141 decodeColorMode(mode).c_str(), mode);
1142 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001143 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1144 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001145 }
1146 }));
1147
Michael Wright28f24d02016-07-12 13:30:53 -07001148 return NO_ERROR;
1149}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001150
Svetoslavd85084b2014-03-20 10:28:31 -07001151status_t SurfaceFlinger::clearAnimationFrameStats() {
1152 Mutex::Autolock _l(mStateLock);
1153 mAnimFrameTracker.clearStats();
1154 return NO_ERROR;
1155}
1156
1157status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1158 Mutex::Autolock _l(mStateLock);
1159 mAnimFrameTracker.getStats(outStats);
1160 return NO_ERROR;
1161}
1162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1164 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001165 Mutex::Autolock _l(mStateLock);
1166
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001167 const auto display = getDisplayDeviceLocked(displayToken);
1168 if (!display) {
1169 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001170 return BAD_VALUE;
1171 }
1172
Peiyong Linfb069302018-04-25 14:34:31 -07001173 // At this point the DisplayDeivce should already be set up,
1174 // meaning the luminance information is already queried from
1175 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001176 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001177 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1178 capabilities.getDesiredMaxLuminance(),
1179 capabilities.getDesiredMaxAverageLuminance(),
1180 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001181
1182 return NO_ERROR;
1183}
1184
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001185status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1186 ui::PixelFormat* outFormat,
1187 ui::Dataspace* outDataspace,
1188 uint8_t* outComponentMask) const {
1189 if (!outFormat || !outDataspace || !outComponentMask) {
1190 return BAD_VALUE;
1191 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001192 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001193 if (!display || !display->getId()) {
1194 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1195 return BAD_VALUE;
1196 }
1197 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1198 outDataspace, outComponentMask);
1199}
1200
Kevin DuBois74e53772018-11-19 10:52:38 -08001201status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1202 bool enable, uint8_t componentMask,
1203 uint64_t maxFrames) const {
1204 const auto display = getDisplayDevice(displayToken);
1205 if (!display || !display->getId()) {
1206 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1207 return BAD_VALUE;
1208 }
1209
1210 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1211 componentMask, maxFrames);
1212}
1213
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001214status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1215 uint64_t maxFrames, uint64_t timestamp,
1216 DisplayedFrameStats* outStats) const {
1217 const auto display = getDisplayDevice(displayToken);
1218 if (!display || !display->getId()) {
1219 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1220 return BAD_VALUE;
1221 }
1222
1223 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1224 outStats);
1225}
1226
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001227status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1228 if (!outSupported) {
1229 return BAD_VALUE;
1230 }
1231 *outSupported = getRenderEngine().supportsProtectedContent();
1232 return NO_ERROR;
1233}
1234
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001235status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1236 bool* outIsWideColorDisplay) const {
1237 if (!displayToken || !outIsWideColorDisplay) {
1238 return BAD_VALUE;
1239 }
1240 Mutex::Autolock _l(mStateLock);
1241 const auto display = getDisplayDeviceLocked(displayToken);
1242 if (!display) {
1243 return BAD_VALUE;
1244 }
1245 *outIsWideColorDisplay = display->hasWideColorGamut();
1246 return NO_ERROR;
1247}
1248
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001249status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001250 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001251 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001252
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 if (mInjectVSyncs == enable) {
1254 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001255 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256
Ana Krulecc2870422019-01-29 19:00:58 -08001257 auto resyncCallback =
1258 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001259
Ana Krulec98b5b242018-08-10 15:03:23 -07001260 // TODO(akrulec): Part of the Injector should be refactored, so that it
1261 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262 if (enable) {
1263 ALOGV("VSync Injections enabled");
1264 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001265 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001266 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001267 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001268 impl::EventThread::InterceptVSyncsCallback(),
1269 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001270 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001271 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 } else {
1273 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001274 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1275 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001276 }
1277
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001278 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001279 }));
1280
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001281 return NO_ERROR;
1282}
1283
1284status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001285 Mutex::Autolock _l(mStateLock);
1286
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001287 if (!mInjectVSyncs) {
1288 ALOGE("VSync Injections not enabled");
1289 return BAD_VALUE;
1290 }
1291 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1292 ALOGV("Injecting VSync inside SurfaceFlinger");
1293 mVSyncInjector->onInjectSyncEvent(when);
1294 }
1295 return NO_ERROR;
1296}
1297
Lloyd Pique755e3192018-01-31 16:46:15 -08001298status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1299 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001300 // Try to acquire a lock for 1s, fail gracefully
1301 const status_t err = mStateLock.timedLock(s2ns(1));
1302 const bool locked = (err == NO_ERROR);
1303 if (!locked) {
1304 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1305 return TIMED_OUT;
1306 }
1307
1308 outLayers->clear();
1309 mCurrentState.traverseInZOrder([&](Layer* layer) {
1310 outLayers->push_back(layer->getLayerDebugInfo());
1311 });
1312
1313 mStateLock.unlock();
1314 return NO_ERROR;
1315}
1316
Peiyong Linc6780972018-10-28 15:24:08 -07001317status_t SurfaceFlinger::getCompositionPreference(
1318 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1319 Dataspace* outWideColorGamutDataspace,
1320 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001321 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001322 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001323 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001324 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001325 return NO_ERROR;
1326}
1327
Dan Stozaec460082018-12-17 15:35:09 -08001328status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1329 const sp<IBinder>& stopLayerHandle,
1330 const sp<IRegionSamplingListener>& listener) {
1331 if (!listener) {
1332 return BAD_VALUE;
1333 }
1334 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001335 return NO_ERROR;
1336}
1337
Dan Stozaec460082018-12-17 15:35:09 -08001338status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1339 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001340 return NO_ERROR;
1341}
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001342// ----------------------------------------------------------------------------
1343
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001344sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1345 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001346 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001347 Mutex::Autolock lock(mStateLock);
1348 return getVsyncPeriod();
1349 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001350
Ana Krulecc2870422019-01-29 19:00:58 -08001351 const auto& handle =
1352 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001353
Ana Krulecc2870422019-01-29 19:00:58 -08001354 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001355}
1356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001357// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001358
1359void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001360 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001361}
1362
1363void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001364 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001365}
1366
1367void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001368 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001369}
1370
1371void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001372 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001373 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001374}
1375
1376status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001377 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001378 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001379}
1380
1381status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001382 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001383 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001384 if (res == NO_ERROR) {
1385 msg->wait();
1386 }
1387 return res;
1388}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001389
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001390void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001391 do {
1392 waitForEvent();
1393 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001394}
1395
Dominik Laskowski83b88212018-12-11 13:34:06 -08001396nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001397 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001398 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1399 return 0;
1400 }
1401
1402 const auto config = getHwComposer().getActiveConfig(*displayId);
1403 return config ? config->getVsyncPeriod() : 0;
1404}
1405
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001406void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1407 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001408 ATRACE_NAME("SF onVsync");
1409
Steven Thomas3cfac282017-02-06 12:29:30 -08001410 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001412 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 return;
1414 }
1415
Dominik Laskowski075d3172018-05-24 15:50:06 -07001416 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001417 return;
1418 }
1419
Dominik Laskowski075d3172018-05-24 15:50:06 -07001420 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001421 // For now, we don't do anything with external display vsyncs.
1422 return;
1423 }
1424
Ana Krulecc2870422019-01-29 19:00:58 -08001425 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001426}
1427
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001428void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001429 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1430 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001431}
1432
Ady Abraham838de062019-02-04 10:24:03 -08001433bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1434 std::lock_guard lock(mAllowedConfigsLock);
1435
1436 // if allowed configs are not set yet for this display, every config is considered allowed
1437 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1438 return true;
1439 }
1440
1441 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1442}
1443
Ady Abraham447052e2019-02-13 16:07:27 -08001444void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001445 mPhaseOffsets->setRefreshRateType(refreshRate);
1446
1447 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1448 mVsyncModulator.setPhaseOffsets(early, gl, late);
1449
1450 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001451 return;
1452 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001453
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1455 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1456 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1457 // refresh cycle.
1458
1459 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001460 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001461 if (currentVsyncPeriod == 0) {
1462 return;
1463 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001464
Ana Krulec7d1d6832018-12-27 11:10:09 -08001465 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1466 // floating numbers.
1467 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001468 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1469 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001470 if (std::abs(currentFps - newFps) <= 1) {
1471 return;
1472 }
1473
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001474 const auto displayId = getInternalDisplayIdLocked();
1475 LOG_ALWAYS_FATAL_IF(!displayId);
1476
1477 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001478 for (int i = 0; i < configs.size(); i++) {
Ady Abraham838de062019-02-04 10:24:03 -08001479 if (!isConfigAllowed(*displayId, i)) {
1480 ALOGV("Skipping config %d as it is not part of allowed configs", i);
1481 continue;
1482 }
1483
Ana Krulec7d1d6832018-12-27 11:10:09 -08001484 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1485 if (vsyncPeriod == 0) {
1486 continue;
1487 }
1488 const float fps = 1e9 / vsyncPeriod;
1489 // TODO(b/113612090): There should be a better way at determining which config
1490 // has the right refresh rate.
1491 if (std::abs(fps - newFps) <= 1) {
Ady Abraham447052e2019-02-13 16:07:27 -08001492 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001493 }
1494 }
1495}
1496
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001497void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001498 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001500 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
Lloyd Piqueba04e622017-12-14 17:11:26 -08001502 // Ignore events that do not have the right sequenceId.
1503 if (sequenceId != getBE().mComposerSequenceId) {
1504 return;
1505 }
1506
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Only lock if we're not on the main thread. This function is normally
1508 // called on a hwbinder thread, but for the primary display it's called on
1509 // the main thread with the state lock already held, so don't attempt to
1510 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001511 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001512
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001513 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001514
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001515 if (std::this_thread::get_id() == mMainThreadId) {
1516 // Process all pending hot plug events immediately if we are on the main thread.
1517 processDisplayHotplugEventsLocked();
1518 }
1519
Lloyd Piqueba04e622017-12-14 17:11:26 -08001520 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001521}
1522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001524 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001525 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001527 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001528 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001529}
1530
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001531void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001532 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001534 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001535 getHwComposer().setVsyncEnabled(*displayId,
1536 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1537 }
Mathias Agopian86303202012-07-24 22:46:10 -07001538}
1539
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001541void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001542 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001543 // Clear the drawing state so that the logic inside of
1544 // handleTransactionLocked will fire. It will determine the delta between
1545 // mCurrentState and mDrawingState and re-apply all changes when we make the
1546 // transition.
1547 mDrawingState.displays.clear();
1548 mDisplays.clear();
1549}
1550
Steven Thomas050b2c82017-03-06 11:45:16 -08001551void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001552 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001553 if (!mVrFlinger)
1554 return;
1555 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001556 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001557 return;
1558 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559
Lloyd Pique441d5042018-10-18 16:49:51 -07001560 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 ALOGE("Vr flinger is only supported for remote hardware composer"
1562 " service connections. Ignoring request to transition to vr"
1563 " flinger.");
1564 mVrFlingerRequestsDisplay = false;
1565 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001566 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001568 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001571 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001572
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001573 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001574
1575 // Clear out all the output layers from the composition engine for all
1576 // displays before destroying the hardware composer interface. This ensures
1577 // any HWC layers are destroyed through that interface before it becomes
1578 // invalid.
1579 for (const auto& [token, displayDevice] : mDisplays) {
1580 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1581 compositionengine::Output::OutputLayers());
1582 }
1583
Steven Thomas0123ac62018-07-12 11:32:34 -07001584 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1585 // called below. Clear the reference now so we don't accidentally use it
1586 // later.
1587 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588
Steven Thomasb02664d2017-07-26 18:48:28 -07001589 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001594 // Delete the current instance before creating the new one
1595 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1596 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1597 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1598 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001599
Lloyd Pique441d5042018-10-18 16:49:51 -07001600 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001601 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001602
1603 if (vrFlingerRequestsDisplay) {
1604 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001605 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001606
1607 mVisibleRegionsDirty = true;
1608 invalidateHwcGeometry();
1609
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001610 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001611 display = getDefaultDisplayDeviceLocked();
1612 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001613 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001614
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001616 const nsecs_t vsyncPeriod = getVsyncPeriod();
1617 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001618
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001619 // The present fences returned from vr_hwc are not an accurate
1620 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001621 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001622
Steven Thomasb02664d2017-07-26 18:48:28 -07001623 // Use phase of 0 since phase is not known.
1624 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001625 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001626 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001627
Ana Krulecc2870422019-01-29 19:00:58 -08001628 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001629
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001630 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632}
1633
Mathias Agopian4fec8732012-06-29 14:12:52 -07001634void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001635 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001636 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001637 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001638 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001639 break;
1640 }
1641
Ana Krulecba13ab32019-02-20 14:14:12 -08001642 if (mUse90Hz && mUseSmart90ForVideo) {
1643 // This call is made each time SF wakes up and creates a new frame. It is part
1644 // of video detection feature.
1645 mScheduler->incrementFrameCounter();
1646 }
Alec Mourife3dc942019-02-12 14:19:18 -08001647 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001648 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001649 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001650 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001651 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1652 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001653 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001654 }
1655 // For now, only propagate backpressure when missing a hwc frame.
1656 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001657 if (mPropagateBackpressure) {
1658 signalLayerUpdate();
1659 break;
1660 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001661 }
Dan Stoza50182882016-07-08 12:02:20 -07001662
Steven Thomas050b2c82017-03-06 11:45:16 -08001663 // Now that we're going to make it to the handleMessageTransaction()
1664 // call below it's safe to call updateVrFlinger(), which will
1665 // potentially trigger a display handoff.
1666 updateVrFlinger();
1667
Dan Stoza6b9454d2014-11-07 16:00:59 -08001668 bool refreshNeeded = handleMessageTransaction();
1669 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001670
1671 updateCursorAsync();
1672 updateInputFlinger();
1673
Dan Stoza58784442014-12-02 16:58:17 -08001674 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001675 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001676 // Signal a refresh if a transaction modified the window state,
1677 // a new buffer was latched, or if HWC has requested a full
1678 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001679 signalRefresh();
1680 }
1681 break;
1682 }
1683 case MessageQueue::REFRESH: {
1684 handleMessageRefresh();
1685 break;
1686 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001687 }
1688}
1689
Dan Stoza6b9454d2014-11-07 16:00:59 -08001690bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001691 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001692 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001693
1694 // Apply any ready transactions in the queues if there are still transactions that have not been
1695 // applied, wake up during the next vsync period and check again
1696 bool transactionNeeded = false;
1697 if (!flushTransactionQueues()) {
1698 transactionNeeded = true;
1699 }
1700
Mathias Agopian4fec8732012-06-29 14:12:52 -07001701 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001702 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001703 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001704
1705 if (transactionNeeded) {
1706 setTransactionFlags(eTransactionNeeded);
1707 }
1708
1709 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001710}
1711
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001714
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001715 mRefreshPending = false;
1716
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001717 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001718 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001719 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001720 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001721 for (const auto& [token, display] : mDisplays) {
1722 beginFrame(display);
1723 prepareFrame(display);
1724 doDebugFlashRegions(display, repaintEverything);
1725 doComposition(display, repaintEverything);
1726 }
1727
Adrian Roos1e1a1282017-11-01 19:05:31 +01001728 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001729 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001730
1731 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001732 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001733
Dan Stozabfbffeb2016-07-21 14:49:33 -07001734 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001735 for (const auto& [token, displayDevice] : mDisplays) {
1736 auto display = displayDevice->getCompositionDisplay();
1737 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001738 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001739 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001740 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001741
Jorim Jaggi90535212018-05-23 23:44:06 +02001742 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001743
David Sodman7e4ae112018-02-09 15:02:28 -08001744 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001745
1746 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001748
David Sodmanfa9b2af2017-12-24 13:28:59 -08001749
1750bool SurfaceFlinger::handleMessageInvalidate() {
1751 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001752 bool refreshNeeded = handlePageFlip();
1753
Vishnu Nair4351ad52019-02-11 14:13:02 -08001754 if (mVisibleRegionsDirty) {
1755 computeLayerBounds();
1756 }
1757
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001758 for (auto& layer : mLayersPendingRefresh) {
1759 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001760 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001761 invalidateLayerStack(layer, visibleReg);
1762 }
1763 mLayersPendingRefresh.clear();
1764 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001765}
1766
David Sodman79bba0e2018-08-05 18:07:49 -07001767void SurfaceFlinger::calculateWorkingSet() {
1768 ATRACE_CALL();
1769 ALOGV(__FUNCTION__);
1770
David Sodman79bba0e2018-08-05 18:07:49 -07001771 // build the h/w work list
1772 if (CC_UNLIKELY(mGeometryInvalid)) {
1773 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001774 for (const auto& [token, displayDevice] : mDisplays) {
1775 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001776 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001777 if (!displayId) {
1778 continue;
1779 }
David Sodman79bba0e2018-08-05 18:07:49 -07001780
Lloyd Pique32cbe282018-10-19 13:09:22 -07001781 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001782 for (size_t i = 0; i < currentLayers.size(); i++) {
1783 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001784
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001785 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001786 layer->forceClientComposition(displayDevice);
1787 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001788 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001789
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001791 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001792 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001793 }
David Sodman79bba0e2018-08-05 18:07:49 -07001794 }
1795 }
1796 }
1797
1798 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001799 for (const auto& [token, displayDevice] : mDisplays) {
1800 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001801 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001802 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001803 continue;
1804 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001805 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001806
1807 if (mDrawingState.colorMatrixChanged) {
1808 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001809 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001810 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001811 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001812 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001813 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1814 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001815 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001816 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001817 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1818 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001819 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001820 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001821 }
1822
Peiyong Lind3788632018-09-18 16:01:31 -07001823 // TODO(b/111562338) remove when composer 2.3 is shipped.
1824 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001825 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001826 }
1827
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001828 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001829 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001830 }
1831
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001832 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001833 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001834 layer->setCompositionType(displayDevice,
1835 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001836 continue;
1837 }
1838
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001840 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001842 }
1843
Peiyong Lin13effd12018-07-24 17:01:47 -07001844 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001845 ColorMode colorMode;
1846 Dataspace dataSpace;
1847 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001848 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001849 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001850 }
1851 }
1852
1853 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001854
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001855 for (const auto& [token, displayDevice] : mDisplays) {
1856 auto display = displayDevice->getCompositionDisplay();
1857 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001858 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001859 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1860 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1861 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001862 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001863 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001864 }
1865 }
David Sodman79bba0e2018-08-05 18:07:49 -07001866}
1867
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1869 bool repaintEverything) {
1870 auto display = displayDevice->getCompositionDisplay();
1871 const auto& displayState = display->getState();
1872
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 // is debugging enabled
1874 if (CC_LIKELY(!mDebugRegion))
1875 return;
1876
Lloyd Pique32cbe282018-10-19 13:09:22 -07001877 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001878 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001879 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001880 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001881 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001882 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001883 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001884
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001885 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 }
1887 }
1888
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890
1891 if (mDebugRegion > 1) {
1892 usleep(mDebugRegion * 1000);
1893 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001894
Lloyd Pique32cbe282018-10-19 13:09:22 -07001895 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001896}
1897
Adrian Roos1e1a1282017-11-01 19:05:31 +01001898void SurfaceFlinger::doTracing(const char* where) {
1899 ATRACE_CALL();
1900 ATRACE_NAME(where);
1901 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001902 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001903 }
1904}
1905
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001906void SurfaceFlinger::logLayerStats() {
1907 ATRACE_CALL();
1908 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001909 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001910 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001911 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001912 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001913 }
1914 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001915
1916 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001917 }
1918}
1919
David Sodman2b406362017-12-15 13:33:47 -08001920void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 ATRACE_CALL();
1923 ALOGV("preComposition");
1924
David Sodman2b406362017-12-15 13:33:47 -08001925 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1926
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001928 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001929 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001930 needExtraInvalidate = true;
1931 }
Robert Carr2047fae2016-11-28 14:09:09 -08001932 });
1933
Mathias Agopiancd60f992012-08-16 16:28:27 -07001934 if (needExtraInvalidate) {
1935 signalLayerUpdate();
1936 }
1937}
1938
Ana Krulece588e312018-09-18 12:32:24 -07001939void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1940 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 // Update queue of past composite+present times and determine the
1942 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001943 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001945 while (!getBE().mCompositePresentTimes.empty()) {
1946 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 // Cached values should have been updated before calling this method,
1948 // which helps avoid duplicate syscalls.
1949 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1950 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1951 break;
1952 }
1953 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001954 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955 }
1956
1957 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001958 while (getBE().mCompositePresentTimes.size() > 16) {
1959 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960 }
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001963}
1964
Ana Krulece588e312018-09-18 12:32:24 -07001965void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1966 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 // Integer division and modulo round toward 0 not -inf, so we need to
1968 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001969 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1970 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1971 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972
Ana Krulec757f63a2019-01-25 10:46:18 -08001973 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001974 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001975 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001976 }
1977
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Snap the latency to a value that removes scheduling jitter from the
1979 // composition and present times, which often have >1ms of jitter.
1980 // Reducing jitter is important if an app attempts to extrapolate
1981 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001982 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001983 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001984 nsecs_t bias = stats.vsyncPeriod / 2;
1985 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1986 nsecs_t snappedCompositeToPresentLatency =
1987 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988
David Sodman99974d22017-11-28 12:04:33 -08001989 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001990 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1991 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001992 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001993}
1994
Ady Abraham8164d482019-01-11 14:47:59 -08001995// debug patch for b/119477596 - add stack guards to catch stack
1996// corruptions and disable clang optimizations.
1997// The code below is temporary and planned to be removed once stack
1998// corruptions are found.
1999#pragma clang optimize off
2000class StackGuard {
2001public:
2002 StackGuard(const char* name, const char* func, int line) {
2003 guarders.reserve(MIN_CAPACITY);
2004 guarders.push_back({this, name, func, line});
2005 validate();
2006 }
2007 ~StackGuard() {
2008 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2009 if (i->guard == this) {
2010 guarders.erase(i);
2011 break;
2012 }
2013 }
2014 }
2015
2016 static void validate() {
2017 for (const auto& guard : guarders) {
2018 if (guard.guard->cookie != COOKIE_VALUE) {
2019 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2020 CallStack stack(LOG_TAG);
2021 abort();
2022 }
2023 }
2024 }
2025
2026private:
2027 uint64_t cookie = COOKIE_VALUE;
2028 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2029 static constexpr size_t MIN_CAPACITY = 16;
2030
2031 struct GuarderElement {
2032 StackGuard* guard;
2033 const char* name;
2034 const char* func;
2035 int line;
2036 };
2037
2038 static std::vector<GuarderElement> guarders;
2039};
2040std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2041
2042#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2043
2044#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002045void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002046{
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 ATRACE_CALL();
2049 ALOGV("postComposition");
2050
Brian Anderson3546a3f2016-07-14 11:51:14 -07002051 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002052 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002054 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002055 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002056 }
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002059 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002060 const auto displayDevice = getDefaultDisplayDeviceLocked();
2061 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002062
David Sodman73beded2017-11-15 11:56:06 -08002063 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002065 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2066
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002069 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2070 ->getRenderSurface()
2071 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002072 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002073 } else {
2074 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2075 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002076
Ady Abraham8164d482019-01-11 14:47:59 -08002077 ASSERT_ON_STACK_GUARD();
2078
David Sodman73beded2017-11-15 11:56:06 -08002079 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002080 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2081 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002082 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002083 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002084 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085
Ana Krulece588e312018-09-18 12:32:24 -07002086 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002087 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002088 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089
Ady Abraham8164d482019-01-11 14:47:59 -08002090 ASSERT_ON_STACK_GUARD();
2091
David Sodman2b406362017-12-15 13:33:47 -08002092 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002093 // when we started doing work for this frame, but that should be okay
2094 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002095 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002096 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002097 DEFINE_STACK_GUARD(compositorTiming);
2098
Brian Andersond0010582017-03-07 13:20:31 -08002099 {
David Sodman99974d22017-11-28 12:04:33 -08002100 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002101 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002102 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002103
2104 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002105 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002106
Robert Carr2047fae2016-11-28 14:09:09 -08002107 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002108 bool frameLatched =
2109 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2110 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002111 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002112 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002113 recordBufferingStats(layer->getName().string(),
2114 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002115 }
Ady Abraham8164d482019-01-11 14:47:59 -08002116 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002117 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002118
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002119 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002120 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002121 mScheduler->addPresentFence(presentFenceTime);
2122 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002123 }
2124
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002125 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002126 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2127 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002128 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 }
2130 }
2131
Ady Abraham8164d482019-01-11 14:47:59 -08002132 ASSERT_ON_STACK_GUARD();
2133
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002134 if (mAnimCompositionPending) {
2135 mAnimCompositionPending = false;
2136
Brian Anderson4e606e32017-03-16 15:34:57 -07002137 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002138 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002139 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002140
2141 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002142 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002143 // The HWC doesn't support present fences, so use the refresh
2144 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002145 const nsecs_t presentTime =
2146 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002147 DEFINE_STACK_GUARD(presentTime);
2148
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002149 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002150 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002151 }
2152 mAnimFrameTracker.advanceFrame();
2153 }
Dan Stozab90cf072015-03-05 11:05:59 -08002154
Ady Abraham8164d482019-01-11 14:47:59 -08002155 ASSERT_ON_STACK_GUARD();
2156
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002157 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002158 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002159 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002160 }
2161
Ady Abraham8164d482019-01-11 14:47:59 -08002162 ASSERT_ON_STACK_GUARD();
2163
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002164 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002165
Ady Abraham8164d482019-01-11 14:47:59 -08002166 ASSERT_ON_STACK_GUARD();
2167
Lloyd Pique32cbe282018-10-19 13:09:22 -07002168 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2169 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002170 return;
2171 }
2172
2173 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002174 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002175 if (mHasPoweredOff) {
2176 mHasPoweredOff = false;
2177 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002178 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002179 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002180 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002181 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002182 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2183 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002184 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002185 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002186 }
David Sodman4a36e932017-11-07 14:29:47 -08002187 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002188
2189 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002190 }
David Sodman4a36e932017-11-07 14:29:47 -08002191 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002192 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002193
2194 {
2195 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002196 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002197 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002198 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002199 if (refillCount > 0) {
2200 const size_t offset = mTexturePool.size();
2201 mTexturePool.resize(mTexturePoolSize);
2202 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2203 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2204 }
Ady Abraham8164d482019-01-11 14:47:59 -08002205 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002206 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002207
Marissa Wallfda30bb2018-10-12 11:34:28 -07002208 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002209 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002210
Dan Stozaec460082018-12-17 15:35:09 -08002211 if (mLumaSampling) {
2212 mRegionSamplingThread->sampleNow();
2213 }
2214
Ady Abraham8164d482019-01-11 14:47:59 -08002215 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002216}
Ady Abraham8164d482019-01-11 14:47:59 -08002217#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218
Vishnu Nair4351ad52019-02-11 14:13:02 -08002219void SurfaceFlinger::computeLayerBounds() {
2220 for (const auto& pair : mDisplays) {
2221 const auto& displayDevice = pair.second;
2222 const auto display = displayDevice->getCompositionDisplay();
2223 for (const auto& layer : mDrawingState.layersSortedByZ) {
2224 // only consider the layers on the given layer stack
2225 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002226 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002227 }
2228
2229 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2230 }
2231 }
2232}
2233
Mathias Agopiancd60f992012-08-16 16:28:27 -07002234void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235 ATRACE_CALL();
2236 ALOGV("rebuildLayerStacks");
2237
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002238 // We need to clear these out now as these may be holding on to a
2239 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2240 // also holds a reference. When the set of visible layers is recomputed,
2241 // some layers may be destroyed if the only thing keeping them alive was
2242 // that list of visible layers associated with each display. The layer
2243 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2244 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2245 for (const auto& [token, display] : mDisplays) {
2246 getBE().mCompositionInfo[token].clear();
2247 }
2248
Mathias Agopiancd60f992012-08-16 16:28:27 -07002249 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002250 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002251 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002252 mVisibleRegionsDirty = false;
2253 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002254
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002255 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002256 const auto& displayDevice = pair.second;
2257 auto display = displayDevice->getCompositionDisplay();
2258 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 Region opaqueRegion;
2260 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002261 compositionengine::Output::OutputLayers layersSortedByZ;
2262 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002263 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002264 const ui::Transform& tr = displayState.transform;
2265 const Rect bounds = displayState.bounds;
2266 if (displayState.isEnabled) {
2267 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002268
Jeff Sharkey76488112017-02-27 14:15:18 -07002269 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002270 auto compositionLayer = layer->getCompositionLayer();
2271 if (compositionLayer == nullptr) {
2272 return;
2273 }
2274
Lloyd Pique32cbe282018-10-19 13:09:22 -07002275 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002276 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2277 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2278
Lloyd Pique07e33212018-12-18 16:33:37 -08002279 bool needsOutputLayer = false;
2280
Lloyd Piqueef36b002019-01-23 17:52:04 -08002281 if (display->belongsInOutput(layer->getLayerStack(),
2282 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002283 Region drawRegion(tr.transform(
2284 layer->visibleNonTransparentRegion));
2285 drawRegion.andSelf(bounds);
2286 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002287 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002288 }
Chia-I Wu83806892017-11-16 10:50:20 -08002289 }
2290
Lloyd Pique07e33212018-12-18 16:33:37 -08002291 if (needsOutputLayer) {
2292 layersSortedByZ.emplace_back(
2293 display->getOrCreateOutputLayer(displayId, compositionLayer,
2294 layerFE));
2295 deprecated_layersSortedByZ.add(layer);
2296
2297 auto& outputLayerState = layersSortedByZ.back()->editState();
2298 outputLayerState.visibleRegion =
2299 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2300 } else if (displayId) {
2301 // For layers that are being removed from a HWC display,
2302 // and that have queued frames, add them to a a list of
2303 // released layers so we can properly set a fence.
2304 bool hasExistingOutputLayer =
2305 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2306 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2307 mLayersWithQueuedFrames.cend(),
2308 layer) != mLayersWithQueuedFrames.cend();
2309
2310 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002311 layersNeedingFences.add(layer);
2312 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002313 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002314 });
2315 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002316
2317 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2318
2319 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002320 displayDevice->setLayersNeedingFences(layersNeedingFences);
2321
2322 Region undefinedRegion{bounds};
2323 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2324
2325 display->editState().undefinedRegion = undefinedRegion;
2326 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002327 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002328 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002329}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002330
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002333// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002335// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336// The returned HDR data space is one of
2337// - Dataspace::UNKNOWN
2338// - Dataspace::BT2020_HLG
2339// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002340Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2341 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002342 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 *outHdrDataSpace = Dataspace::UNKNOWN;
2344
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002346 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002347 case Dataspace::V0_SCRGB:
2348 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002349 case Dataspace::BT2020:
2350 case Dataspace::BT2020_ITU:
2351 case Dataspace::BT2020_LINEAR:
2352 case Dataspace::DISPLAY_BT2020:
2353 bestDataSpace = Dataspace::DISPLAY_BT2020;
2354 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002355 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002356 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002358 case Dataspace::BT2020_PQ:
2359 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002360 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002361 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002363 case Dataspace::BT2020_HLG:
2364 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002365 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366 // When there's mixed PQ content and HLG content, we set the HDR
2367 // data space to be BT2020_PQ and convert HLG to PQ.
2368 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2369 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002370 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 break;
2372 default:
2373 break;
2374 }
Romain Guy54f154a2017-10-24 21:40:32 +01002375 }
2376
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002378}
2379
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002380// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2382 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002383 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2384 *outMode = ColorMode::NATIVE;
2385 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002386 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002388 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002389
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002390 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002391 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002392
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002393 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2394
Peiyong Lina3ea5592019-02-10 14:45:00 -08002395 switch (mForceColorMode) {
2396 case ColorMode::SRGB:
2397 bestDataSpace = Dataspace::V0_SRGB;
2398 break;
2399 case ColorMode::DISPLAY_P3:
2400 bestDataSpace = Dataspace::DISPLAY_P3;
2401 break;
2402 default:
2403 break;
2404 }
2405
Peiyong Lindfde5112018-06-05 10:58:41 -07002406 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002407 const bool isHdr =
2408 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002409 if (isHdr) {
2410 bestDataSpace = hdrDataSpace;
2411 }
2412
Chia-I Wu0d711262018-05-21 15:19:35 -07002413 RenderIntent intent;
2414 switch (mDisplayColorSetting) {
2415 case DisplayColorSetting::MANAGED:
2416 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002417 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002418 break;
2419 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002420 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002421 break;
2422 default: // vendor display color setting
2423 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2424 break;
2425 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002426
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002427 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002428}
2429
Lloyd Pique32cbe282018-10-19 13:09:22 -07002430void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2431 auto display = displayDevice->getCompositionDisplay();
2432 const auto& displayState = display->getState();
2433
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002434 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2436 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002437
David Sodmanfa9b2af2017-12-24 13:28:59 -08002438 // If nothing has changed (!dirty), don't recompose.
2439 // If something changed, but we don't currently have any visible layers,
2440 // and didn't when we last did a composition, then skip it this time.
2441 // The second rule does two things:
2442 // - When all layers are removed from a display, we'll emit one black
2443 // frame, then nothing more until we get new layers.
2444 // - When a display is created with a private layer stack, we won't
2445 // emit any black frames until a layer is added to the layer stack.
2446 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002447
Dominik Laskowski075d3172018-05-24 15:50:06 -07002448 const char flagPrefix[] = {'-', '+'};
2449 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2451 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2452 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2453 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002454
Lloyd Pique31cb2942018-10-19 17:23:03 -07002455 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002456
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002459 }
2460}
2461
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2463 auto display = displayDevice->getCompositionDisplay();
2464 const auto& displayState = display->getState();
2465
2466 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002467 return;
David Sodman2b406362017-12-15 13:33:47 -08002468 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002469
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002470 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002472 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002473}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002474
Lloyd Pique32cbe282018-10-19 13:09:22 -07002475void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002476 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 ALOGV("doComposition");
2478
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 auto display = displayDevice->getCompositionDisplay();
2480 const auto& displayState = display->getState();
2481
2482 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002483 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002484 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002485
David Sodmanfa9b2af2017-12-24 13:28:59 -08002486 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002487 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002488
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002490 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002491 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002492 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002493}
2494
David Sodmanfa9b2af2017-12-24 13:28:59 -08002495void SurfaceFlinger::postFrame()
2496{
2497 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498 const auto display = getDefaultDisplayDeviceLocked();
2499 if (display && getHwComposer().isConnected(*display->getId())) {
2500 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002501 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2502 logFrameStats();
2503 }
2504 }
2505}
2506
Lloyd Pique32cbe282018-10-19 13:09:22 -07002507void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002508 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002509 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002510
Lloyd Pique32cbe282018-10-19 13:09:22 -07002511 auto display = displayDevice->getCompositionDisplay();
2512 const auto& displayState = display->getState();
2513 const auto displayId = display->getId();
2514
David Sodmanfa9b2af2017-12-24 13:28:59 -08002515 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002516
Lloyd Pique32cbe282018-10-19 13:09:22 -07002517 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002518 if (displayId) {
2519 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002520 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002521 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002522 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002523 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002524
Chia-I Wu7b549592017-11-15 09:14:57 -08002525 // The layer buffer from the previous frame (if any) is released
2526 // by HWC only when the release fence from this frame (if any) is
2527 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002528 if (displayId && layer->hasHwcLayer(displayDevice)) {
2529 releaseFence =
2530 getHwComposer().getLayerReleaseFence(*displayId,
2531 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002532 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002533
2534 // If the layer was client composited in the previous frame, we
2535 // need to merge with the previous client target acquire fence.
2536 // Since we do not track that, always merge with the current
2537 // client target acquire fence when it is available, even though
2538 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002539 if (layer->getCompositionType(displayDevice) ==
2540 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002541 releaseFence =
2542 Fence::merge("LayerRelease", releaseFence,
2543 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002544 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002545
David Sodman15094112018-10-11 09:39:37 -07002546 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002547 }
Chia-I Wu83806892017-11-16 10:50:20 -08002548
2549 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002550 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002551 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002552 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002554 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002555 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002556 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002557 }
2558 }
2559
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 if (displayId) {
2561 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002562 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002563 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564}
2565
Mathias Agopian87baae12012-07-31 12:38:26 -07002566void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567{
Mathias Agopian841cde52012-03-01 15:44:37 -08002568 ATRACE_CALL();
2569
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002570 // here we keep a copy of the drawing state (that is the state that's
2571 // going to be overwritten by handleTransactionLocked()) outside of
2572 // mStateLock so that the side-effects of the State assignment
2573 // don't happen with mStateLock held (which can cause deadlocks).
2574 State drawingState(mDrawingState);
2575
Mathias Agopianca4d3602011-05-19 15:38:14 -07002576 Mutex::Autolock _l(mStateLock);
2577 const nsecs_t now = systemTime();
2578 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579
Mathias Agopianca4d3602011-05-19 15:38:14 -07002580 // Here we're guaranteed that some transaction flags are set
2581 // so we can call handleTransactionLocked() unconditionally.
2582 // We call getTransactionFlags(), which will also clear the flags,
2583 // with mStateLock held to guarantee that mCurrentState won't change
2584 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002585
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002586 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002587 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002588 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002589
Mathias Agopianca4d3602011-05-19 15:38:14 -07002590 mLastTransactionTime = systemTime() - now;
2591 mDebugInTransaction = 0;
2592 invalidateHwcGeometry();
2593 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002594}
2595
Lloyd Piqueba04e622017-12-14 17:11:26 -08002596void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2597 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 const std::optional<DisplayIdentificationInfo> info =
2599 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002600
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002602 continue;
2603 }
2604
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002607 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 mPhysicalDisplayTokens[info->id] = new BBinder();
2609 DisplayDeviceState state;
2610 state.displayId = info->id;
2611 state.isSecure = true; // All physical displays are currently considered secure.
2612 state.displayName = info->name;
2613 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2614 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002615 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002616 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002617 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002618
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2620 if (index >= 0) {
2621 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2622 mInterceptor->saveDisplayDeletion(state.sequenceId);
2623 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002624 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002626 }
2627
2628 processDisplayChangesLocked();
2629 }
2630
2631 mPendingHotplugEvents.clear();
2632}
2633
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002634void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002635 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2636 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002637}
2638
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002641 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 const sp<IGraphicBufferProducer>& producer) {
2643 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002644 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002646 creationArgs.isSecure = state.isSecure;
2647 creationArgs.displaySurface = dispSurface;
2648 creationArgs.hasWideColorGamut = false;
2649 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002650
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002651 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 creationArgs.isPrimary = isInternalDisplay;
2653
2654 if (useColorManagement && displayId) {
2655 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002657 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002658 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002660
Dominik Laskowski7e045462018-05-30 13:02:02 -07002661 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002662 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002663 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664 }
tangrobin6753a022018-08-10 10:58:54 +08002665 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
Dominik Laskowski075d3172018-05-24 15:50:06 -07002667 if (displayId) {
2668 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002669 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002671 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672
Lloyd Pique90c115d2018-09-18 21:39:42 -07002673 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002675 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677 // Make sure that composition can never be stalled by a virtual display
2678 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002679 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002680 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002681 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2682 }
2683
Dominik Laskowski075d3172018-05-24 15:50:06 -07002684 creationArgs.displayInstallOrientation =
2685 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002686
Lloyd Pique99d3da52018-01-22 17:48:03 -08002687 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002688 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689
Lloyd Pique90c115d2018-09-18 21:39:42 -07002690 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002691
2692 if (maxFrameBufferAcquiredBuffers >= 3) {
2693 nativeWindowSurface->preallocateBuffers();
2694 }
2695
2696 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002697 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002698 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002699 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002700 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002701 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002702 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2703 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002704 if (!state.isVirtual()) {
2705 LOG_ALWAYS_FATAL_IF(!displayId);
2706 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002707 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002708
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 display->setLayerStack(state.layerStack);
2710 display->setProjection(state.orientation, state.viewport, state.frame);
2711 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002712
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002714}
2715
Lloyd Pique347200f2017-12-14 17:00:15 -08002716void SurfaceFlinger::processDisplayChangesLocked() {
2717 // here we take advantage of Vector's copy-on-write semantics to
2718 // improve performance by skipping the transaction entirely when
2719 // know that the lists are identical
2720 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2721 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2722 if (!curr.isIdenticalTo(draw)) {
2723 mVisibleRegionsDirty = true;
2724 const size_t cc = curr.size();
2725 size_t dc = draw.size();
2726
2727 // find the displays that were removed
2728 // (ie: in drawing state but not in current state)
2729 // also handle displays that changed
2730 // (ie: displays that are in both lists)
2731 for (size_t i = 0; i < dc;) {
2732 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2733 if (j < 0) {
2734 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002735 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002736 // Save display ID before disconnecting.
2737 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002738 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002739
2740 if (!display->isVirtual()) {
2741 LOG_ALWAYS_FATAL_IF(!displayId);
2742 dispatchDisplayHotplugEvent(displayId->value, false);
2743 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002744 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002745
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002747 } else {
2748 // this display is in both lists. see if something changed.
2749 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2752 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2753 if (state_binder != draw_binder) {
2754 // changing the surface is like destroying and
2755 // recreating the DisplayDevice, so we just remove it
2756 // from the drawing state, so that it get re-added
2757 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002758 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002759 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 mDrawingState.displays.removeItemsAt(i);
2763 dc--;
2764 // at this point we must loop to the next item
2765 continue;
2766 }
2767
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002768 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002769 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002770 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 }
2772 if ((state.orientation != draw[i].orientation) ||
2773 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 }
2776 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002777 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 }
2779 }
2780 }
2781 ++i;
2782 }
2783
2784 // find displays that were added
2785 // (ie: in current state but not in drawing state)
2786 for (size_t i = 0; i < cc; i++) {
2787 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2788 const DisplayDeviceState& state(curr[i]);
2789
Lloyd Pique542307f2018-10-19 13:24:08 -07002790 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002791 sp<IGraphicBufferProducer> producer;
2792 sp<IGraphicBufferProducer> bqProducer;
2793 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002794 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002795
Dominik Laskowski075d3172018-05-24 15:50:06 -07002796 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002797 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002798 // Virtual displays without a surface are dormant:
2799 // they have external state (layer stack, projection,
2800 // etc.) but no internal state (i.e. a DisplayDevice).
2801 if (state.surface != nullptr) {
2802 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002803 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002804 int width = 0;
2805 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2806 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2807 int height = 0;
2808 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2809 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2810 int intFormat = 0;
2811 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2812 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002813 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002814
Dominik Laskowski075d3172018-05-24 15:50:06 -07002815 displayId =
2816 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002817 }
2818
2819 // TODO: Plumb requested format back up to consumer
2820
2821 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002822 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002823 bqProducer, bqConsumer,
2824 state.displayName);
2825
2826 dispSurface = vds;
2827 producer = vds;
2828 }
2829 } else {
2830 ALOGE_IF(state.surface != nullptr,
2831 "adding a supported display, but rendering "
2832 "surface is provided (%p), ignoring it",
2833 state.surface.get());
2834
Dominik Laskowski075d3172018-05-24 15:50:06 -07002835 displayId = state.displayId;
2836 LOG_ALWAYS_FATAL_IF(!displayId);
2837 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002838 producer = bqProducer;
2839 }
2840
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002842 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002843 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002844 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002846 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002847 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002848 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002849 }
2850 }
2851 }
2852 }
2853 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002854
2855 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002856}
2857
Mathias Agopian87baae12012-07-31 12:38:26 -07002858void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002859{
Dan Stoza7dde5992015-05-22 09:51:44 -07002860 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002861 mCurrentState.traverseInZOrder([](Layer* layer) {
2862 layer->notifyAvailableFrames();
2863 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002864
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 /*
2866 * Traversal of the children
2867 * (perform the transaction for each of them if needed)
2868 */
2869
Mathias Agopian3559b072012-08-15 13:46:03 -07002870 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002871 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002873 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874
2875 const uint32_t flags = layer->doTransaction(0);
2876 if (flags & Layer::eVisibleRegion)
2877 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002878
2879 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002880 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002881 }
Robert Carr2047fae2016-11-28 14:09:09 -08002882 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 }
2884
2885 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002886 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 */
2888
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002890 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002891 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002894 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002895 // The transform hint might have changed for some layers
2896 // (either because a display has changed, or because a layer
2897 // as changed).
2898 //
2899 // Walk through all the layers in currentLayers,
2900 // and update their transform hint.
2901 //
2902 // If a layer is visible only on a single display, then that
2903 // display is used to calculate the hint, otherwise we use the
2904 // default display.
2905 //
2906 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2907 // the hint is set before we acquire a buffer from the surface texture.
2908 //
2909 // NOTE: layer transactions have taken place already, so we use their
2910 // drawing state. However, SurfaceFlinger's own transaction has not
2911 // happened yet, so we must use the current state layer list
2912 // (soon to become the drawing state list).
2913 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002915 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002916 bool first = true;
2917 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002918 // NOTE: we rely on the fact that layers are sorted by
2919 // layerStack first (so we don't have to traverse the list
2920 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002922 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002923 currentlayerStack = layerStack;
2924 // figure out if this layerstack is mirrored
2925 // (more than one display) if so, pick the default display,
2926 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 hintDisplay = nullptr;
2928 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002929 if (display->getCompositionDisplay()
2930 ->belongsInOutput(layer->getLayerStack(),
2931 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 if (hintDisplay) {
2933 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002934 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002935 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002937 }
2938 }
2939 }
2940 }
Chet Haase91d25932013-04-11 15:24:55 -07002941
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002943 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2944 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002945
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002946 // could be null when this layer is using a layerStack
2947 // that is not visible on any display. Also can occur at
2948 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002949 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002950 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002951
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002953 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002954 if (hintDisplay) {
2955 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002956 }
Robert Carr2047fae2016-11-28 14:09:09 -08002957
2958 first = false;
2959 });
Mathias Agopian84300952012-11-21 16:02:13 -08002960 }
2961
2962
Mathias Agopian3559b072012-08-15 13:46:03 -07002963 /*
2964 * Perform our own transaction if needed
2965 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002966
2967 if (mLayersAdded) {
2968 mLayersAdded = false;
2969 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002970 mVisibleRegionsDirty = true;
2971 }
2972
2973 // some layers might have been removed, so
2974 // we need to update the regions they're exposing.
2975 if (mLayersRemoved) {
2976 mLayersRemoved = false;
2977 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002978 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002980 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002981 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002982 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002983 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002984 }
Robert Carr2047fae2016-11-28 14:09:09 -08002985 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 }
2987
Vishnu Nairec0ab382019-02-13 15:32:56 -08002988 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002990}
2991
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002992void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002993 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002994 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002995 return;
2996 }
2997
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002998 if (mVisibleRegionsDirty || mInputInfoChanged) {
2999 mInputInfoChanged = false;
3000 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08003001 } else if (mInputWindowCommands.syncInputWindows) {
3002 // If the caller requested to sync input windows, but there are no
3003 // changes to input windows, notify immediately.
3004 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003005 }
3006
3007 executeInputWindowCommands();
3008}
3009
3010void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003011 Vector<InputWindowInfo> inputHandles;
3012
3013 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3014 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003015 // When calculating the screen bounds we ignore the transparent region since it may
3016 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003017 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003018 }
3019 });
chaviw291d88a2019-02-14 10:33:58 -08003020
3021 mInputFlinger->setInputWindows(inputHandles,
3022 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3023 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003024}
3025
Vishnu Nairec0ab382019-02-13 15:32:56 -08003026void SurfaceFlinger::commitInputWindowCommands() {
3027 mInputWindowCommands.merge(mPendingInputWindowCommands);
3028 mPendingInputWindowCommands.clear();
3029}
3030
chaviwfbe5d9c2018-12-26 12:23:37 -08003031void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003032 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3033 if (transferTouchFocusCommand.fromToken != nullptr &&
3034 transferTouchFocusCommand.toToken != nullptr &&
3035 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3036 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3037 transferTouchFocusCommand.toToken);
3038 }
3039 }
3040
3041 mInputWindowCommands.clear();
3042}
3043
Riley Andrews03414a12014-07-01 14:22:59 -07003044void SurfaceFlinger::updateCursorAsync()
3045{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003046 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003047 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003048 continue;
3049 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003051 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3052 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003053 }
3054 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003055}
3056
chaviw61626f22018-11-15 16:26:27 -08003057void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3058 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003059 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003060 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003061 }
3062 layer->releasePendingBuffer(systemTime());
3063}
3064
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065void SurfaceFlinger::commitTransaction()
3066{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003067 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003068 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 for (const auto& l : mLayersPendingRemoval) {
3070 recordBufferingStats(l->getName().string(),
3071 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003072
Lloyd Pique07e33212018-12-18 16:33:37 -08003073 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003074 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003075 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003076 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 }
3078 mLayersPendingRemoval.clear();
3079 }
3080
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003081 // If this transaction is part of a window animation then the next frame
3082 // we composite should be considered an animation as well.
3083 mAnimCompositionPending = mAnimTransactionPending;
3084
Mathias Agopian4fec8732012-06-29 14:12:52 -07003085 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003086 // clear the "changed" flags in current state
3087 mCurrentState.colorMatrixChanged = false;
3088
Robert Carr1f0a16a2016-10-24 16:27:39 -07003089 mDrawingState.traverseInZOrder([](Layer* layer) {
3090 layer->commitChildList();
3091 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003092 mTransactionPending = false;
3093 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095}
3096
Lloyd Pique32cbe282018-10-19 13:09:22 -07003097void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003098 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003099 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003100 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003101
Lloyd Pique32cbe282018-10-19 13:09:22 -07003102 auto display = displayDevice->getCompositionDisplay();
3103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 Region aboveOpaqueLayers;
3105 Region aboveCoveredLayers;
3106 Region dirty;
3107
Mathias Agopian87baae12012-07-31 12:38:26 -07003108 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109
Robert Carr2047fae2016-11-28 14:09:09 -08003110 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003111 // start with the whole surface at its current location
3112 const Layer::State& s(layer->getDrawingState());
3113
Jesse Hall01e29052013-02-19 16:13:35 -08003114 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003115 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003116 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003117 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003118
Mathias Agopianab028732010-03-16 16:41:46 -07003119 /*
3120 * opaqueRegion: area of a surface that is fully opaque.
3121 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003123
3124 /*
3125 * visibleRegion: area of a surface that is visible on screen
3126 * and not fully transparent. This is essentially the layer's
3127 * footprint minus the opaque regions above it.
3128 * Areas covered by a translucent surface are considered visible.
3129 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003131
3132 /*
3133 * coveredRegion: area of a surface that is covered by all
3134 * visible regions above it (which includes the translucent areas).
3135 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003137
Jesse Halla8026d22012-09-25 13:25:04 -07003138 /*
3139 * transparentRegion: area of a surface that is hinted to be completely
3140 * transparent. This is only used to tell when the layer has no visible
3141 * non-transparent regions and can be removed from the layer list. It
3142 * does not affect the visibleRegion of this layer or any layers
3143 * beneath it. The hint may not be correct if apps don't respect the
3144 * SurfaceView restrictions (which, sadly, some don't).
3145 */
3146 Region transparentRegion;
3147
Mathias Agopianab028732010-03-16 16:41:46 -07003148
3149 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003150 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003151 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003152 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003155 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003156 if (!visibleRegion.isEmpty()) {
3157 // Remove the transparent area from the visible region
3158 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003159 if (tr.preserveRects()) {
3160 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003161 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003162 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003163 // transformation too complex, can't do the
3164 // transparent region optimization.
3165 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003166 }
Mathias Agopianab028732010-03-16 16:41:46 -07003167 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168
Mathias Agopianab028732010-03-16 16:41:46 -07003169 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003170 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003171 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003172 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003173 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003174 // the opaque region is the layer's footprint
3175 opaqueRegion = visibleRegion;
3176 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 }
3178 }
3179
Robert Carre5f4f692018-01-12 13:12:28 -08003180 if (visibleRegion.isEmpty()) {
3181 layer->clearVisibilityRegions();
3182 return;
3183 }
3184
Mathias Agopianab028732010-03-16 16:41:46 -07003185 // Clip the covered region to the visible region
3186 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3187
3188 // Update aboveCoveredLayers for next (lower) layer
3189 aboveCoveredLayers.orSelf(visibleRegion);
3190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 // subtract the opaque region covered by the layers above us
3192 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193
3194 // compute this layer's dirty region
3195 if (layer->contentDirty) {
3196 // we need to invalidate the whole region
3197 dirty = visibleRegion;
3198 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003199 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 layer->contentDirty = false;
3201 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003202 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003203 * the exposed region consists of two components:
3204 * 1) what's VISIBLE now and was COVERED before
3205 * 2) what's EXPOSED now less what was EXPOSED before
3206 *
3207 * note that (1) is conservative, we start with the whole
3208 * visible region but only keep what used to be covered by
3209 * something -- which mean it may have been exposed.
3210 *
3211 * (2) handles areas that were not covered by anything but got
3212 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003213 */
Mathias Agopianab028732010-03-16 16:41:46 -07003214 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003215 const Region oldVisibleRegion = layer->visibleRegion;
3216 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003217 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3218 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 }
3220 dirty.subtractSelf(aboveOpaqueLayers);
3221
3222 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003223 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224
Mathias Agopianab028732010-03-16 16:41:46 -07003225 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003227
Jesse Halla8026d22012-09-25 13:25:04 -07003228 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 layer->setVisibleRegion(visibleRegion);
3230 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003231 layer->setVisibleNonTransparentRegion(
3232 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003233 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234
Mathias Agopian87baae12012-07-31 12:38:26 -07003235 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236}
3237
Chia-I Wuab0c3192017-08-01 11:29:00 -07003238void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003239 for (const auto& [token, displayDevice] : mDisplays) {
3240 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003241 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003242 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003243 }
3244 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003245}
3246
Daniel Solomon42d04562019-01-20 21:03:19 -08003247void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3248 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3249 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3250 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3251 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3252 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3253 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3254 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3255 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3256 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3257 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3258 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3259 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3260}
3261
Dan Stoza6b9454d2014-11-07 16:00:59 -08003262bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003264 ALOGV("handlePageFlip");
3265
Brian Andersond6927fb2016-07-23 23:37:30 -07003266 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267
Mathias Agopian4fec8732012-06-29 14:12:52 -07003268 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003269 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003270 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003271
3272 // Store the set of layers that need updates. This set must not change as
3273 // buffers are being latched, as this could result in a deadlock.
3274 // Example: Two producers share the same command stream and:
3275 // 1.) Layer 0 is latched
3276 // 2.) Layer 0 gets a new frame
3277 // 2.) Layer 1 gets a new frame
3278 // 3.) Layer 1 is latched.
3279 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3280 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003281 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003282 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003283 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003284 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003285 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003286 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003287 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003288 } else {
3289 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003290 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003291 } else {
3292 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003293 }
Robert Carr2047fae2016-11-28 14:09:09 -08003294 });
3295
Lloyd Piquef2c79392018-12-20 16:23:33 -08003296 if (!mLayersWithQueuedFrames.empty()) {
3297 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3298 // writes to Layer current state. See also b/119481871
3299 Mutex::Autolock lock(mStateLock);
3300
3301 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003302 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003303 mLayersPendingRefresh.push_back(layer);
3304 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003305 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003306 if (layer->isBufferLatched()) {
3307 newDataLatched = true;
3308 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003309 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003310 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003311
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003312 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003313
3314 // If we will need to wake up at some time in the future to deal with a
3315 // queued frame that shouldn't be displayed during this vsync period, wake
3316 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003317 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003318 signalLayerUpdate();
3319 }
3320
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003321 // enter boot animation on first buffer latch
3322 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3323 ALOGI("Enter boot animation");
3324 mBootStage = BootStage::BOOTANIMATION;
3325 }
3326
Dan Stoza6b9454d2014-11-07 16:00:59 -08003327 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003328 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003329}
3330
Mathias Agopianad456f92011-01-13 17:53:01 -08003331void SurfaceFlinger::invalidateHwcGeometry()
3332{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003333 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003334}
3335
Lloyd Pique32cbe282018-10-19 13:09:22 -07003336void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003337 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003338 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003339 // We only need to actually compose the display if:
3340 // 1) It is being handled by hardware composer, which may need this to
3341 // keep its virtual display state machine in sync, or
3342 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003343 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003344 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003345 return;
3346 }
3347
Dan Stoza9e56aa02015-11-02 13:00:03 -08003348 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003349 base::unique_fd readyFence;
3350 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003351
3352 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003353 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354}
3355
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003356bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3357 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003358 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003359 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003360
Lloyd Pique32cbe282018-10-19 13:09:22 -07003361 auto display = displayDevice->getCompositionDisplay();
3362 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003363 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003364
3365 const Region bounds(displayState.bounds);
3366 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003367 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003368 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003369
Peiyong Lind3788632018-09-18 16:01:31 -07003370 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003371 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003372
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 renderengine::DisplaySettings clientCompositionDisplay;
3374 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3375 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003376 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003377
Dan Stoza9e56aa02015-11-02 13:00:03 -08003378 if (hasClientComposition) {
3379 ALOGV("hasClientComposition");
3380
Alec Mouri6338c9d2019-02-07 16:57:51 -08003381 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003382 if (buf == nullptr) {
3383 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3384 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003385 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003386 return false;
3387 }
3388
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003389 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3390 clientCompositionDisplay.clip = displayState.scissor;
3391 const ui::Transform& displayTransform = displayState.transform;
3392 mat4 m;
3393 m[0][0] = displayTransform[0][0];
3394 m[0][1] = displayTransform[0][1];
3395 m[0][3] = displayTransform[0][2];
3396 m[1][0] = displayTransform[1][0];
3397 m[1][1] = displayTransform[1][1];
3398 m[1][3] = displayTransform[1][2];
3399 m[3][0] = displayTransform[2][0];
3400 m[3][1] = displayTransform[2][1];
3401 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003402 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003403
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003404 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003405 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003406 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003407 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003408 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003409 clientCompositionDisplay.outputDataspace = outputDataspace;
3410 clientCompositionDisplay.maxLuminance =
3411 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003412
Lloyd Pique441d5042018-10-18 16:49:51 -07003413 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003414 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003415 getHwComposer()
3416 .hasDisplayCapability(displayId,
3417 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003418
Peiyong Lind3788632018-09-18 16:01:31 -07003419 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003420 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3421 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003422 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003423 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003424 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003425
Mathias Agopian85d751c2012-08-29 16:59:24 -07003426 /*
3427 * and then, render the layers targeted at the framebuffer
3428 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003429
Dan Stoza9e56aa02015-11-02 13:00:03 -08003430 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003431 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003432 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003433 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003434 const Region viewportRegion(displayState.viewport);
3435 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003436 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003437 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003438 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003439 switch (layer->getCompositionType(displayDevice)) {
3440 case Hwc2::IComposerClient::Composition::CURSOR:
3441 case Hwc2::IComposerClient::Composition::DEVICE:
3442 case Hwc2::IComposerClient::Composition::SIDEBAND:
3443 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003444 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003445 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003446 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003447 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003448 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 // never clear the very first layer since we're
3450 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003451 renderengine::LayerSettings layerSettings;
3452 Region dummyRegion;
3453 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3454 layerSettings);
3455
3456 if (prepared) {
3457 layerSettings.source.buffer.buffer = nullptr;
3458 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3459 layerSettings.alpha = half(0.0);
3460 layerSettings.disableBlending = true;
3461 clientCompositionLayers.push_back(layerSettings);
3462 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003463 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003464 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003465 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003466 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003467 renderengine::LayerSettings layerSettings;
3468 bool prepared =
3469 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3470 if (prepared) {
3471 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003472 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003473 break;
3474 }
3475 default:
3476 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003477 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003478 } else {
3479 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003480 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003481 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003482 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003483
Alec Mouri820c7402019-01-23 13:02:39 -08003484 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003485 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003486 clientCompositionDisplay.clearRegion = clearRegion;
3487 if (!debugRegion.isEmpty()) {
3488 Region::const_iterator it = debugRegion.begin();
3489 Region::const_iterator end = debugRegion.end();
3490 while (it != end) {
3491 const Rect& rect = *it++;
3492 renderengine::LayerSettings layerSettings;
3493 layerSettings.source.buffer.buffer = nullptr;
3494 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3495 layerSettings.geometry.boundaries = rect.toFloatRect();
3496 layerSettings.alpha = half(1.0);
3497 clientCompositionLayers.push_back(layerSettings);
3498 }
3499 }
3500 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mouri6338c9d2019-02-07 16:57:51 -08003501 buf->getNativeBuffer(), std::move(fd), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003502 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003503 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504}
3505
Chia-I Wu28e3a252018-09-07 12:05:02 -07003506void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003507 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003508 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509}
3510
Dan Stoza7d89d062015-04-30 13:29:25 -07003511status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003512 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003513 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003514 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003515 const sp<Layer>& parent,
3516 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003517{
Dan Stoza7d89d062015-04-30 13:29:25 -07003518 // add this layer to the current state list
3519 {
3520 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003521 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003522 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3523 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003524 return NO_MEMORY;
3525 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003526 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003527 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003528 } else if (parent == nullptr) {
3529 lbc->onRemovedFromCurrentState();
3530 } else if (parent->isRemovedFromCurrentState()) {
3531 parent->addChild(lbc);
3532 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003533 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003534 parent->addChild(lbc);
3535 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003536
Yiwei Zhang243b3782018-05-15 17:40:04 -07003537 if (gbc != nullptr) {
3538 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3539 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3540 mMaxGraphicBufferProducerListSize,
3541 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3542 mGraphicBufferProducerList.size(),
3543 mMaxGraphicBufferProducerListSize, mNumLayers);
3544 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003545 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003546 }
3547
Mathias Agopian96f08192010-06-02 23:28:45 -07003548 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003549 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003550
Dan Stoza7d89d062015-04-30 13:29:25 -07003551 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003552}
3553
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003554uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003555 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003556}
3557
Mathias Agopian3f844832013-08-07 21:24:32 -07003558uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003559 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560}
3561
Mathias Agopian3f844832013-08-07 21:24:32 -07003562uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003563 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003564}
3565
3566uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003567 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003568 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003569 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003571 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 }
3573 return old;
3574}
3575
Marissa Wall713b63f2018-10-17 15:42:43 -07003576bool SurfaceFlinger::flushTransactionQueues() {
3577 Mutex::Autolock _l(mStateLock);
3578 auto it = mTransactionQueues.begin();
3579 while (it != mTransactionQueues.end()) {
3580 auto& [applyToken, transactionQueue] = *it;
3581
3582 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003583 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3584 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003585 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003586 break;
3587 }
Robert Carr14167e02019-02-13 13:50:55 -08003588 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003589 transactionQueue.pop();
3590 }
3591
3592 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3593 }
3594 return mTransactionQueues.empty();
3595}
3596
chaviwca27f252018-02-06 16:46:39 -08003597bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3598 for (const ComposerState& state : states) {
3599 // Here we need to check that the interface we're given is indeed
3600 // one of our own. A malicious client could give us a nullptr
3601 // IInterface, or one of its own or even one of our own but a
3602 // different type. All these situations would cause us to crash.
3603 if (state.client == nullptr) {
3604 return true;
3605 }
3606
3607 sp<IBinder> binder = IInterface::asBinder(state.client);
3608 if (binder == nullptr) {
3609 return true;
3610 }
3611
3612 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3613 return true;
3614 }
3615 }
3616 return false;
3617}
3618
Marissa Wall17b4e452018-12-26 16:32:34 -08003619bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3620 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003621 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003622 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3623 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3624 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3625 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3626 return false;
3627 }
3628
Marissa Wall713b63f2018-10-17 15:42:43 -07003629 for (const ComposerState& state : states) {
3630 const layer_state_t& s = state.state;
3631 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3632 continue;
3633 }
3634 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003635 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003636 }
3637 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003638 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003639}
3640
3641void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3642 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003643 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003644 const InputWindowCommands& inputWindowCommands,
3645 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003646 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003647
3648 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3649
Mathias Agopian698c0872011-06-28 19:09:31 -07003650 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003651
chaviwca27f252018-02-06 16:46:39 -08003652 if (containsAnyInvalidClientState(states)) {
3653 return;
3654 }
3655
Marissa Wall713b63f2018-10-17 15:42:43 -07003656 // If its TransactionQueue already has a pending TransactionState or if it is pending
3657 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003658 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003659 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3660 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003661 setTransactionFlags(eTransactionNeeded);
3662 return;
3663 }
3664
Robert Carr14167e02019-02-13 13:50:55 -08003665 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003666}
3667
3668void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003669 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003670 const InputWindowCommands& inputWindowCommands,
3671 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003672 uint32_t transactionFlags = 0;
3673
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003674 if (flags & eAnimation) {
3675 // For window updates that are part of an animation we must wait for
3676 // previous animation "frames" to be handled.
3677 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003678 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 if (CC_UNLIKELY(err != NO_ERROR)) {
3680 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003681 // caller after a few seconds.
3682 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3683 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 mAnimTransactionPending = false;
3685 break;
3686 }
3687 }
3688 }
3689
chaviwca27f252018-02-06 16:46:39 -08003690 for (const DisplayState& display : displays) {
3691 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003692 }
3693
Marissa Walle2ffb422018-10-12 11:33:52 -07003694 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003695 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003696 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003697 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003698 // If the state doesn't require a traversal and there are callbacks, send them now
3699 if (!(clientStateFlags & eTraversalNeeded)) {
3700 mTransactionCompletedThread.sendCallbacks();
3701 }
3702 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003703
chaviw273171b2018-12-26 11:46:30 -08003704 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3705
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003706 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3707 // anyway. This can be used as a flush mechanism for previous async transactions.
3708 // Empty animation transaction can be used to simulate back-pressure, so also force a
3709 // transaction for empty animation transactions.
3710 if (transactionFlags == 0 &&
3711 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003712 transactionFlags = eTransactionNeeded;
3713 }
3714
Mathias Agopian386aa982011-11-07 21:58:03 -08003715 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003716 if (mInterceptor->isEnabled()) {
3717 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003718 }
Irvel468051e2016-06-13 16:44:44 -07003719
Mathias Agopian386aa982011-11-07 21:58:03 -08003720 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003721 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3722 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003723 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003724
3725 // if this is a synchronous transaction, wait for it to take effect
3726 // before returning.
3727 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003728 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003729 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003730 if (flags & eAnimation) {
3731 mAnimTransactionPending = true;
3732 }
chaviw95ef3c42019-02-14 10:55:09 -08003733
3734 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3735 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003736 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3737 if (CC_UNLIKELY(err != NO_ERROR)) {
3738 // just in case something goes wrong in SF, return to the
3739 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003740 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3741 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003742 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003743 break;
3744 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003745 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746 }
3747}
3748
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003749uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3750 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3751 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003752
Mathias Agopiane57f2922012-08-09 16:29:12 -07003753 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003754 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3755
3756 const uint32_t what = s.what;
3757 if (what & DisplayState::eSurfaceChanged) {
3758 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3759 state.surface = s.surface;
3760 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003761 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003762 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003763 if (what & DisplayState::eLayerStackChanged) {
3764 if (state.layerStack != s.layerStack) {
3765 state.layerStack = s.layerStack;
3766 flags |= eDisplayTransactionNeeded;
3767 }
3768 }
3769 if (what & DisplayState::eDisplayProjectionChanged) {
3770 if (state.orientation != s.orientation) {
3771 state.orientation = s.orientation;
3772 flags |= eDisplayTransactionNeeded;
3773 }
3774 if (state.frame != s.frame) {
3775 state.frame = s.frame;
3776 flags |= eDisplayTransactionNeeded;
3777 }
3778 if (state.viewport != s.viewport) {
3779 state.viewport = s.viewport;
3780 flags |= eDisplayTransactionNeeded;
3781 }
3782 }
3783 if (what & DisplayState::eDisplaySizeChanged) {
3784 if (state.width != s.width) {
3785 state.width = s.width;
3786 flags |= eDisplayTransactionNeeded;
3787 }
3788 if (state.height != s.height) {
3789 state.height = s.height;
3790 flags |= eDisplayTransactionNeeded;
3791 }
3792 }
3793
Mathias Agopiane57f2922012-08-09 16:29:12 -07003794 return flags;
3795}
3796
Robert Carr14167e02019-02-13 13:50:55 -08003797bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003798 IPCThreadState* ipc = IPCThreadState::self();
3799 const int pid = ipc->getCallingPid();
3800 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003801 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003802 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003803 return false;
3804 }
3805 return true;
3806}
3807
Robert Carr14167e02019-02-13 13:50:55 -08003808uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3809 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003810 const layer_state_t& s = composerState.state;
3811 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3812
Mathias Agopian13127d82013-03-05 17:47:11 -08003813 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003814 if (layer == nullptr) {
3815 return 0;
3816 }
3817
chaviw8b3871a2017-11-01 17:41:01 -07003818 uint32_t flags = 0;
3819
Garfield Tan8a3083e2018-12-03 13:21:07 -08003820 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003821 bool geometryAppliesWithResize =
3822 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003823
3824 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3825 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003826 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003827 layer->pushPendingState();
3828 }
3829
chaviw8b3871a2017-11-01 17:41:01 -07003830 if (what & layer_state_t::ePositionChanged) {
3831 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3832 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003833 }
chaviw8b3871a2017-11-01 17:41:01 -07003834 }
3835 if (what & layer_state_t::eLayerChanged) {
3836 // NOTE: index needs to be calculated before we update the state
3837 const auto& p = layer->getParent();
3838 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003839 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003840 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003841 mCurrentState.layersSortedByZ.removeAt(idx);
3842 mCurrentState.layersSortedByZ.add(layer);
3843 // we need traversal (state changed)
3844 // AND transaction (list changed)
3845 flags |= eTransactionNeeded|eTraversalNeeded;
3846 }
chaviw8b3871a2017-11-01 17:41:01 -07003847 } else {
3848 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003849 flags |= eTransactionNeeded|eTraversalNeeded;
3850 }
3851 }
chaviw8b3871a2017-11-01 17:41:01 -07003852 }
3853 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003854 // NOTE: index needs to be calculated before we update the state
3855 const auto& p = layer->getParent();
3856 if (p == nullptr) {
3857 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3858 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3859 mCurrentState.layersSortedByZ.removeAt(idx);
3860 mCurrentState.layersSortedByZ.add(layer);
3861 // we need traversal (state changed)
3862 // AND transaction (list changed)
3863 flags |= eTransactionNeeded|eTraversalNeeded;
3864 }
3865 } else {
3866 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3867 flags |= eTransactionNeeded|eTraversalNeeded;
3868 }
chaviw8b3871a2017-11-01 17:41:01 -07003869 }
3870 }
3871 if (what & layer_state_t::eSizeChanged) {
3872 if (layer->setSize(s.w, s.h)) {
3873 flags |= eTraversalNeeded;
3874 }
3875 }
3876 if (what & layer_state_t::eAlphaChanged) {
3877 if (layer->setAlpha(s.alpha))
3878 flags |= eTraversalNeeded;
3879 }
3880 if (what & layer_state_t::eColorChanged) {
3881 if (layer->setColor(s.color))
3882 flags |= eTraversalNeeded;
3883 }
Peiyong Lind3788632018-09-18 16:01:31 -07003884 if (what & layer_state_t::eColorTransformChanged) {
3885 if (layer->setColorTransform(s.colorTransform)) {
3886 flags |= eTraversalNeeded;
3887 }
3888 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003889 if (what & layer_state_t::eBackgroundColorChanged) {
3890 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3891 flags |= eTraversalNeeded;
3892 }
3893 }
chaviw8b3871a2017-11-01 17:41:01 -07003894 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003895 // TODO: b/109894387
3896 //
3897 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3898 // rotation. To see the problem observe that if we have a square parent, and a child
3899 // of the same size, then we rotate the child 45 degrees around it's center, the child
3900 // must now be cropped to a non rectangular 8 sided region.
3901 //
3902 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3903 // private API, and the WindowManager only uses rotation in one case, which is on a top
3904 // level layer in which cropping is not an issue.
3905 //
3906 // However given that abuse of rotation matrices could lead to surfaces extending outside
3907 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3908 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3909 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003910 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003911 flags |= eTraversalNeeded;
3912 }
3913 if (what & layer_state_t::eTransparentRegionChanged) {
3914 if (layer->setTransparentRegionHint(s.transparentRegion))
3915 flags |= eTraversalNeeded;
3916 }
3917 if (what & layer_state_t::eFlagsChanged) {
3918 if (layer->setFlags(s.flags, s.mask))
3919 flags |= eTraversalNeeded;
3920 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003921 if (what & layer_state_t::eCropChanged_legacy) {
3922 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003923 flags |= eTraversalNeeded;
3924 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003925 if (what & layer_state_t::eCornerRadiusChanged) {
3926 if (layer->setCornerRadius(s.cornerRadius))
3927 flags |= eTraversalNeeded;
3928 }
chaviw8b3871a2017-11-01 17:41:01 -07003929 if (what & layer_state_t::eLayerStackChanged) {
3930 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3931 // We only allow setting layer stacks for top level layers,
3932 // everything else inherits layer stack from its parent.
3933 if (layer->hasParent()) {
3934 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3935 layer->getName().string());
3936 } else if (idx < 0) {
3937 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3938 "that also does not appear in the top level layer list. Something"
3939 " has gone wrong.", layer->getName().string());
3940 } else if (layer->setLayerStack(s.layerStack)) {
3941 mCurrentState.layersSortedByZ.removeAt(idx);
3942 mCurrentState.layersSortedByZ.add(layer);
3943 // we need traversal (state changed)
3944 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003945 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003946 }
3947 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003948 if (what & layer_state_t::eDeferTransaction_legacy) {
3949 if (s.barrierHandle_legacy != nullptr) {
3950 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3951 } else if (s.barrierGbp_legacy != nullptr) {
3952 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003953 if (authenticateSurfaceTextureLocked(gbp)) {
3954 const auto& otherLayer =
3955 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003956 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003957 } else {
3958 ALOGE("Attempt to defer transaction to to an"
3959 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003960 }
3961 }
chaviw8b3871a2017-11-01 17:41:01 -07003962 // We don't trigger a traversal here because if no other state is
3963 // changed, we don't want this to cause any more work
3964 }
3965 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003966 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003967 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003968 if (!hadParent) {
3969 mCurrentState.layersSortedByZ.remove(layer);
3970 }
chaviw8b3871a2017-11-01 17:41:01 -07003971 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003972 }
chaviw8b3871a2017-11-01 17:41:01 -07003973 }
3974 if (what & layer_state_t::eReparentChildren) {
3975 if (layer->reparentChildren(s.reparentHandle)) {
3976 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003977 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003978 }
chaviw8b3871a2017-11-01 17:41:01 -07003979 if (what & layer_state_t::eDetachChildren) {
3980 layer->detachChildren();
3981 }
3982 if (what & layer_state_t::eOverrideScalingModeChanged) {
3983 layer->setOverrideScalingMode(s.overrideScalingMode);
3984 // We don't trigger a traversal here because if no other state is
3985 // changed, we don't want this to cause any more work
3986 }
Marissa Wall61c58622018-07-18 10:12:20 -07003987 if (what & layer_state_t::eTransformChanged) {
3988 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3989 }
3990 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3991 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3992 flags |= eTraversalNeeded;
3993 }
3994 if (what & layer_state_t::eCropChanged) {
3995 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3996 }
Marissa Wall861616d2018-10-22 12:52:23 -07003997 if (what & layer_state_t::eFrameChanged) {
3998 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3999 }
Marissa Wall61c58622018-07-18 10:12:20 -07004000 if (what & layer_state_t::eAcquireFenceChanged) {
4001 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4002 }
4003 if (what & layer_state_t::eDataspaceChanged) {
4004 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4005 }
4006 if (what & layer_state_t::eHdrMetadataChanged) {
4007 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4008 }
4009 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4010 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4011 }
4012 if (what & layer_state_t::eApiChanged) {
4013 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4014 }
4015 if (what & layer_state_t::eSidebandStreamChanged) {
4016 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4017 }
Robert Carr720e5062018-07-30 17:45:14 -07004018 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004019 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4020 layer->setInputInfo(s.inputInfo);
4021 flags |= eTraversalNeeded;
4022 } else {
4023 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4024 }
Robert Carr720e5062018-07-30 17:45:14 -07004025 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004026 if (what & layer_state_t::eMetadataChanged) {
4027 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4028 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004029 std::vector<sp<CallbackHandle>> callbackHandles;
4030 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4031 mTransactionCompletedThread.run();
4032 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4033 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4034 }
4035 }
Marissa Wall73411622019-01-25 10:45:41 -08004036
4037 if (what & layer_state_t::eBufferChanged) {
4038 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4039 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4040 s.buffer);
4041 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004042 if (what & layer_state_t::eCachedBufferChanged) {
4043 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004044 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4045 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004046 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4047 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004048 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4049 // Do not put anything that updates layer state or modifies flags after
4050 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004051 return flags;
4052}
4053
chaviw273171b2018-12-26 11:46:30 -08004054uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4055 uint32_t flags = 0;
4056 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4057 flags |= eTraversalNeeded;
4058 }
4059
chaviwa911b102019-02-14 10:18:33 -08004060 if (inputWindowCommands.syncInputWindows) {
4061 flags |= eTraversalNeeded;
4062 }
4063
Vishnu Nairec0ab382019-02-13 15:32:56 -08004064 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004065 return flags;
4066}
4067
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004068status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4069 uint32_t h, PixelFormat format, uint32_t flags,
4070 LayerMetadata metadata, sp<IBinder>* handle,
4071 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004072 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004073 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004074 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004075 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004076 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004077
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004078 status_t result = NO_ERROR;
4079
4080 sp<Layer> layer;
4081
Cody Northropbc755282017-03-31 12:00:08 -06004082 String8 uniqueName = getUniqueLayerName(name);
4083
Mathias Agopian3165cc22012-08-08 19:42:09 -07004084 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004085 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004086 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4087 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004090 case ISurfaceComposerClient::eFXSurfaceBufferState:
4091 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4092 break;
chaviw13fdc492017-06-27 12:40:18 -07004093 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004094 // check if buffer size is set for color layer.
4095 if (w > 0 || h > 0) {
4096 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4097 int(w), int(h));
4098 return BAD_VALUE;
4099 }
4100
chaviw13fdc492017-06-27 12:40:18 -07004101 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004102 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004103 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004104 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004105 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004106 // check if buffer size is set for container layer.
4107 if (w > 0 || h > 0) {
4108 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4109 int(w), int(h));
4110 return BAD_VALUE;
4111 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004112 result = createContainerLayer(client,
4113 uniqueName, w, h, flags,
4114 handle, &layer);
4115 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004116 default:
4117 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 break;
4119 }
4120
Dan Stoza7d89d062015-04-30 13:29:25 -07004121 if (result != NO_ERROR) {
4122 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004123 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004124
Chia-I Wuab0c3192017-08-01 11:29:00 -07004125 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4126 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004127 if (metadata.has(METADATA_WINDOW_TYPE)) {
4128 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4129 if (windowType == 441731) {
4130 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4131 layer->setPrimaryDisplayOnly();
4132 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004133 }
4134
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004135 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004136
Robert Carrb89ea9d2018-12-10 13:01:14 -08004137 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4138 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4139 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004140 if (result != NO_ERROR) {
4141 return result;
4142 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004143 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004144
4145 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004146 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147}
4148
Cody Northropbc755282017-03-31 12:00:08 -06004149String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4150{
4151 bool matchFound = true;
4152 uint32_t dupeCounter = 0;
4153
4154 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4155 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4156
Dan Stoza436ccf32018-06-21 12:10:12 -07004157 // Grab the state lock since we're accessing mCurrentState
4158 Mutex::Autolock lock(mStateLock);
4159
Cody Northropbc755282017-03-31 12:00:08 -06004160 // Loop over layers until we're sure there is no matching name
4161 while (matchFound) {
4162 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004163 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004164 if (layer->getName() == uniqueName) {
4165 matchFound = true;
4166 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4167 }
4168 });
4169 }
4170
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004171 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4172 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004173
4174 return uniqueName;
4175}
4176
Marissa Wallfd668622018-05-10 10:21:13 -07004177status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4178 uint32_t w, uint32_t h, uint32_t flags,
4179 PixelFormat& format, sp<IBinder>* handle,
4180 sp<IGraphicBufferProducer>* gbp,
4181 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004182 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004183 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 case PIXEL_FORMAT_TRANSPARENT:
4185 case PIXEL_FORMAT_TRANSLUCENT:
4186 format = PIXEL_FORMAT_RGBA_8888;
4187 break;
4188 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004189 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004190 break;
4191 }
4192
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004193 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004194 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004195 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004196 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004197 *handle = layer->getHandle();
4198 *gbp = layer->getProducer();
4199 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004200 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004201
Marissa Wallfd668622018-05-10 10:21:13 -07004202 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004204}
4205
Marissa Wall61c58622018-07-18 10:12:20 -07004206status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4207 uint32_t w, uint32_t h, uint32_t flags,
4208 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004209 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004210 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004211 *handle = layer->getHandle();
4212 *outLayer = layer;
4213
4214 return NO_ERROR;
4215}
4216
chaviw13fdc492017-06-27 12:40:18 -07004217status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004218 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004219 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004220{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004221 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004222 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004223 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004224}
4225
Robert Carr6b3f6c52018-08-13 13:05:17 -07004226status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4227 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4228 sp<IBinder>* handle, sp<Layer>* outLayer)
4229{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004230 *outLayer =
4231 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004232 *handle = (*outLayer)->getHandle();
4233 return NO_ERROR;
4234}
4235
4236
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004237void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004238 mLayersPendingRemoval.add(layer);
4239 mLayersRemoved = true;
4240 setTransactionFlags(eTransactionNeeded);
4241}
4242
Robert Carr695d5282018-12-18 15:27:58 -08004243void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004244{
Robert Carr2e102c92018-10-23 12:11:15 -07004245 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004246 // If a layer has a parent, we allow it to out-live it's handle
4247 // with the idea that the parent holds a reference and will eventually
4248 // be cleaned up. However no one cleans up the top-level so we do so
4249 // here.
4250 if (layer->getParent() == nullptr) {
4251 mCurrentState.layersSortedByZ.remove(layer);
4252 }
4253 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004254 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004255}
4256
Mathias Agopianb60314a2012-04-10 22:09:54 -07004257// ---------------------------------------------------------------------------
4258
Andy McFadden13a082e2012-08-24 10:16:42 -07004259void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004260 const auto display = getDefaultDisplayDeviceLocked();
4261 if (!display) return;
4262
4263 const sp<IBinder> token = display->getDisplayToken().promote();
4264 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004265
Jesse Hall01e29052013-02-19 16:13:35 -08004266 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004267 Vector<ComposerState> state;
4268 Vector<DisplayState> displays;
4269 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004270 d.what = DisplayState::eDisplayProjectionChanged |
4271 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004272 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004273 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004274 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004275 d.frame.makeInvalid();
4276 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004277 d.width = 0;
4278 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004279 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004280 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004281
Dominik Laskowskie9774092018-12-11 10:04:24 -08004282 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004283
Dominik Laskowski83b88212018-12-11 13:34:06 -08004284 const nsecs_t vsyncPeriod = getVsyncPeriod();
4285 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004286
Brian Andersond0010582017-03-07 13:20:31 -08004287 // Use phase of 0 since phase is not known.
4288 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004289 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004290 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004291}
4292
4293void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004294 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004295 postMessageAsync(
4296 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004297}
4298
Dominik Laskowskie9774092018-12-11 10:04:24 -08004299void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004300 if (display->isVirtual()) {
4301 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004302 return;
4303 }
4304
Dominik Laskowski075d3172018-05-24 15:50:06 -07004305 const auto displayId = display->getId();
4306 LOG_ALWAYS_FATAL_IF(!displayId);
4307
Dominik Laskowski34157762018-10-31 13:07:19 -07004308 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004309
4310 int currentMode = display->getPowerMode();
4311 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004312 return;
4313 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315 display->setPowerMode(mode);
4316
Lloyd Pique4dccc412018-01-22 17:21:36 -08004317 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004318 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004319 }
4320
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004321 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004322 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004323 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004324 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004325 mScheduler->onScreenAcquired(mAppConnectionHandle);
4326 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004327 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004328
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004329 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004330 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004331 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004332
4333 struct sched_param param = {0};
4334 param.sched_priority = 1;
4335 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4336 ALOGW("Couldn't set SCHED_FIFO on display on");
4337 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004338 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004339 // Turn off the display
4340 struct sched_param param = {0};
4341 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4342 ALOGW("Couldn't set SCHED_OTHER on display off");
4343 }
4344
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004345 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004346 mScheduler->disableHardwareVsync(true);
4347 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004348 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004349
Dominik Laskowski075d3172018-05-24 15:50:06 -07004350 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004351 mVisibleRegionsDirty = true;
4352 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004353 } else if (mode == HWC_POWER_MODE_DOZE ||
4354 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004355 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004356 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004358 mScheduler->onScreenAcquired(mAppConnectionHandle);
4359 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004360 }
4361 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4362 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004363 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004364 mScheduler->disableHardwareVsync(true);
4365 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004366 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004367 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004368 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004369 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004370 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004371 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004372
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004373 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004374 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004375 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004376 // Update refresh rate stats.
4377 mRefreshRateStats->setPowerMode(mode);
4378 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004379 }
4380
Dominik Laskowski34157762018-10-31 13:07:19 -07004381 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004382}
4383
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004384void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004385 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004386 const auto display = getDisplayDevice(displayToken);
4387 if (!display) {
4388 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4389 displayToken.get());
4390 } else if (display->isVirtual()) {
4391 ALOGW("Attempt to set power mode %d for virtual display", mode);
4392 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004393 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004394 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004395 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004396}
4397
4398// ---------------------------------------------------------------------------
4399
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4401 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004402 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004403
Mathias Agopianbd115332013-04-18 16:41:04 -07004404 IPCThreadState* ipc = IPCThreadState::self();
4405 const int pid = ipc->getCallingPid();
4406 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004407
Mathias Agopianbd115332013-04-18 16:41:04 -07004408 if ((uid != AID_SHELL) &&
4409 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004410 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4411 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004412 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004413 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004414 // (this would indicate SF is stuck, but we want to be able to
4415 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004416 status_t err = mStateLock.timedLock(s2ns(1));
4417 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004418 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result,
4420 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4421 "(no locks held)\n",
4422 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004423 }
4424
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004426
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427 static const std::unordered_map<std::string, Dumper> dumpers = {
4428 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4429 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4430 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004431 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004432 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004433 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004434 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4435 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004436 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4437 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4438 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4439 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4440 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4441 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004442 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004443 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4444 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004445
Dominik Laskowskic2867142019-01-21 11:33:38 -08004446 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004447
Dominik Laskowskic2867142019-01-21 11:33:38 -08004448 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4449 (it->second)(args, asProto, result);
4450 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004451 if (asProto) {
4452 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4453 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4454 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004455 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004456 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004457 }
4458
Mathias Agopian9795c422009-08-26 16:36:26 -07004459 if (locked) {
4460 mStateLock.unlock();
4461 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004462 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 return NO_ERROR;
4465}
4466
Dominik Laskowskic2867142019-01-21 11:33:38 -08004467void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 mCurrentState.traverseInZOrder(
4469 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004470}
4471
Dominik Laskowskic2867142019-01-21 11:33:38 -08004472void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004473 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004474
Dominik Laskowskic2867142019-01-21 11:33:38 -08004475 if (args.size() > 1) {
4476 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004477 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004478 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004479 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004480 }
Robert Carr2047fae2016-11-28 14:09:09 -08004481 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004482 } else {
4483 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484 }
4485}
4486
Dominik Laskowskic2867142019-01-21 11:33:38 -08004487void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004488 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004489 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004490 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004491 }
Robert Carr2047fae2016-11-28 14:09:09 -08004492 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004493
Svetoslavd85084b2014-03-20 10:28:31 -07004494 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004495}
4496
Dominik Laskowskic2867142019-01-21 11:33:38 -08004497void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4498 mTimeStats->parseArgs(asProto, args, result);
4499}
4500
Jamie Gennis6547ff42013-07-16 20:12:42 -07004501// This should only be called from the main thread. Otherwise it would need
4502// the lock and should use mCurrentState rather than mDrawingState.
4503void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004504 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004505 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004506 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004507
4508 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4509}
4510
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004512 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004513
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004514 if (isLayerTripleBufferingDisabled())
4515 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004516
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4518 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4519 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4520 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4521 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4522 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004523 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004524}
4525
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004526void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004527 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004528 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004529 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004530 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004531
Ana Krulecba13ab32019-02-20 14:14:12 -08004532 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4533 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4534 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004535 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004536}
4537
Yiwei Zhang5434a782018-12-05 18:06:32 -08004538void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4539 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004540 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4541 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004542 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004543 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004545 }
David Sodman4a36e932017-11-07 14:29:47 -08004546 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004547 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004548 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004549 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4550 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004551}
4552
Dan Stozae77c7662016-05-13 11:37:28 -07004553void SurfaceFlinger::recordBufferingStats(const char* layerName,
4554 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004555 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4556 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004557 for (const auto& segment : history) {
4558 if (!segment.usedThirdBuffer) {
4559 stats.twoBufferTime += segment.totalTime;
4560 }
4561 if (segment.occupancyAverage < 1.0f) {
4562 stats.doubleBufferedTime += segment.totalTime;
4563 } else if (segment.occupancyAverage < 2.0f) {
4564 stats.tripleBufferedTime += segment.totalTime;
4565 }
4566 ++stats.numSegments;
4567 stats.totalTime += segment.totalTime;
4568 }
4569}
4570
Yiwei Zhang5434a782018-12-05 18:06:32 -08004571void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4572 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004573
4574 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4575 const size_t count = currentLayers.size();
4576 for (size_t i=0 ; i<count ; i++) {
4577 currentLayers[i]->dumpFrameEvents(result);
4578 }
4579}
4580
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004582 result.append("Buffering stats:\n");
4583 result.append(" [Layer name] <Active time> <Two buffer> "
4584 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004585 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004586 typedef std::tuple<std::string, float, float, float> BufferTuple;
4587 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004588 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004589 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004590 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004591 if (stats.numSegments == 0) {
4592 continue;
4593 }
4594 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4595 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4596 stats.totalTime;
4597 float doubleBufferRatio = static_cast<float>(
4598 stats.doubleBufferedTime) / stats.totalTime;
4599 float tripleBufferRatio = static_cast<float>(
4600 stats.tripleBufferedTime) / stats.totalTime;
4601 sorted.insert({activeTime, {name, twoBufferRatio,
4602 doubleBufferRatio, tripleBufferRatio}});
4603 }
4604 for (const auto& sortedPair : sorted) {
4605 float activeTime = sortedPair.first;
4606 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4608 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004609 }
4610 result.append("\n");
4611}
4612
Yiwei Zhang5434a782018-12-05 18:06:32 -08004613void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004615 const auto displayId = display->getId();
4616 if (!displayId) {
4617 continue;
4618 }
4619 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004620 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004621 continue;
4622 }
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result,
4625 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4626 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004627 uint8_t port;
4628 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004629 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004630 result.append("no identification data\n");
4631 continue;
4632 }
4633
4634 if (!isEdid(data)) {
4635 result.append("unknown identification data: ");
4636 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004637 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004638 }
4639 result.append("\n");
4640 continue;
4641 }
4642
4643 const auto edid = parseEdid(data);
4644 if (!edid) {
4645 result.append("invalid EDID: ");
4646 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004648 }
4649 result.append("\n");
4650 continue;
4651 }
4652
Yiwei Zhang5434a782018-12-05 18:06:32 -08004653 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004654 result.append(edid->displayName.data(), edid->displayName.length());
4655 result.append("\"\n");
4656 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004657}
4658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4660 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4661 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4662 StringAppendF(&result, "DisplayColorSetting: %s\n",
4663 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004664
4665 // TODO: print out if wide-color mode is active or not
4666
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004667 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004668 const auto displayId = display->getId();
4669 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004670 continue;
4671 }
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004674 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004675 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004676 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004677 }
4678
Lloyd Pique32cbe282018-10-19 13:09:22 -07004679 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, " Current color mode: %s (%d)\n",
4681 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004682 }
4683 result.append("\n");
4684}
4685
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004686LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004687 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004688 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4689 const State& state = useDrawing ? mDrawingState : mCurrentState;
4690 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004691 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004692 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004693 });
4694
4695 return layersProto;
4696}
4697
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004698LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4699 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004700 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004701
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004702 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004703 resolution->set_w(displayDevice->getWidth());
4704 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004705
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004706 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004707 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004708
Lloyd Pique32cbe282018-10-19 13:09:22 -07004709 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4710 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4711 layersProto.set_global_transform(displayState.orientation);
4712
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004713 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004714 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004715 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004716 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004717 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004718 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004719 }
4720 });
4721
4722 return layersProto;
4723}
4724
Dominik Laskowskic2867142019-01-21 11:33:38 -08004725void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4726 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004727 Colorizer colorizer(colorize);
4728
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729 // figure out if we're stuck somewhere
4730 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4733
4734 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004735 * Dump library configuration.
4736 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004737
4738 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004739 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004740 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004741 appendSfConfigString(result);
4742 appendUiConfigString(result);
4743 appendGuiConfigString(result);
4744 result.append("\n");
4745
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004746 result.append("\nDisplay identification data:\n");
4747 dumpDisplayIdentificationData(result);
4748
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004749 result.append("\nWide-Color information:\n");
4750 dumpWideColorInfo(result);
4751
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004752 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004753 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004755 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004756 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004757
Andy McFadden41d67d72014-04-25 16:58:34 -07004758 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004759 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004760 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004761 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004762 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004763
Dan Stozab90cf072015-03-05 11:05:59 -08004764 dumpStaticScreenStats(result);
4765 result.append("\n");
4766
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004768
Dan Stozae77c7662016-05-13 11:37:28 -07004769 dumpBufferingStats(result);
4770
Andy McFadden4803b742012-09-24 19:07:20 -07004771 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004772 * Dump the visible layer list
4773 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4776 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4777 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004778 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004779
Chia-I Wu2f884132018-09-13 15:17:58 -07004780 {
4781 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4782 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004784 result.append("\n");
4785 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004786
4787 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004788 * Dump Display state
4789 */
4790
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004791 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004793 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004794 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004795 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004796 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004797 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004798
4799 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004800 * Dump SurfaceFlinger global state
4801 */
4802
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004804 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004805 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004806
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004807 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808
Dominik Laskowski075d3172018-05-24 15:50:06 -07004809 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004810 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4811 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004812 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4813 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004814 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815 StringAppendF(&result,
4816 " transaction-flags : %08x\n"
4817 " gpu_to_cpu_unsupported : %d\n",
4818 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004819
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004820 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004821 displayId && getHwComposer().isConnected(*displayId)) {
4822 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004823 StringAppendF(&result,
4824 " refresh-rate : %f fps\n"
4825 " x-dpi : %f\n"
4826 " y-dpi : %f\n",
4827 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4828 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004829 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832
Dan Stozae22aec72016-08-01 13:20:59 -07004833 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004834 * Tracing state
4835 */
4836 mTracing.dump(result);
4837 result.append("\n");
4838
4839 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004840 * HWC layer minidump
4841 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004842 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004843 const auto displayId = display->getId();
4844 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004845 continue;
4846 }
4847
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004849 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004850 const sp<DisplayDevice> displayDevice = display;
4851 mCurrentState.traverseInZOrder(
4852 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004853 result.append("\n");
4854 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004855
4856 /*
4857 * Dump HWComposer state
4858 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004859 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004860 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004861 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004862 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004864 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004865
4866 /*
4867 * Dump gralloc state
4868 */
4869 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4870 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004871
4872 /*
4873 * Dump VrFlinger state if in use.
4874 */
4875 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4876 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004878 result.append("\n");
4879 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004880
4881 /**
4882 * Scheduler dump state.
4883 */
Ana Krulecc2870422019-01-29 19:00:58 -08004884 result.append("\nScheduler state:\n");
4885 result.append(mScheduler->doDump() + "\n");
4886 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004887}
4888
Dominik Laskowski075d3172018-05-24 15:50:06 -07004889const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004890 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004891 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004892 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004893 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004894 }
4895 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004896
Dominik Laskowski34157762018-10-31 13:07:19 -07004897 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004898 static const Vector<sp<Layer>> empty;
4899 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004900}
4901
Chia-I Wu28f320b2018-05-03 11:02:56 -07004902void SurfaceFlinger::updateColorMatrixLocked() {
4903 mat4 colorMatrix;
4904 if (mGlobalSaturationFactor != 1.0f) {
4905 // Rec.709 luma coefficients
4906 float3 luminance{0.213f, 0.715f, 0.072f};
4907 luminance *= 1.0f - mGlobalSaturationFactor;
4908 mat4 saturationMatrix = mat4(
4909 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4910 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4911 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4912 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4913 );
4914 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4915 } else {
4916 colorMatrix = mClientColorMatrix * mDaltonizer();
4917 }
4918
4919 if (mCurrentState.colorMatrix != colorMatrix) {
4920 mCurrentState.colorMatrix = colorMatrix;
4921 mCurrentState.colorMatrixChanged = true;
4922 setTransactionFlags(eTransactionNeeded);
4923 }
4924}
4925
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004926status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927#pragma clang diagnostic push
4928#pragma clang diagnostic error "-Wswitch-enum"
4929 switch (static_cast<ISurfaceComposerTag>(code)) {
4930 // These methods should at minimum make sure that the client requested
4931 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004932 case BOOT_FINISHED:
4933 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934 case CREATE_DISPLAY:
4935 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004936 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 case GET_ACTIVE_COLOR_MODE:
4938 case GET_ANIMATION_FRAME_STATS:
4939 case GET_HDR_CAPABILITIES:
4940 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004941 case SET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004943 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004944 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004945 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004946 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4947 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004948 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4949 IPCThreadState* ipc = IPCThreadState::self();
4950 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4951 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004952 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 }
Robert Carr1db73f62016-12-21 12:58:51 -08004954 return OK;
4955 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004956 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004957 IPCThreadState* ipc = IPCThreadState::self();
4958 const int pid = ipc->getCallingPid();
4959 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4961 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004962 return PERMISSION_DENIED;
4963 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004964 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004965 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966 // Used by apps to hook Choreographer to SurfaceFlinger.
4967 case CREATE_DISPLAY_EVENT_CONNECTION:
4968 // The following calls are currently used by clients that do not
4969 // request necessary permissions. However, they do not expose any secret
4970 // information, so it is OK to pass them.
4971 case AUTHENTICATE_SURFACE:
4972 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004973 case GET_PHYSICAL_DISPLAY_IDS:
4974 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004975 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004976 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004977 case GET_DISPLAY_CONFIGS:
4978 case GET_DISPLAY_STATS:
4979 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4980 // Calling setTransactionState is safe, because you need to have been
4981 // granted a reference to Client* and Handle* to do anything with it.
4982 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004983 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004984 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004985 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004986 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004987 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004988 return OK;
4989 }
4990 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004991 case CAPTURE_SCREEN:
4992 case ADD_REGION_SAMPLING_LISTENER:
4993 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004995 IPCThreadState* ipc = IPCThreadState::self();
4996 const int pid = ipc->getCallingPid();
4997 const int uid = ipc->getCallingUid();
4998 if ((uid != AID_GRAPHICS) &&
4999 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5000 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5001 return PERMISSION_DENIED;
5002 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005003 return OK;
5004 }
5005 // The following codes are deprecated and should never be allowed to access SF.
5006 case CONNECT_DISPLAY_UNUSED:
5007 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5008 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5009 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005010 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005011 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005012
5013 // These codes are used for the IBinder protocol to either interrogate the recipient
5014 // side of the transaction for its canonical interface descriptor or to dump its state.
5015 // We let them pass by default.
5016 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5017 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5018 code == IBinder::SYSPROPS_TRANSACTION) {
5019 return OK;
5020 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005021 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005022 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005023 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005024 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5025 return OK;
5026 }
5027 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5028 return PERMISSION_DENIED;
5029#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005030}
5031
Ana Krulec13be8ad2018-08-21 02:43:56 +00005032status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5033 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005034 status_t credentialCheck = CheckTransactCodeCredentials(code);
5035 if (credentialCheck != OK) {
5036 return credentialCheck;
5037 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005038
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005039 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5040 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005041 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005042 IPCThreadState* ipc = IPCThreadState::self();
5043 const int uid = ipc->getCallingUid();
5044 if (CC_UNLIKELY(uid != AID_SYSTEM
5045 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005046 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005047 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005048 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005049 return PERMISSION_DENIED;
5050 }
5051 int n;
5052 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005053 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005054 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005055 return NO_ERROR;
5056 case 1002: // SHOW_UPDATES
5057 n = data.readInt32();
5058 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005059 invalidateHwcGeometry();
5060 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005061 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005062 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005063 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005064 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005066 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005067 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005068 setTransactionFlags(
5069 eTransactionNeeded|
5070 eDisplayTransactionNeeded|
5071 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005072 return NO_ERROR;
5073 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005074 case 1006:{ // send empty update
5075 signalRefresh();
5076 return NO_ERROR;
5077 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005078 case 1008: // toggle use of hw composer
5079 n = data.readInt32();
5080 mDebugDisableHWC = n ? 1 : 0;
5081 invalidateHwcGeometry();
5082 repaintEverything();
5083 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005084 case 1009: // toggle use of transform hint
5085 n = data.readInt32();
5086 mDebugDisableTransformHint = n ? 1 : 0;
5087 invalidateHwcGeometry();
5088 repaintEverything();
5089 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005090 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005091 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005092 reply->writeInt32(0);
5093 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005094 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005095 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005096 return NO_ERROR;
5097 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005098 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005099 if (!display) {
5100 return NAME_NOT_FOUND;
5101 }
5102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005103 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005104 return NO_ERROR;
5105 }
5106 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005107 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005108 // daltonize
5109 n = data.readInt32();
5110 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005111 case 1:
5112 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5113 break;
5114 case 2:
5115 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5116 break;
5117 case 3:
5118 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5119 break;
5120 default:
5121 mDaltonizer.setType(ColorBlindnessType::None);
5122 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005123 }
5124 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005125 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005126 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005127 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005128 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005129
5130 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005131 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005132 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005133 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005134 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005135 // apply a color matrix
5136 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005137 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005138 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005139 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005140 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005141 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005142 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005143 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005144 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005145 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005146 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005147
5148 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5149 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005150 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005151 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5152 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5153 }
5154
Chia-I Wu28f320b2018-05-03 11:02:56 -07005155 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005156 return NO_ERROR;
5157 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005158 // This is an experimental interface
5159 // Needs to be shifted to proper binder interface when we productize
5160 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005161 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005162 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005163 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005164 return NO_ERROR;
5165 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005166 case 1017: {
5167 n = data.readInt32();
5168 mForceFullDamage = static_cast<bool>(n);
5169 return NO_ERROR;
5170 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005171 case 1018: { // Modify Choreographer's phase offset
5172 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005173 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005174 return NO_ERROR;
5175 }
5176 case 1019: { // Modify SurfaceFlinger's phase offset
5177 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005178 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005179 return NO_ERROR;
5180 }
Irvel468051e2016-06-13 16:44:44 -07005181 case 1020: { // Layer updates interceptor
5182 n = data.readInt32();
5183 if (n) {
5184 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005185 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005186 }
5187 else{
5188 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005189 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005190 }
5191 return NO_ERROR;
5192 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005193 case 1021: { // Disable HWC virtual displays
5194 n = data.readInt32();
5195 mUseHwcVirtualDisplays = !n;
5196 return NO_ERROR;
5197 }
Romain Guy0147a172017-06-01 13:53:56 -07005198 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005199 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005200 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005201
Chia-I Wu28f320b2018-05-03 11:02:56 -07005202 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005203 return NO_ERROR;
5204 }
Romain Guy54f154a2017-10-24 21:40:32 +01005205 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005206 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005207 invalidateHwcGeometry();
5208 repaintEverything();
5209 return NO_ERROR;
5210 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005211 // Deprecate, use 1030 to check whether the device is color managed.
5212 case 1024: {
5213 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005214 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005215 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005216 n = data.readInt32();
5217 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005218 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005219 mTracing.enable();
5220 doTracing("tracing.enable");
5221 reply->writeInt32(NO_ERROR);
5222 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005223 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005224 status_t err = mTracing.disable();
5225 reply->writeInt32(err);
5226 }
5227 return NO_ERROR;
5228 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005229 case 1026: { // Get layer tracing status
5230 reply->writeBool(mTracing.isEnabled());
5231 return NO_ERROR;
5232 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005233 // Is a DisplayColorSetting supported?
5234 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005235 const auto display = getDefaultDisplayDevice();
5236 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005237 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005238 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005239
5240 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5241 switch (setting) {
5242 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005243 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005244 break;
5245 case DisplayColorSetting::UNMANAGED:
5246 reply->writeBool(true);
5247 break;
5248 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005249 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005250 break;
5251 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005252 reply->writeBool(
5253 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005254 break;
5255 }
5256 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005257 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005258 // Is VrFlinger active?
5259 case 1028: {
5260 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005261 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005262 return NO_ERROR;
5263 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005264 // Is device color managed?
5265 case 1030: {
5266 reply->writeBool(useColorManagement);
5267 return NO_ERROR;
5268 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005269 // Override default composition data space
5270 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5271 // && adb shell stop zygote && adb shell start zygote
5272 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5273 // adb shell stop zygote && adb shell start zygote
5274 case 1031: {
5275 Mutex::Autolock _l(mStateLock);
5276 n = data.readInt32();
5277 if (n) {
5278 n = data.readInt32();
5279 if (n) {
5280 Dataspace dataspace = static_cast<Dataspace>(n);
5281 if (!validateCompositionDataspace(dataspace)) {
5282 return BAD_VALUE;
5283 }
5284 mDefaultCompositionDataspace = dataspace;
5285 }
5286 n = data.readInt32();
5287 if (n) {
5288 Dataspace dataspace = static_cast<Dataspace>(n);
5289 if (!validateCompositionDataspace(dataspace)) {
5290 return BAD_VALUE;
5291 }
5292 mWideColorGamutCompositionDataspace = dataspace;
5293 }
5294 } else {
5295 // restore composition data space.
5296 mDefaultCompositionDataspace = defaultCompositionDataspace;
5297 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5298 }
5299 return NO_ERROR;
5300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005301 }
5302 }
5303 return err;
5304}
5305
Steven Thomas6d8110b2017-08-31 18:24:21 -07005306void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005307 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005308 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005309}
5310
Ana Krulec7d1d6832018-12-27 11:10:09 -08005311void SurfaceFlinger::repaintEverythingForHWC() {
5312 mRepaintEverything = true;
5313 mEventQueue->invalidateForHWC();
5314}
5315
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005316// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5317class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005318public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005319 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5320 ~WindowDisconnector() {
5321 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005322 }
5323
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005324private:
5325 ANativeWindow* mWindow;
5326 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005327};
5328
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005329status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005330 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5331 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005332 uint32_t reqWidth, uint32_t reqHeight,
5333 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005334 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005335 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005336
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005337 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005338
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005339 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5340
Chia-I Wu20261cb2018-08-23 12:55:44 -07005341 sp<DisplayDevice> display;
5342 {
5343 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005344
Chia-I Wu20261cb2018-08-23 12:55:44 -07005345 display = getDisplayDeviceLocked(displayToken);
5346 if (!display) return BAD_VALUE;
5347
Chia-I Wucb023152018-08-28 12:57:23 -07005348 // set the requested width/height to the logical display viewport size
5349 // by default
5350 if (reqWidth == 0 || reqHeight == 0) {
5351 reqWidth = uint32_t(display->getViewport().width());
5352 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005353 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005354 }
5355
Peiyong Lin0e003c92018-09-17 11:09:51 -07005356 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5357 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005358
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005359 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5360 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005361 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5362 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005363}
5364
5365status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005366 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5367 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005368 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005369 ATRACE_CALL();
5370
5371 class LayerRenderArea : public RenderArea {
5372 public:
Robert Carr578038f2018-03-09 12:25:24 -08005373 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005374 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5375 bool childrenOnly)
5376 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005377 mLayer(layer),
5378 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005379 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005380 mFlinger(flinger),
5381 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005382 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005383 Rect getBounds() const override {
5384 const Layer::State& layerState(mLayer->getDrawingState());
5385 return mLayer->getBufferSize(layerState);
5386 }
Marissa Wall61c58622018-07-18 10:12:20 -07005387 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005388 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005389 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005390 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005391 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005392 }
chaviwa76b2712017-09-20 12:02:26 -07005393 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005394 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005395 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005396 Rect getSourceCrop() const override {
5397 if (mCrop.isEmpty()) {
5398 return getBounds();
5399 } else {
5400 return mCrop;
5401 }
5402 }
Robert Carr578038f2018-03-09 12:25:24 -08005403 class ReparentForDrawing {
5404 public:
5405 const sp<Layer>& oldParent;
5406 const sp<Layer>& newParent;
5407
Vishnu Nair4351ad52019-02-11 14:13:02 -08005408 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5409 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005410 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005411 // Compute and cache the bounds for the new parent layer.
5412 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005413 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005414 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005415 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005416 };
5417
5418 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005419 const Rect sourceCrop = getSourceCrop();
5420 // no need to check rotation because there is none
5421 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5422 sourceCrop.height() != getReqHeight();
5423
Robert Carr578038f2018-03-09 12:25:24 -08005424 if (!mChildrenOnly) {
5425 mTransform = mLayer->getTransform().inverse();
5426 drawLayers();
5427 } else {
5428 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005429 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005430 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5431 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005432
Vishnu Nair4351ad52019-02-11 14:13:02 -08005433 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005434 drawLayers();
5435 }
5436 }
chaviwa76b2712017-09-20 12:02:26 -07005437
chaviwa76b2712017-09-20 12:02:26 -07005438 private:
chaviw7206d492017-11-10 16:16:12 -08005439 const sp<Layer> mLayer;
5440 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005441
5442 // In the "childrenOnly" case we reparent the children to a screenshot
5443 // layer which has no properties set and which does not draw.
5444 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005445 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005446 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005447
5448 SurfaceFlinger* mFlinger;
5449 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005450 };
5451
5452 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5453 auto parent = layerHandle->owner.promote();
5454
Robert Carr2e102c92018-10-23 12:11:15 -07005455 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005456 ALOGE("captureLayers called with a removed parent");
5457 return NAME_NOT_FOUND;
5458 }
5459
Robert Carr578038f2018-03-09 12:25:24 -08005460 const int uid = IPCThreadState::self()->getCallingUid();
5461 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005462 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005463 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5464 return PERMISSION_DENIED;
5465 }
5466
chaviw7206d492017-11-10 16:16:12 -08005467 Rect crop(sourceCrop);
5468 if (sourceCrop.width() <= 0) {
5469 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005470 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005471 }
5472
5473 if (sourceCrop.height() <= 0) {
5474 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005475 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005476 }
5477
5478 int32_t reqWidth = crop.width() * frameScale;
5479 int32_t reqHeight = crop.height() * frameScale;
5480
Chia-I Wu20261cb2018-08-23 12:55:44 -07005481 // really small crop or frameScale
5482 if (reqWidth <= 0) {
5483 reqWidth = 1;
5484 }
5485 if (reqHeight <= 0) {
5486 reqHeight = 1;
5487 }
5488
Peiyong Lin0e003c92018-09-17 11:09:51 -07005489 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005490
Robert Carr578038f2018-03-09 12:25:24 -08005491 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005492 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5493 if (!layer->isVisible()) {
5494 return;
Robert Carr578038f2018-03-09 12:25:24 -08005495 } else if (childrenOnly && layer == parent.get()) {
5496 return;
chaviwa76b2712017-09-20 12:02:26 -07005497 }
5498 visitor(layer);
5499 });
5500 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005501 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005502}
5503
5504status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5505 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005506 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005507 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005508 bool useIdentityTransform) {
5509 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005510
Peiyong Lin0e003c92018-09-17 11:09:51 -07005511 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005512 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5513 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005514 *outBuffer =
5515 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5516 static_cast<android_pixel_format>(reqPixelFormat), 1,
5517 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005518
Dan Stozaec460082018-12-17 15:35:09 -08005519 return captureScreenCore(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
5520}
5521
5522status_t SurfaceFlinger::captureScreenCore(RenderArea& renderArea,
5523 TraverseLayersFunction traverseLayers,
5524 const sp<GraphicBuffer>& buffer,
5525 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526 // This mutex protects syncFd and captureResult for communication of the return values from the
5527 // main thread back to this Binder thread
5528 std::mutex captureMutex;
5529 std::condition_variable captureCondition;
5530 std::unique_lock<std::mutex> captureLock(captureMutex);
5531 int syncFd = -1;
5532 std::optional<status_t> captureResult;
5533
Robert Carr03480e22018-01-04 16:02:06 -08005534 const int uid = IPCThreadState::self()->getCallingUid();
5535 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5536
Dominik Laskowski8c001672018-05-30 16:52:06 -07005537 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005538 // If there is a refresh pending, bug out early and tell the binder thread to try again
5539 // after the refresh.
5540 if (mRefreshPending) {
5541 ATRACE_NAME("Skipping screenshot for now");
5542 std::unique_lock<std::mutex> captureLock(captureMutex);
5543 captureResult = std::make_optional<status_t>(EAGAIN);
5544 captureCondition.notify_one();
5545 return;
5546 }
5547
5548 status_t result = NO_ERROR;
5549 int fd = -1;
5550 {
5551 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005552 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005553 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005554 useIdentityTransform, forSystem, &fd);
5555 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005556 }
5557
5558 {
5559 std::unique_lock<std::mutex> captureLock(captureMutex);
5560 syncFd = fd;
5561 captureResult = std::make_optional<status_t>(result);
5562 captureCondition.notify_one();
5563 }
5564 });
5565
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005566 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005567 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005568 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005569 while (*captureResult == EAGAIN) {
5570 captureResult.reset();
5571 result = postMessageAsync(message);
5572 if (result != NO_ERROR) {
5573 return result;
5574 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005575 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005576 }
5577 result = *captureResult;
5578 }
5579
5580 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005581 sync_wait(syncFd, -1);
5582 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005583 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005584
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005585 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005586}
5587
chaviwa76b2712017-09-20 12:02:26 -07005588void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005589 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005590 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5591 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005592 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005593
chaviwa76b2712017-09-20 12:02:26 -07005594 const auto reqWidth = renderArea.getReqWidth();
5595 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005596 const auto sourceCrop = renderArea.getSourceCrop();
5597 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005598
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005599 renderengine::DisplaySettings clientCompositionDisplay;
5600 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005601
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005602 // assume that bounds are never offset, and that they are the same as the
5603 // buffer bounds.
5604 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5605 ui::Transform transform = renderArea.getTransform();
5606 mat4 m;
5607 m[0][0] = transform[0][0];
5608 m[0][1] = transform[0][1];
5609 m[0][3] = transform[0][2];
5610 m[1][0] = transform[1][0];
5611 m[1][1] = transform[1][1];
5612 m[1][3] = transform[1][2];
5613 m[3][0] = transform[2][0];
5614 m[3][1] = transform[2][1];
5615 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005616
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005617 clientCompositionDisplay.globalTransform = m;
5618 mat4 rotMatrix;
5619 // Displacement for repositioning the clipping rectangle after rotating it
5620 // with the rotation hint.
5621 int displacementX = 0;
5622 int displacementY = 0;
5623 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5624 switch (rotation) {
5625 case ui::Transform::ROT_90:
5626 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5627 displacementX = reqWidth;
5628 break;
5629 case ui::Transform::ROT_180:
5630 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5631 displacementX = reqWidth;
5632 displacementY = reqHeight;
5633 break;
5634 case ui::Transform::ROT_270:
5635 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5636 displacementY = reqHeight;
5637 break;
5638 default:
5639 break;
5640 }
5641 // We need to transform the clipping window into the right spot.
5642 // First, rotate the clipping rectangle by the rotation hint to get the
5643 // right orientation
5644 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5645 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5646 const vec4 rotClipTL = rotMatrix * clipTL;
5647 const vec4 rotClipBR = rotMatrix * clipBR;
5648 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5649 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5650 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5651 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5652
5653 // Now reposition the clipping rectangle with the displacement vector
5654 // computed above.
5655 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5656
5657 clientCompositionDisplay.clip =
5658 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5659 newClipRight + displacementX, newClipBottom + displacementY);
5660
5661 // We need to perform the same transformation in layer space, so propagate
5662 // it to the global transform.
5663 mat4 clipTransform = displacementMat * rotMatrix;
5664 clientCompositionDisplay.globalTransform *= clipTransform;
5665 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5666 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005667
chaviw50da5042018-04-09 13:49:37 -07005668 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005669
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005670 renderengine::LayerSettings fillLayer;
5671 fillLayer.source.buffer.buffer = nullptr;
5672 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5673 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5674 fillLayer.alpha = half(alpha);
5675 clientCompositionLayers.push_back(fillLayer);
5676
5677 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005678 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005679 renderengine::LayerSettings layerSettings;
5680 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5681 layerSettings);
5682 if (prepared) {
5683 clientCompositionLayers.push_back(layerSettings);
5684 }
chaviwa76b2712017-09-20 12:02:26 -07005685 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005686
5687 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005688 // Use an empty fence for the buffer fence, since we just created the buffer so
5689 // there is no need for synchronization with the GPU.
5690 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005691 base::unique_fd drawFence;
5692 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005693 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694
5695 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005696}
5697
chaviwa76b2712017-09-20 12:02:26 -07005698status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5699 TraverseLayersFunction traverseLayers,
5700 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005701 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005702 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005703 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005704 ATRACE_CALL();
5705
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005706 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005707
5708 traverseLayers([&](Layer* layer) {
5709 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5710 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005711
Robert Carr03480e22018-01-04 16:02:06 -08005712 // We allow the system server to take screenshots of secure layers for
5713 // use in situations like the Screen-rotation animation and place
5714 // the impetus on WindowManager to not persist them.
5715 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005716 ALOGW("FB is protected: PERMISSION_DENIED");
5717 return PERMISSION_DENIED;
5718 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005719 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005720 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005721}
5722
chaviw95ef3c42019-02-14 10:55:09 -08005723void SurfaceFlinger::setInputWindowsFinished() {
5724 Mutex::Autolock _l(mStateLock);
5725
5726 mPendingSyncInputWindows = false;
5727 mTransactionCV.broadcast();
5728}
chaviw5f21a5e2019-02-14 10:00:34 -08005729
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005730// ---------------------------------------------------------------------------
5731
Dan Stoza412903f2017-04-27 13:42:17 -07005732void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5733 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005734}
5735
Dan Stoza412903f2017-04-27 13:42:17 -07005736void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5737 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005738}
5739
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005740void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005741 const LayerVector::Visitor& visitor) {
5742 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005743 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005744 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005745 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005746 continue;
5747 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005748 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005749 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005750 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005751 return;
5752 }
chaviwa76b2712017-09-20 12:02:26 -07005753 if (!layer->isVisible()) {
5754 return;
5755 }
5756 visitor(layer);
5757 });
5758 }
5759}
5760
Ady Abraham838de062019-02-04 10:24:03 -08005761void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5762 const android::sp<android::IBinder>& displayToken,
5763 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5764 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5765 if (!displayId) {
5766 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5767 return;
5768 }
5769
5770 ALOGV("Updating allowed configs");
5771 {
5772 std::lock_guard lock(mAllowedConfigsLock);
5773 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5774 }
5775
5776 // make sure that the current config is still allowed
5777 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5778 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
5779 // TODO(b/122906558): stop querying HWC for the available configs and instead use the cached
5780 // configs queried on boot
5781 auto configs = getHwComposer().getConfigs(*displayId);
5782
5783 for (int i = 0; i < configs.size(); i++) {
5784 if (isConfigAllowed(*displayId, i)) {
5785 // TODO: we switch to the first allowed config. In the future
5786 // we may want to enhance this logic to pick a similar config
5787 // to the current one
5788 ALOGV("Old config is not allowed - switching to config %d", i);
Ady Abraham447052e2019-02-13 16:07:27 -08005789 setDesiredActiveConfig(displayToken, i, ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005790 break;
5791 }
5792 }
5793 }
5794}
5795
5796status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5797 const std::vector<int32_t>& allowedConfigs) {
5798 ATRACE_CALL();
5799
5800 if (!displayToken) {
5801 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5802 return BAD_VALUE;
5803 }
5804
5805 if (!allowedConfigs.size()) {
5806 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5807 return BAD_VALUE;
5808 }
5809
5810 {
5811 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5812 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5813 if (!displayId) {
5814 ALOGE("setAllowedDisplayConfigs: display not found");
5815 return NAME_NOT_FOUND;
5816 }
5817 }
5818
5819 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5820 for (int config : allowedConfigs) {
5821 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5822 allowedDisplayConfigsBuilder.addConfig(config);
5823 }
5824 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5825 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5826 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5827 }));
5828 return NO_ERROR;
5829}
5830
chaviw291d88a2019-02-14 10:33:58 -08005831// ----------------------------------------------------------------------------
5832
5833void SetInputWindowsListener::onSetInputWindowsFinished() {
5834 mFlinger->setInputWindowsFinished();
5835}
5836
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005837}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005838
Lloyd Pique074e8122018-07-26 12:57:23 -07005839
Mathias Agopian3f844832013-08-07 21:24:32 -07005840#if defined(__gl_h_)
5841#error "don't include gl/gl.h in this file"
5842#endif
5843
5844#if defined(__gl2_h_)
5845#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005846#endif