blob: 8ac79177de64a6d9e1cf8def4a1ebb1f2202dca3 [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
Ady Abraham9360a222019-02-27 17:05:30 -0800971 // config twice. However event generation config might have changed so we need to update it
972 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham9360a222019-02-27 17:05:30 -0800974 const ConfigEvent desiredConfig = mDesiredActiveConfig.event | event;
975 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken, desiredConfig};
Ady Abrahamb838aed2019-02-12 15:30:16 -0800976
977 if (!mDesiredActiveConfigChanged) {
978 // This is the first time we set the desired
979 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
980
981 // This will trigger HWC refresh without resetting the idle timer.
982 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800984 mDesiredActiveConfigChanged = true;
985 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986}
987
988status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
989 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800990
991 std::vector<int32_t> allowedConfig;
992 allowedConfig.push_back(mode);
993
994 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995}
996
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997void SurfaceFlinger::setActiveConfigInternal() {
998 ATRACE_CALL();
999
1000 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -08001001 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002
1003 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1004 display->setActiveConfig(mUpcomingActiveConfig.configId);
1005
Ana Krulecc2870422019-01-29 19:00:58 -08001006 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Ady Abraham447052e2019-02-13 16:07:27 -08001008 if (mUpcomingActiveConfig.event != ConfigEvent::None) {
1009 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1010 mUpcomingActiveConfig.configId);
1011 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012}
1013
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001015 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 // we may be in the process of changing the active state
1017 if (mWaitForNextInvalidate) {
1018 mWaitForNextInvalidate = false;
1019
1020 repaintEverythingForHWC();
1021 // We do not want to give another frame to HWC while we are transitioning.
1022 return true;
1023 }
1024
1025 if (mCheckPendingFence) {
1026 if (mPreviousPresentFence != Fence::NO_FENCE &&
1027 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1028 // fence has not signaled yet. wait for the next invalidate
1029 repaintEverythingForHWC();
1030 return true;
1031 }
1032
1033 // We received the present fence from the HWC, so we assume it successfully updated
1034 // the config, hence we update SF.
1035 mCheckPendingFence = false;
1036 setActiveConfigInternal();
1037 }
1038
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 // Store the local variable to release the lock.
1040 ActiveConfigInfo desiredActiveConfig;
1041 {
1042 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 if (!mDesiredActiveConfigChanged) {
1044 return false;
1045 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001046 desiredActiveConfig = mDesiredActiveConfig;
1047 }
1048
1049 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1051 // display is not valid or we are already in the requested mode
1052 // on both cases there is nothing left to do
1053 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1054 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1055 mDesiredActiveConfigChanged = false;
1056 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1057 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001058 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001059
Ady Abraham838de062019-02-04 10:24:03 -08001060 // Desired active config was set, it is different than the config currently in use, however
1061 // allowed configs might have change by the time we process the refresh.
1062 // Make sure the desired config is still allowed
1063 if (!isConfigAllowed(*display->getId(), desiredActiveConfig.configId)) {
1064 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1065 mDesiredActiveConfig.configId = display->getActiveConfig();
1066 return false;
1067 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001068 mUpcomingActiveConfig = desiredActiveConfig;
1069 const auto displayId = display->getId();
1070 LOG_ALWAYS_FATAL_IF(!displayId);
1071
1072 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1073 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1074
1075 // we need to submit an empty frame to HWC to start the process
1076 mWaitForNextInvalidate = true;
1077 mCheckPendingFence = true;
1078
1079 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001080}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1083 Vector<ColorMode>* outColorModes) {
1084 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001089 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001090 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1091
1092 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1093 if (!displayId) {
1094 return NAME_NOT_FOUND;
1095 }
1096
Dominik Laskowski075d3172018-05-24 15:50:06 -07001097 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001098 }
Michael Wright28f24d02016-07-12 13:30:53 -07001099 outColorModes->clear();
1100 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1101
1102 return NO_ERROR;
1103}
1104
Daniel Solomon42d04562019-01-20 21:03:19 -08001105status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1106 ui::DisplayPrimaries &primaries) {
1107 if (!displayToken) {
1108 return BAD_VALUE;
1109 }
1110
1111 // Currently we only support this API for a single internal display.
1112 if (getInternalDisplayToken() != displayToken) {
1113 return BAD_VALUE;
1114 }
1115
1116 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1117 return NO_ERROR;
1118}
1119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1121 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001122 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001123 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001124 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001125}
1126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001128 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129 Vector<ColorMode> modes;
1130 getDisplayColorModes(displayToken, &modes);
1131 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1132 if (mode < ColorMode::NATIVE || !exists) {
1133 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1134 decodeColorMode(mode).c_str(), mode, displayToken.get());
1135 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001136 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 const auto display = getDisplayDevice(displayToken);
1138 if (!display) {
1139 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1140 decodeColorMode(mode).c_str(), mode, displayToken.get());
1141 } else if (display->isVirtual()) {
1142 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1143 decodeColorMode(mode).c_str(), mode);
1144 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001145 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1146 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 }
1148 }));
1149
Michael Wright28f24d02016-07-12 13:30:53 -07001150 return NO_ERROR;
1151}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001152
Svetoslavd85084b2014-03-20 10:28:31 -07001153status_t SurfaceFlinger::clearAnimationFrameStats() {
1154 Mutex::Autolock _l(mStateLock);
1155 mAnimFrameTracker.clearStats();
1156 return NO_ERROR;
1157}
1158
1159status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1160 Mutex::Autolock _l(mStateLock);
1161 mAnimFrameTracker.getStats(outStats);
1162 return NO_ERROR;
1163}
1164
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1166 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001167 Mutex::Autolock _l(mStateLock);
1168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169 const auto display = getDisplayDeviceLocked(displayToken);
1170 if (!display) {
1171 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001172 return BAD_VALUE;
1173 }
1174
Peiyong Linfb069302018-04-25 14:34:31 -07001175 // At this point the DisplayDeivce should already be set up,
1176 // meaning the luminance information is already queried from
1177 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001178 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001179 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1180 capabilities.getDesiredMaxLuminance(),
1181 capabilities.getDesiredMaxAverageLuminance(),
1182 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001183
1184 return NO_ERROR;
1185}
1186
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001187status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1188 ui::PixelFormat* outFormat,
1189 ui::Dataspace* outDataspace,
1190 uint8_t* outComponentMask) const {
1191 if (!outFormat || !outDataspace || !outComponentMask) {
1192 return BAD_VALUE;
1193 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001194 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001195 if (!display || !display->getId()) {
1196 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1197 return BAD_VALUE;
1198 }
1199 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1200 outDataspace, outComponentMask);
1201}
1202
Kevin DuBois74e53772018-11-19 10:52:38 -08001203status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1204 bool enable, uint8_t componentMask,
1205 uint64_t maxFrames) const {
1206 const auto display = getDisplayDevice(displayToken);
1207 if (!display || !display->getId()) {
1208 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1209 return BAD_VALUE;
1210 }
1211
1212 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1213 componentMask, maxFrames);
1214}
1215
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001216status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1217 uint64_t maxFrames, uint64_t timestamp,
1218 DisplayedFrameStats* outStats) const {
1219 const auto display = getDisplayDevice(displayToken);
1220 if (!display || !display->getId()) {
1221 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1222 return BAD_VALUE;
1223 }
1224
1225 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1226 outStats);
1227}
1228
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001229status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1230 if (!outSupported) {
1231 return BAD_VALUE;
1232 }
1233 *outSupported = getRenderEngine().supportsProtectedContent();
1234 return NO_ERROR;
1235}
1236
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001237status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1238 bool* outIsWideColorDisplay) const {
1239 if (!displayToken || !outIsWideColorDisplay) {
1240 return BAD_VALUE;
1241 }
1242 Mutex::Autolock _l(mStateLock);
1243 const auto display = getDisplayDeviceLocked(displayToken);
1244 if (!display) {
1245 return BAD_VALUE;
1246 }
1247 *outIsWideColorDisplay = display->hasWideColorGamut();
1248 return NO_ERROR;
1249}
1250
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001252 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 if (mInjectVSyncs == enable) {
1256 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258
Ana Krulecc2870422019-01-29 19:00:58 -08001259 auto resyncCallback =
1260 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001261
Ana Krulec98b5b242018-08-10 15:03:23 -07001262 // TODO(akrulec): Part of the Injector should be refactored, so that it
1263 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001264 if (enable) {
1265 ALOGV("VSync Injections enabled");
1266 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001267 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001268 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001269 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001270 impl::EventThread::InterceptVSyncsCallback(),
1271 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001273 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001274 } else {
1275 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001276 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1277 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001278 }
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001281 }));
1282
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001283 return NO_ERROR;
1284}
1285
1286status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001287 Mutex::Autolock _l(mStateLock);
1288
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001289 if (!mInjectVSyncs) {
1290 ALOGE("VSync Injections not enabled");
1291 return BAD_VALUE;
1292 }
1293 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1294 ALOGV("Injecting VSync inside SurfaceFlinger");
1295 mVSyncInjector->onInjectSyncEvent(when);
1296 }
1297 return NO_ERROR;
1298}
1299
Lloyd Pique755e3192018-01-31 16:46:15 -08001300status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1301 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001302 // Try to acquire a lock for 1s, fail gracefully
1303 const status_t err = mStateLock.timedLock(s2ns(1));
1304 const bool locked = (err == NO_ERROR);
1305 if (!locked) {
1306 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1307 return TIMED_OUT;
1308 }
1309
1310 outLayers->clear();
1311 mCurrentState.traverseInZOrder([&](Layer* layer) {
1312 outLayers->push_back(layer->getLayerDebugInfo());
1313 });
1314
1315 mStateLock.unlock();
1316 return NO_ERROR;
1317}
1318
Peiyong Linc6780972018-10-28 15:24:08 -07001319status_t SurfaceFlinger::getCompositionPreference(
1320 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1321 Dataspace* outWideColorGamutDataspace,
1322 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001323 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001324 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001325 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001326 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001327 return NO_ERROR;
1328}
1329
Dan Stozaec460082018-12-17 15:35:09 -08001330status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1331 const sp<IBinder>& stopLayerHandle,
1332 const sp<IRegionSamplingListener>& listener) {
1333 if (!listener) {
1334 return BAD_VALUE;
1335 }
1336 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001337 return NO_ERROR;
1338}
1339
Dan Stozaec460082018-12-17 15:35:09 -08001340status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1341 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001342 return NO_ERROR;
1343}
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001344// ----------------------------------------------------------------------------
1345
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001346sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1347 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001348 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001349 Mutex::Autolock lock(mStateLock);
1350 return getVsyncPeriod();
1351 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001352
Ana Krulecc2870422019-01-29 19:00:58 -08001353 const auto& handle =
1354 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001355
Ana Krulecc2870422019-01-29 19:00:58 -08001356 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001357}
1358
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001359// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001360
1361void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001362 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001363}
1364
1365void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001366 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367}
1368
1369void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001370 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001371}
1372
1373void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001374 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001375 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001376}
1377
1378status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001379 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001380 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381}
1382
1383status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001384 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001385 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001386 if (res == NO_ERROR) {
1387 msg->wait();
1388 }
1389 return res;
1390}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001391
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001392void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001393 do {
1394 waitForEvent();
1395 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001396}
1397
Dominik Laskowski83b88212018-12-11 13:34:06 -08001398nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001399 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001400 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1401 return 0;
1402 }
1403
1404 const auto config = getHwComposer().getActiveConfig(*displayId);
1405 return config ? config->getVsyncPeriod() : 0;
1406}
1407
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001408void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1409 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001410 ATRACE_NAME("SF onVsync");
1411
Steven Thomas3cfac282017-02-06 12:29:30 -08001412 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001414 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 return;
1416 }
1417
Dominik Laskowski075d3172018-05-24 15:50:06 -07001418 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001419 return;
1420 }
1421
Dominik Laskowski075d3172018-05-24 15:50:06 -07001422 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001423 // For now, we don't do anything with external display vsyncs.
1424 return;
1425 }
1426
Ana Krulecc2870422019-01-29 19:00:58 -08001427 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001428}
1429
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001430void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001431 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1432 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001433}
1434
Ady Abraham838de062019-02-04 10:24:03 -08001435bool SurfaceFlinger::isConfigAllowed(const DisplayId& displayId, int32_t config) {
1436 std::lock_guard lock(mAllowedConfigsLock);
1437
1438 // if allowed configs are not set yet for this display, every config is considered allowed
1439 if (mAllowedConfigs.find(displayId) == mAllowedConfigs.end()) {
1440 return true;
1441 }
1442
1443 return mAllowedConfigs[displayId]->isConfigAllowed(config);
1444}
1445
Ady Abraham447052e2019-02-13 16:07:27 -08001446void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, ConfigEvent event) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001447 mPhaseOffsets->setRefreshRateType(refreshRate);
1448
1449 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1450 mVsyncModulator.setPhaseOffsets(early, gl, late);
1451
1452 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001453 return;
1454 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001455
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1457 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1458 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1459 // refresh cycle.
1460
1461 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001462 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001463 if (currentVsyncPeriod == 0) {
1464 return;
1465 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001466
Ana Krulec7d1d6832018-12-27 11:10:09 -08001467 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1468 // floating numbers.
1469 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001470 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1471 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001472 if (std::abs(currentFps - newFps) <= 1) {
1473 return;
1474 }
1475
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001476 const auto displayId = getInternalDisplayIdLocked();
1477 LOG_ALWAYS_FATAL_IF(!displayId);
1478
1479 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001480 for (int i = 0; i < configs.size(); i++) {
Ady Abraham838de062019-02-04 10:24:03 -08001481 if (!isConfigAllowed(*displayId, i)) {
1482 ALOGV("Skipping config %d as it is not part of allowed configs", i);
1483 continue;
1484 }
1485
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1487 if (vsyncPeriod == 0) {
1488 continue;
1489 }
1490 const float fps = 1e9 / vsyncPeriod;
1491 // TODO(b/113612090): There should be a better way at determining which config
1492 // has the right refresh rate.
1493 if (std::abs(fps - newFps) <= 1) {
Ady Abraham447052e2019-02-13 16:07:27 -08001494 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i, event);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001495 }
1496 }
1497}
1498
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001500 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001501 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001502 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503
Lloyd Piqueba04e622017-12-14 17:11:26 -08001504 // Ignore events that do not have the right sequenceId.
1505 if (sequenceId != getBE().mComposerSequenceId) {
1506 return;
1507 }
1508
Steven Thomasb02664d2017-07-26 18:48:28 -07001509 // Only lock if we're not on the main thread. This function is normally
1510 // called on a hwbinder thread, but for the primary display it's called on
1511 // the main thread with the state lock already held, so don't attempt to
1512 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001513 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001514
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001515 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001516
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001517 if (std::this_thread::get_id() == mMainThreadId) {
1518 // Process all pending hot plug events immediately if we are on the main thread.
1519 processDisplayHotplugEventsLocked();
1520 }
1521
Lloyd Piqueba04e622017-12-14 17:11:26 -08001522 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001523}
1524
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001525void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001526 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001527 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001529 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001530 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001531}
1532
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001533void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001534 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001535 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001536 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001537 getHwComposer().setVsyncEnabled(*displayId,
1538 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1539 }
Mathias Agopian86303202012-07-24 22:46:10 -07001540}
1541
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001543void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001544 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545 // Clear the drawing state so that the logic inside of
1546 // handleTransactionLocked will fire. It will determine the delta between
1547 // mCurrentState and mDrawingState and re-apply all changes when we make the
1548 // transition.
1549 mDrawingState.displays.clear();
1550 mDisplays.clear();
1551}
1552
Steven Thomas050b2c82017-03-06 11:45:16 -08001553void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001554 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001555 if (!mVrFlinger)
1556 return;
1557 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001558 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001559 return;
1560 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561
Lloyd Pique441d5042018-10-18 16:49:51 -07001562 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 ALOGE("Vr flinger is only supported for remote hardware composer"
1564 " service connections. Ignoring request to transition to vr"
1565 " flinger.");
1566 mVrFlingerRequestsDisplay = false;
1567 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001568 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001569
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001571
Steven Thomas0123ac62018-07-12 11:32:34 -07001572 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001573 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001574
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001575 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001576
1577 // Clear out all the output layers from the composition engine for all
1578 // displays before destroying the hardware composer interface. This ensures
1579 // any HWC layers are destroyed through that interface before it becomes
1580 // invalid.
1581 for (const auto& [token, displayDevice] : mDisplays) {
1582 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1583 compositionengine::Output::OutputLayers());
1584 }
1585
Steven Thomas0123ac62018-07-12 11:32:34 -07001586 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1587 // called below. Clear the reference now so we don't accidentally use it
1588 // later.
1589 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001590
Steven Thomasb02664d2017-07-26 18:48:28 -07001591 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001593 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594
Steven Thomasb02664d2017-07-26 18:48:28 -07001595 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001596 // Delete the current instance before creating the new one
1597 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1598 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1599 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1600 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001601
Lloyd Pique441d5042018-10-18 16:49:51 -07001602 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001603 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001604
1605 if (vrFlingerRequestsDisplay) {
1606 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001607 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001608
1609 mVisibleRegionsDirty = true;
1610 invalidateHwcGeometry();
1611
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001612 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001613 display = getDefaultDisplayDeviceLocked();
1614 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001615 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001616
Steven Thomasb02664d2017-07-26 18:48:28 -07001617 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001618 const nsecs_t vsyncPeriod = getVsyncPeriod();
1619 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001620
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001621 // The present fences returned from vr_hwc are not an accurate
1622 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001623 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001624
Steven Thomasb02664d2017-07-26 18:48:28 -07001625 // Use phase of 0 since phase is not known.
1626 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001627 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001628 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001629
Ana Krulecc2870422019-01-29 19:00:58 -08001630 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001631
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001632 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001633 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001634}
1635
Mathias Agopian4fec8732012-06-29 14:12:52 -07001636void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001637 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001638 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001639 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001640 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001641 break;
1642 }
1643
Ana Krulecba13ab32019-02-20 14:14:12 -08001644 if (mUse90Hz && mUseSmart90ForVideo) {
1645 // This call is made each time SF wakes up and creates a new frame. It is part
1646 // of video detection feature.
1647 mScheduler->incrementFrameCounter();
1648 }
Alec Mourife3dc942019-02-12 14:19:18 -08001649 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001650 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001651 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001652 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001653 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1654 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001655 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001656 }
1657 // For now, only propagate backpressure when missing a hwc frame.
1658 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001659 if (mPropagateBackpressure) {
1660 signalLayerUpdate();
1661 break;
1662 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001663 }
Dan Stoza50182882016-07-08 12:02:20 -07001664
Steven Thomas050b2c82017-03-06 11:45:16 -08001665 // Now that we're going to make it to the handleMessageTransaction()
1666 // call below it's safe to call updateVrFlinger(), which will
1667 // potentially trigger a display handoff.
1668 updateVrFlinger();
1669
Dan Stoza6b9454d2014-11-07 16:00:59 -08001670 bool refreshNeeded = handleMessageTransaction();
1671 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001672
1673 updateCursorAsync();
1674 updateInputFlinger();
1675
Dan Stoza58784442014-12-02 16:58:17 -08001676 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001677 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001678 // Signal a refresh if a transaction modified the window state,
1679 // a new buffer was latched, or if HWC has requested a full
1680 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001681 signalRefresh();
1682 }
1683 break;
1684 }
1685 case MessageQueue::REFRESH: {
1686 handleMessageRefresh();
1687 break;
1688 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001689 }
1690}
1691
Dan Stoza6b9454d2014-11-07 16:00:59 -08001692bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001693 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001694 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001695
1696 // Apply any ready transactions in the queues if there are still transactions that have not been
1697 // applied, wake up during the next vsync period and check again
1698 bool transactionNeeded = false;
1699 if (!flushTransactionQueues()) {
1700 transactionNeeded = true;
1701 }
1702
Mathias Agopian4fec8732012-06-29 14:12:52 -07001703 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001704 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001705 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001706
1707 if (transactionNeeded) {
1708 setTransactionFlags(eTransactionNeeded);
1709 }
1710
1711 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712}
1713
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001716
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001717 mRefreshPending = false;
1718
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001719 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001720 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001721 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001722 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001723 for (const auto& [token, display] : mDisplays) {
1724 beginFrame(display);
1725 prepareFrame(display);
1726 doDebugFlashRegions(display, repaintEverything);
1727 doComposition(display, repaintEverything);
1728 }
1729
Adrian Roos1e1a1282017-11-01 19:05:31 +01001730 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001731 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001732
1733 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001734 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001735
Dan Stozabfbffeb2016-07-21 14:49:33 -07001736 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001737 for (const auto& [token, displayDevice] : mDisplays) {
1738 auto display = displayDevice->getCompositionDisplay();
1739 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001740 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001741 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001742 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001743
Jorim Jaggi90535212018-05-23 23:44:06 +02001744 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001745
David Sodman7e4ae112018-02-09 15:02:28 -08001746 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001747
1748 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001749}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001750
David Sodmanfa9b2af2017-12-24 13:28:59 -08001751
1752bool SurfaceFlinger::handleMessageInvalidate() {
1753 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001754 bool refreshNeeded = handlePageFlip();
1755
Vishnu Nair4351ad52019-02-11 14:13:02 -08001756 if (mVisibleRegionsDirty) {
1757 computeLayerBounds();
1758 }
1759
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001760 for (auto& layer : mLayersPendingRefresh) {
1761 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001762 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001763 invalidateLayerStack(layer, visibleReg);
1764 }
1765 mLayersPendingRefresh.clear();
1766 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001767}
1768
David Sodman79bba0e2018-08-05 18:07:49 -07001769void SurfaceFlinger::calculateWorkingSet() {
1770 ATRACE_CALL();
1771 ALOGV(__FUNCTION__);
1772
David Sodman79bba0e2018-08-05 18:07:49 -07001773 // build the h/w work list
1774 if (CC_UNLIKELY(mGeometryInvalid)) {
1775 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001776 for (const auto& [token, displayDevice] : mDisplays) {
1777 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001778 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001779 if (!displayId) {
1780 continue;
1781 }
David Sodman79bba0e2018-08-05 18:07:49 -07001782
Lloyd Pique32cbe282018-10-19 13:09:22 -07001783 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001784 for (size_t i = 0; i < currentLayers.size(); i++) {
1785 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001786
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001787 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001788 layer->forceClientComposition(displayDevice);
1789 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001790 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001791
Lloyd Pique32cbe282018-10-19 13:09:22 -07001792 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001793 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001794 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001795 }
David Sodman79bba0e2018-08-05 18:07:49 -07001796 }
1797 }
1798 }
1799
1800 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001801 for (const auto& [token, displayDevice] : mDisplays) {
1802 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001803 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001804 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001805 continue;
1806 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001807 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001808
1809 if (mDrawingState.colorMatrixChanged) {
1810 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001811 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001812 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001813 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001814 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001815 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1816 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001817 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001818 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001819 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1820 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001821 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001822 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001823 }
1824
Peiyong Lind3788632018-09-18 16:01:31 -07001825 // TODO(b/111562338) remove when composer 2.3 is shipped.
1826 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001827 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001828 }
1829
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001830 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001831 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001832 }
1833
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001834 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001835 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001836 layer->setCompositionType(displayDevice,
1837 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001838 continue;
1839 }
1840
Lloyd Pique32cbe282018-10-19 13:09:22 -07001841 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001842 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001844 }
1845
Peiyong Lin13effd12018-07-24 17:01:47 -07001846 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001847 ColorMode colorMode;
1848 Dataspace dataSpace;
1849 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001851 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001852 }
1853 }
1854
1855 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001856
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001857 for (const auto& [token, displayDevice] : mDisplays) {
1858 auto display = displayDevice->getCompositionDisplay();
1859 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001860 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001861 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1862 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1863 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001864 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001865 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001866 }
1867 }
David Sodman79bba0e2018-08-05 18:07:49 -07001868}
1869
Lloyd Pique32cbe282018-10-19 13:09:22 -07001870void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1871 bool repaintEverything) {
1872 auto display = displayDevice->getCompositionDisplay();
1873 const auto& displayState = display->getState();
1874
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875 // is debugging enabled
1876 if (CC_LIKELY(!mDebugRegion))
1877 return;
1878
Lloyd Pique32cbe282018-10-19 13:09:22 -07001879 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001880 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001881 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001882 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001883 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001884 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001885 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001887 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 }
1889 }
1890
Lloyd Pique32cbe282018-10-19 13:09:22 -07001891 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892
1893 if (mDebugRegion > 1) {
1894 usleep(mDebugRegion * 1000);
1895 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001896
Lloyd Pique32cbe282018-10-19 13:09:22 -07001897 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898}
1899
Adrian Roos1e1a1282017-11-01 19:05:31 +01001900void SurfaceFlinger::doTracing(const char* where) {
1901 ATRACE_CALL();
1902 ATRACE_NAME(where);
1903 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001904 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001905 }
1906}
1907
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001908void SurfaceFlinger::logLayerStats() {
1909 ATRACE_CALL();
1910 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001911 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001913 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001914 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001915 }
1916 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001917
1918 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001919 }
1920}
1921
David Sodman2b406362017-12-15 13:33:47 -08001922void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001923{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 ATRACE_CALL();
1925 ALOGV("preComposition");
1926
David Sodman2b406362017-12-15 13:33:47 -08001927 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1928
Mathias Agopiancd60f992012-08-16 16:28:27 -07001929 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001930 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001931 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932 needExtraInvalidate = true;
1933 }
Robert Carr2047fae2016-11-28 14:09:09 -08001934 });
1935
Mathias Agopiancd60f992012-08-16 16:28:27 -07001936 if (needExtraInvalidate) {
1937 signalLayerUpdate();
1938 }
1939}
1940
Ana Krulece588e312018-09-18 12:32:24 -07001941void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1942 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943 // Update queue of past composite+present times and determine the
1944 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001945 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001946 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001947 while (!getBE().mCompositePresentTimes.empty()) {
1948 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949 // Cached values should have been updated before calling this method,
1950 // which helps avoid duplicate syscalls.
1951 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1952 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1953 break;
1954 }
1955 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001956 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 }
1958
1959 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001960 while (getBE().mCompositePresentTimes.size() > 16) {
1961 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001962 }
1963
Ana Krulece588e312018-09-18 12:32:24 -07001964 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001965}
1966
Ana Krulece588e312018-09-18 12:32:24 -07001967void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1968 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001969 // Integer division and modulo round toward 0 not -inf, so we need to
1970 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001971 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1972 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1973 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974
Ana Krulec757f63a2019-01-25 10:46:18 -08001975 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001976 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001977 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001978 }
1979
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980 // Snap the latency to a value that removes scheduling jitter from the
1981 // composition and present times, which often have >1ms of jitter.
1982 // Reducing jitter is important if an app attempts to extrapolate
1983 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001984 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001986 nsecs_t bias = stats.vsyncPeriod / 2;
1987 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1988 nsecs_t snappedCompositeToPresentLatency =
1989 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990
David Sodman99974d22017-11-28 12:04:33 -08001991 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001992 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1993 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001994 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995}
1996
Ady Abraham8164d482019-01-11 14:47:59 -08001997// debug patch for b/119477596 - add stack guards to catch stack
1998// corruptions and disable clang optimizations.
1999// The code below is temporary and planned to be removed once stack
2000// corruptions are found.
2001#pragma clang optimize off
2002class StackGuard {
2003public:
2004 StackGuard(const char* name, const char* func, int line) {
2005 guarders.reserve(MIN_CAPACITY);
2006 guarders.push_back({this, name, func, line});
2007 validate();
2008 }
2009 ~StackGuard() {
2010 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2011 if (i->guard == this) {
2012 guarders.erase(i);
2013 break;
2014 }
2015 }
2016 }
2017
2018 static void validate() {
2019 for (const auto& guard : guarders) {
2020 if (guard.guard->cookie != COOKIE_VALUE) {
2021 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2022 CallStack stack(LOG_TAG);
2023 abort();
2024 }
2025 }
2026 }
2027
2028private:
2029 uint64_t cookie = COOKIE_VALUE;
2030 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2031 static constexpr size_t MIN_CAPACITY = 16;
2032
2033 struct GuarderElement {
2034 StackGuard* guard;
2035 const char* name;
2036 const char* func;
2037 int line;
2038 };
2039
2040 static std::vector<GuarderElement> guarders;
2041};
2042std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2043
2044#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2045
2046#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002047void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002048{
Ady Abraham8164d482019-01-11 14:47:59 -08002049 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 ATRACE_CALL();
2051 ALOGV("postComposition");
2052
Brian Anderson3546a3f2016-07-14 11:51:14 -07002053 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002054 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002055 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002056 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002057 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002058 }
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002060
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002061 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002062 const auto displayDevice = getDefaultDisplayDeviceLocked();
2063 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064
David Sodman73beded2017-11-15 11:56:06 -08002065 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002066 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2068
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002070 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002071 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2072 ->getRenderSurface()
2073 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002074 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002075 } else {
2076 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2077 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002078
Ady Abraham8164d482019-01-11 14:47:59 -08002079 ASSERT_ON_STACK_GUARD();
2080
David Sodman73beded2017-11-15 11:56:06 -08002081 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002082 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2083 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002084 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002085 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002086 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002087
Ana Krulece588e312018-09-18 12:32:24 -07002088 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002089 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002090 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002091
Ady Abraham8164d482019-01-11 14:47:59 -08002092 ASSERT_ON_STACK_GUARD();
2093
David Sodman2b406362017-12-15 13:33:47 -08002094 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002095 // when we started doing work for this frame, but that should be okay
2096 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002097 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002098 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002099 DEFINE_STACK_GUARD(compositorTiming);
2100
Brian Andersond0010582017-03-07 13:20:31 -08002101 {
David Sodman99974d22017-11-28 12:04:33 -08002102 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002103 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002104 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002105
2106 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002107 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002108
Robert Carr2047fae2016-11-28 14:09:09 -08002109 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002110 bool frameLatched =
2111 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2112 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002113 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002114 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002115 recordBufferingStats(layer->getName().string(),
2116 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002117 }
Ady Abraham8164d482019-01-11 14:47:59 -08002118 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002119 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002120
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002121 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002123 mScheduler->addPresentFence(presentFenceTime);
2124 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002125 }
2126
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002127 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002128 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2129 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002130 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002131 }
2132 }
2133
Ady Abraham8164d482019-01-11 14:47:59 -08002134 ASSERT_ON_STACK_GUARD();
2135
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002136 if (mAnimCompositionPending) {
2137 mAnimCompositionPending = false;
2138
Brian Anderson4e606e32017-03-16 15:34:57 -07002139 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002140 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002141 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002142
2143 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002144 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002145 // The HWC doesn't support present fences, so use the refresh
2146 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002147 const nsecs_t presentTime =
2148 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002149 DEFINE_STACK_GUARD(presentTime);
2150
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002151 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002152 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002153 }
2154 mAnimFrameTracker.advanceFrame();
2155 }
Dan Stozab90cf072015-03-05 11:05:59 -08002156
Ady Abraham8164d482019-01-11 14:47:59 -08002157 ASSERT_ON_STACK_GUARD();
2158
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002159 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002160 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002161 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002162 }
2163
Ady Abraham8164d482019-01-11 14:47:59 -08002164 ASSERT_ON_STACK_GUARD();
2165
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002166 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002167
Ady Abraham8164d482019-01-11 14:47:59 -08002168 ASSERT_ON_STACK_GUARD();
2169
Lloyd Pique32cbe282018-10-19 13:09:22 -07002170 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2171 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002172 return;
2173 }
2174
2175 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002176 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002177 if (mHasPoweredOff) {
2178 mHasPoweredOff = false;
2179 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002180 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002181 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002182 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002183 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002184 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2185 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002186 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002187 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002188 }
David Sodman4a36e932017-11-07 14:29:47 -08002189 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002190
2191 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002192 }
David Sodman4a36e932017-11-07 14:29:47 -08002193 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002194 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002195
2196 {
2197 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002198 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002199 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002200 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002201 if (refillCount > 0) {
2202 const size_t offset = mTexturePool.size();
2203 mTexturePool.resize(mTexturePoolSize);
2204 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2205 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2206 }
Ady Abraham8164d482019-01-11 14:47:59 -08002207 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002208 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002209
Marissa Wallfda30bb2018-10-12 11:34:28 -07002210 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002211 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002212
Dan Stozaec460082018-12-17 15:35:09 -08002213 if (mLumaSampling) {
2214 mRegionSamplingThread->sampleNow();
2215 }
2216
Ady Abraham8164d482019-01-11 14:47:59 -08002217 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218}
Ady Abraham8164d482019-01-11 14:47:59 -08002219#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002220
Vishnu Nair4351ad52019-02-11 14:13:02 -08002221void SurfaceFlinger::computeLayerBounds() {
2222 for (const auto& pair : mDisplays) {
2223 const auto& displayDevice = pair.second;
2224 const auto display = displayDevice->getCompositionDisplay();
2225 for (const auto& layer : mDrawingState.layersSortedByZ) {
2226 // only consider the layers on the given layer stack
2227 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002228 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002229 }
2230
2231 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2232 }
2233 }
2234}
2235
Mathias Agopiancd60f992012-08-16 16:28:27 -07002236void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 ATRACE_CALL();
2238 ALOGV("rebuildLayerStacks");
2239
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002240 // We need to clear these out now as these may be holding on to a
2241 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2242 // also holds a reference. When the set of visible layers is recomputed,
2243 // some layers may be destroyed if the only thing keeping them alive was
2244 // that list of visible layers associated with each display. The layer
2245 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2246 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2247 for (const auto& [token, display] : mDisplays) {
2248 getBE().mCompositionInfo[token].clear();
2249 }
2250
Mathias Agopiancd60f992012-08-16 16:28:27 -07002251 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002252 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002253 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002254 mVisibleRegionsDirty = false;
2255 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002256
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002257 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const auto& displayDevice = pair.second;
2259 auto display = displayDevice->getCompositionDisplay();
2260 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002261 Region opaqueRegion;
2262 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002263 compositionengine::Output::OutputLayers layersSortedByZ;
2264 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002265 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002266 const ui::Transform& tr = displayState.transform;
2267 const Rect bounds = displayState.bounds;
2268 if (displayState.isEnabled) {
2269 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270
Jeff Sharkey76488112017-02-27 14:15:18 -07002271 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002272 auto compositionLayer = layer->getCompositionLayer();
2273 if (compositionLayer == nullptr) {
2274 return;
2275 }
2276
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002278 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2279 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2280
Lloyd Pique07e33212018-12-18 16:33:37 -08002281 bool needsOutputLayer = false;
2282
Lloyd Piqueef36b002019-01-23 17:52:04 -08002283 if (display->belongsInOutput(layer->getLayerStack(),
2284 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002285 Region drawRegion(tr.transform(
2286 layer->visibleNonTransparentRegion));
2287 drawRegion.andSelf(bounds);
2288 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002289 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002290 }
Chia-I Wu83806892017-11-16 10:50:20 -08002291 }
2292
Lloyd Pique07e33212018-12-18 16:33:37 -08002293 if (needsOutputLayer) {
2294 layersSortedByZ.emplace_back(
2295 display->getOrCreateOutputLayer(displayId, compositionLayer,
2296 layerFE));
2297 deprecated_layersSortedByZ.add(layer);
2298
2299 auto& outputLayerState = layersSortedByZ.back()->editState();
2300 outputLayerState.visibleRegion =
2301 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2302 } else if (displayId) {
2303 // For layers that are being removed from a HWC display,
2304 // and that have queued frames, add them to a a list of
2305 // released layers so we can properly set a fence.
2306 bool hasExistingOutputLayer =
2307 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2308 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2309 mLayersWithQueuedFrames.cend(),
2310 layer) != mLayersWithQueuedFrames.cend();
2311
2312 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002313 layersNeedingFences.add(layer);
2314 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002315 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002316 });
2317 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002318
2319 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2320
2321 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002322 displayDevice->setLayersNeedingFences(layersNeedingFences);
2323
2324 Region undefinedRegion{bounds};
2325 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2326
2327 display->editState().undefinedRegion = undefinedRegion;
2328 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002329 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002330 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002331}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002332
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002333// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002335// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002336// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002337// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338// The returned HDR data space is one of
2339// - Dataspace::UNKNOWN
2340// - Dataspace::BT2020_HLG
2341// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2343 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002344 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002345 *outHdrDataSpace = Dataspace::UNKNOWN;
2346
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002348 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002349 case Dataspace::V0_SCRGB:
2350 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002351 case Dataspace::BT2020:
2352 case Dataspace::BT2020_ITU:
2353 case Dataspace::BT2020_LINEAR:
2354 case Dataspace::DISPLAY_BT2020:
2355 bestDataSpace = Dataspace::DISPLAY_BT2020;
2356 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002358 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002359 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002360 case Dataspace::BT2020_PQ:
2361 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002362 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002363 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002364 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002365 case Dataspace::BT2020_HLG:
2366 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002367 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002368 // When there's mixed PQ content and HLG content, we set the HDR
2369 // data space to be BT2020_PQ and convert HLG to PQ.
2370 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2371 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002372 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002373 break;
2374 default:
2375 break;
2376 }
Romain Guy54f154a2017-10-24 21:40:32 +01002377 }
2378
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002379 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002380}
2381
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002382// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2384 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002385 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2386 *outMode = ColorMode::NATIVE;
2387 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002388 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002389 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002390 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002391
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002392 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002393 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002394
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002395 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2396
Peiyong Lina3ea5592019-02-10 14:45:00 -08002397 switch (mForceColorMode) {
2398 case ColorMode::SRGB:
2399 bestDataSpace = Dataspace::V0_SRGB;
2400 break;
2401 case ColorMode::DISPLAY_P3:
2402 bestDataSpace = Dataspace::DISPLAY_P3;
2403 break;
2404 default:
2405 break;
2406 }
2407
Peiyong Lindfde5112018-06-05 10:58:41 -07002408 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002409 const bool isHdr =
2410 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002411 if (isHdr) {
2412 bestDataSpace = hdrDataSpace;
2413 }
2414
Chia-I Wu0d711262018-05-21 15:19:35 -07002415 RenderIntent intent;
2416 switch (mDisplayColorSetting) {
2417 case DisplayColorSetting::MANAGED:
2418 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002419 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002420 break;
2421 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002422 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002423 break;
2424 default: // vendor display color setting
2425 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2426 break;
2427 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002428
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002429 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002430}
2431
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2433 auto display = displayDevice->getCompositionDisplay();
2434 const auto& displayState = display->getState();
2435
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002436 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002437 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2438 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002439
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 // If nothing has changed (!dirty), don't recompose.
2441 // If something changed, but we don't currently have any visible layers,
2442 // and didn't when we last did a composition, then skip it this time.
2443 // The second rule does two things:
2444 // - When all layers are removed from a display, we'll emit one black
2445 // frame, then nothing more until we get new layers.
2446 // - When a display is created with a private layer stack, we won't
2447 // emit any black frames until a layer is added to the layer stack.
2448 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002449
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 const char flagPrefix[] = {'-', '+'};
2451 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2453 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2454 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2455 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002456
Lloyd Pique31cb2942018-10-19 17:23:03 -07002457 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002458
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002460 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002461 }
2462}
2463
Lloyd Pique32cbe282018-10-19 13:09:22 -07002464void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2465 auto display = displayDevice->getCompositionDisplay();
2466 const auto& displayState = display->getState();
2467
2468 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002469 return;
David Sodman2b406362017-12-15 13:33:47 -08002470 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002471
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002472 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002473 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002475}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002476
Lloyd Pique32cbe282018-10-19 13:09:22 -07002477void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002478 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 ALOGV("doComposition");
2480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 auto display = displayDevice->getCompositionDisplay();
2482 const auto& displayState = display->getState();
2483
2484 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002485 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002486 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002487
David Sodmanfa9b2af2017-12-24 13:28:59 -08002488 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002490
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002492 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002493 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002494 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002495}
2496
David Sodmanfa9b2af2017-12-24 13:28:59 -08002497void SurfaceFlinger::postFrame()
2498{
2499 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 const auto display = getDefaultDisplayDeviceLocked();
2501 if (display && getHwComposer().isConnected(*display->getId())) {
2502 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002503 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2504 logFrameStats();
2505 }
2506 }
2507}
2508
Lloyd Pique32cbe282018-10-19 13:09:22 -07002509void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002510 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002511 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002512
Lloyd Pique32cbe282018-10-19 13:09:22 -07002513 auto display = displayDevice->getCompositionDisplay();
2514 const auto& displayState = display->getState();
2515 const auto displayId = display->getId();
2516
David Sodmanfa9b2af2017-12-24 13:28:59 -08002517 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002518
Lloyd Pique32cbe282018-10-19 13:09:22 -07002519 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 if (displayId) {
2521 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002522 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002523 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002524 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002525 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002526
Chia-I Wu7b549592017-11-15 09:14:57 -08002527 // The layer buffer from the previous frame (if any) is released
2528 // by HWC only when the release fence from this frame (if any) is
2529 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002530 if (displayId && layer->hasHwcLayer(displayDevice)) {
2531 releaseFence =
2532 getHwComposer().getLayerReleaseFence(*displayId,
2533 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002534 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002535
2536 // If the layer was client composited in the previous frame, we
2537 // need to merge with the previous client target acquire fence.
2538 // Since we do not track that, always merge with the current
2539 // client target acquire fence when it is available, even though
2540 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002541 if (layer->getCompositionType(displayDevice) ==
2542 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002543 releaseFence =
2544 Fence::merge("LayerRelease", releaseFence,
2545 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002546 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002547
David Sodman15094112018-10-11 09:39:37 -07002548 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 }
Chia-I Wu83806892017-11-16 10:50:20 -08002550
2551 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002552 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002553 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002554 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002556 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002557 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002558 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002559 }
2560 }
2561
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 if (displayId) {
2563 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002564 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002565 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566}
2567
Mathias Agopian87baae12012-07-31 12:38:26 -07002568void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569{
Mathias Agopian841cde52012-03-01 15:44:37 -08002570 ATRACE_CALL();
2571
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002572 // here we keep a copy of the drawing state (that is the state that's
2573 // going to be overwritten by handleTransactionLocked()) outside of
2574 // mStateLock so that the side-effects of the State assignment
2575 // don't happen with mStateLock held (which can cause deadlocks).
2576 State drawingState(mDrawingState);
2577
Mathias Agopianca4d3602011-05-19 15:38:14 -07002578 Mutex::Autolock _l(mStateLock);
2579 const nsecs_t now = systemTime();
2580 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581
Mathias Agopianca4d3602011-05-19 15:38:14 -07002582 // Here we're guaranteed that some transaction flags are set
2583 // so we can call handleTransactionLocked() unconditionally.
2584 // We call getTransactionFlags(), which will also clear the flags,
2585 // with mStateLock held to guarantee that mCurrentState won't change
2586 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002587
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002588 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002589 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002590 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002591
Mathias Agopianca4d3602011-05-19 15:38:14 -07002592 mLastTransactionTime = systemTime() - now;
2593 mDebugInTransaction = 0;
2594 invalidateHwcGeometry();
2595 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002596}
2597
Lloyd Piqueba04e622017-12-14 17:11:26 -08002598void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2599 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002600 const std::optional<DisplayIdentificationInfo> info =
2601 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002602
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002604 continue;
2605 }
2606
Lloyd Piqueba04e622017-12-14 17:11:26 -08002607 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002608 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002609 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 mPhysicalDisplayTokens[info->id] = new BBinder();
2611 DisplayDeviceState state;
2612 state.displayId = info->id;
2613 state.isSecure = true; // All physical displays are currently considered secure.
2614 state.displayName = info->name;
2615 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2616 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002617 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002618 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002619 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002620
Dominik Laskowski075d3172018-05-24 15:50:06 -07002621 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2622 if (index >= 0) {
2623 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2624 mInterceptor->saveDisplayDeletion(state.sequenceId);
2625 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002626 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002628 }
2629
2630 processDisplayChangesLocked();
2631 }
2632
2633 mPendingHotplugEvents.clear();
2634}
2635
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002636void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002637 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2638 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002639}
2640
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002643 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644 const sp<IGraphicBufferProducer>& producer) {
2645 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002646 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002648 creationArgs.isSecure = state.isSecure;
2649 creationArgs.displaySurface = dispSurface;
2650 creationArgs.hasWideColorGamut = false;
2651 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002652
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002653 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 creationArgs.isPrimary = isInternalDisplay;
2655
2656 if (useColorManagement && displayId) {
2657 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002659 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002660 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002662
Dominik Laskowski7e045462018-05-30 13:02:02 -07002663 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002665 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666 }
tangrobin6753a022018-08-10 10:58:54 +08002667 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002668
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 if (displayId) {
2670 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002671 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002673 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674
Lloyd Pique90c115d2018-09-18 21:39:42 -07002675 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002677 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002678
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679 // Make sure that composition can never be stalled by a virtual display
2680 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002681 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002682 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002683 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2684 }
2685
Dominik Laskowski075d3172018-05-24 15:50:06 -07002686 creationArgs.displayInstallOrientation =
2687 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002688
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002690 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002691
Lloyd Pique90c115d2018-09-18 21:39:42 -07002692 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002693
2694 if (maxFrameBufferAcquiredBuffers >= 3) {
2695 nativeWindowSurface->preallocateBuffers();
2696 }
2697
2698 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002699 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002700 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002701 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002702 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002703 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002704 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2705 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002706 if (!state.isVirtual()) {
2707 LOG_ALWAYS_FATAL_IF(!displayId);
2708 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002709 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002710
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 display->setLayerStack(state.layerStack);
2712 display->setProjection(state.orientation, state.viewport, state.frame);
2713 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002716}
2717
Lloyd Pique347200f2017-12-14 17:00:15 -08002718void SurfaceFlinger::processDisplayChangesLocked() {
2719 // here we take advantage of Vector's copy-on-write semantics to
2720 // improve performance by skipping the transaction entirely when
2721 // know that the lists are identical
2722 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2723 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2724 if (!curr.isIdenticalTo(draw)) {
2725 mVisibleRegionsDirty = true;
2726 const size_t cc = curr.size();
2727 size_t dc = draw.size();
2728
2729 // find the displays that were removed
2730 // (ie: in drawing state but not in current state)
2731 // also handle displays that changed
2732 // (ie: displays that are in both lists)
2733 for (size_t i = 0; i < dc;) {
2734 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2735 if (j < 0) {
2736 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002738 // Save display ID before disconnecting.
2739 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002740 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002741
2742 if (!display->isVirtual()) {
2743 LOG_ALWAYS_FATAL_IF(!displayId);
2744 dispatchDisplayHotplugEvent(displayId->value, false);
2745 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002746 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002747
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002748 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 } else {
2750 // this display is in both lists. see if something changed.
2751 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002752 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002753 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2754 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2755 if (state_binder != draw_binder) {
2756 // changing the surface is like destroying and
2757 // recreating the DisplayDevice, so we just remove it
2758 // from the drawing state, so that it get re-added
2759 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002761 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002763 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 mDrawingState.displays.removeItemsAt(i);
2765 dc--;
2766 // at this point we must loop to the next item
2767 continue;
2768 }
2769
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002770 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002772 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002773 }
2774 if ((state.orientation != draw[i].orientation) ||
2775 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002776 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 }
2778 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002779 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 }
2781 }
2782 }
2783 ++i;
2784 }
2785
2786 // find displays that were added
2787 // (ie: in current state but not in drawing state)
2788 for (size_t i = 0; i < cc; i++) {
2789 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2790 const DisplayDeviceState& state(curr[i]);
2791
Lloyd Pique542307f2018-10-19 13:24:08 -07002792 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 sp<IGraphicBufferProducer> producer;
2794 sp<IGraphicBufferProducer> bqProducer;
2795 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002796 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002797
Dominik Laskowski075d3172018-05-24 15:50:06 -07002798 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002799 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002800 // Virtual displays without a surface are dormant:
2801 // they have external state (layer stack, projection,
2802 // etc.) but no internal state (i.e. a DisplayDevice).
2803 if (state.surface != nullptr) {
2804 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002805 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002806 int width = 0;
2807 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2808 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2809 int height = 0;
2810 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2811 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2812 int intFormat = 0;
2813 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2814 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002815 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002816
Dominik Laskowski075d3172018-05-24 15:50:06 -07002817 displayId =
2818 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002819 }
2820
2821 // TODO: Plumb requested format back up to consumer
2822
2823 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002824 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002825 bqProducer, bqConsumer,
2826 state.displayName);
2827
2828 dispSurface = vds;
2829 producer = vds;
2830 }
2831 } else {
2832 ALOGE_IF(state.surface != nullptr,
2833 "adding a supported display, but rendering "
2834 "surface is provided (%p), ignoring it",
2835 state.surface.get());
2836
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837 displayId = state.displayId;
2838 LOG_ALWAYS_FATAL_IF(!displayId);
2839 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002840 producer = bqProducer;
2841 }
2842
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002844 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002845 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002846 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002847 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002848 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002849 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002850 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002851 }
2852 }
2853 }
2854 }
2855 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002856
2857 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002858}
2859
Mathias Agopian87baae12012-07-31 12:38:26 -07002860void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002861{
Dan Stoza7dde5992015-05-22 09:51:44 -07002862 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002863 mCurrentState.traverseInZOrder([](Layer* layer) {
2864 layer->notifyAvailableFrames();
2865 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002866
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 /*
2868 * Traversal of the children
2869 * (perform the transaction for each of them if needed)
2870 */
2871
Mathias Agopian3559b072012-08-15 13:46:03 -07002872 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002873 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002875 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876
2877 const uint32_t flags = layer->doTransaction(0);
2878 if (flags & Layer::eVisibleRegion)
2879 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002880
2881 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002882 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002883 }
Robert Carr2047fae2016-11-28 14:09:09 -08002884 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 }
2886
2887 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002888 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 */
2890
Mathias Agopiane57f2922012-08-09 16:29:12 -07002891 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002892 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002893 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002894 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002896 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002897 // The transform hint might have changed for some layers
2898 // (either because a display has changed, or because a layer
2899 // as changed).
2900 //
2901 // Walk through all the layers in currentLayers,
2902 // and update their transform hint.
2903 //
2904 // If a layer is visible only on a single display, then that
2905 // display is used to calculate the hint, otherwise we use the
2906 // default display.
2907 //
2908 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2909 // the hint is set before we acquire a buffer from the surface texture.
2910 //
2911 // NOTE: layer transactions have taken place already, so we use their
2912 // drawing state. However, SurfaceFlinger's own transaction has not
2913 // happened yet, so we must use the current state layer list
2914 // (soon to become the drawing state list).
2915 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002916 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002917 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002918 bool first = true;
2919 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002920 // NOTE: we rely on the fact that layers are sorted by
2921 // layerStack first (so we don't have to traverse the list
2922 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002924 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002925 currentlayerStack = layerStack;
2926 // figure out if this layerstack is mirrored
2927 // (more than one display) if so, pick the default display,
2928 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002929 hintDisplay = nullptr;
2930 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002931 if (display->getCompositionDisplay()
2932 ->belongsInOutput(layer->getLayerStack(),
2933 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 if (hintDisplay) {
2935 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002936 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002938 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002939 }
2940 }
2941 }
2942 }
Chet Haase91d25932013-04-11 15:24:55 -07002943
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002944 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002945 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2946 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002947
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002948 // could be null when this layer is using a layerStack
2949 // that is not visible on any display. Also can occur at
2950 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002951 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002952 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002953
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002954 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002955 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002956 if (hintDisplay) {
2957 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002958 }
Robert Carr2047fae2016-11-28 14:09:09 -08002959
2960 first = false;
2961 });
Mathias Agopian84300952012-11-21 16:02:13 -08002962 }
2963
2964
Mathias Agopian3559b072012-08-15 13:46:03 -07002965 /*
2966 * Perform our own transaction if needed
2967 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968
2969 if (mLayersAdded) {
2970 mLayersAdded = false;
2971 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002972 mVisibleRegionsDirty = true;
2973 }
2974
2975 // some layers might have been removed, so
2976 // we need to update the regions they're exposing.
2977 if (mLayersRemoved) {
2978 mLayersRemoved = false;
2979 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002980 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002981 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002982 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002983 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002984 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002985 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002986 }
Robert Carr2047fae2016-11-28 14:09:09 -08002987 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 }
2989
Vishnu Nairec0ab382019-02-13 15:32:56 -08002990 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002992}
2993
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002994void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002995 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002996 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002997 return;
2998 }
2999
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003000 if (mVisibleRegionsDirty || mInputInfoChanged) {
3001 mInputInfoChanged = false;
3002 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08003003 } else if (mInputWindowCommands.syncInputWindows) {
3004 // If the caller requested to sync input windows, but there are no
3005 // changes to input windows, notify immediately.
3006 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003007 }
3008
3009 executeInputWindowCommands();
3010}
3011
3012void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003013 Vector<InputWindowInfo> inputHandles;
3014
3015 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3016 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003017 // When calculating the screen bounds we ignore the transparent region since it may
3018 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003019 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003020 }
3021 });
chaviw291d88a2019-02-14 10:33:58 -08003022
3023 mInputFlinger->setInputWindows(inputHandles,
3024 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3025 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003026}
3027
Vishnu Nairec0ab382019-02-13 15:32:56 -08003028void SurfaceFlinger::commitInputWindowCommands() {
3029 mInputWindowCommands.merge(mPendingInputWindowCommands);
3030 mPendingInputWindowCommands.clear();
3031}
3032
chaviwfbe5d9c2018-12-26 12:23:37 -08003033void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003034 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3035 if (transferTouchFocusCommand.fromToken != nullptr &&
3036 transferTouchFocusCommand.toToken != nullptr &&
3037 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3038 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3039 transferTouchFocusCommand.toToken);
3040 }
3041 }
3042
3043 mInputWindowCommands.clear();
3044}
3045
Riley Andrews03414a12014-07-01 14:22:59 -07003046void SurfaceFlinger::updateCursorAsync()
3047{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003048 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003049 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003050 continue;
3051 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3054 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003055 }
3056 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003057}
3058
chaviw61626f22018-11-15 16:26:27 -08003059void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3060 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003061 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003062 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003063 }
3064 layer->releasePendingBuffer(systemTime());
3065}
3066
Mathias Agopian4fec8732012-06-29 14:12:52 -07003067void SurfaceFlinger::commitTransaction()
3068{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003069 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003070 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003071 for (const auto& l : mLayersPendingRemoval) {
3072 recordBufferingStats(l->getName().string(),
3073 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003074
Lloyd Pique07e33212018-12-18 16:33:37 -08003075 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003076 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003077 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003078 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003079 }
3080 mLayersPendingRemoval.clear();
3081 }
3082
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003083 // If this transaction is part of a window animation then the next frame
3084 // we composite should be considered an animation as well.
3085 mAnimCompositionPending = mAnimTransactionPending;
3086
Mathias Agopian4fec8732012-06-29 14:12:52 -07003087 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003088 // clear the "changed" flags in current state
3089 mCurrentState.colorMatrixChanged = false;
3090
Robert Carr1f0a16a2016-10-24 16:27:39 -07003091 mDrawingState.traverseInZOrder([](Layer* layer) {
3092 layer->commitChildList();
3093 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003094 mTransactionPending = false;
3095 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003096 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097}
3098
Lloyd Pique32cbe282018-10-19 13:09:22 -07003099void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003100 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003101 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003102 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003103
Lloyd Pique32cbe282018-10-19 13:09:22 -07003104 auto display = displayDevice->getCompositionDisplay();
3105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106 Region aboveOpaqueLayers;
3107 Region aboveCoveredLayers;
3108 Region dirty;
3109
Mathias Agopian87baae12012-07-31 12:38:26 -07003110 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111
Robert Carr2047fae2016-11-28 14:09:09 -08003112 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003113 // start with the whole surface at its current location
3114 const Layer::State& s(layer->getDrawingState());
3115
Jesse Hall01e29052013-02-19 16:13:35 -08003116 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003117 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003118 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003119 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003120
Mathias Agopianab028732010-03-16 16:41:46 -07003121 /*
3122 * opaqueRegion: area of a surface that is fully opaque.
3123 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003125
3126 /*
3127 * visibleRegion: area of a surface that is visible on screen
3128 * and not fully transparent. This is essentially the layer's
3129 * footprint minus the opaque regions above it.
3130 * Areas covered by a translucent surface are considered visible.
3131 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003133
3134 /*
3135 * coveredRegion: area of a surface that is covered by all
3136 * visible regions above it (which includes the translucent areas).
3137 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003139
Jesse Halla8026d22012-09-25 13:25:04 -07003140 /*
3141 * transparentRegion: area of a surface that is hinted to be completely
3142 * transparent. This is only used to tell when the layer has no visible
3143 * non-transparent regions and can be removed from the layer list. It
3144 * does not affect the visibleRegion of this layer or any layers
3145 * beneath it. The hint may not be correct if apps don't respect the
3146 * SurfaceView restrictions (which, sadly, some don't).
3147 */
3148 Region transparentRegion;
3149
Mathias Agopianab028732010-03-16 16:41:46 -07003150
3151 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003152 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003153 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003154 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003155
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003157 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003158 if (!visibleRegion.isEmpty()) {
3159 // Remove the transparent area from the visible region
3160 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003161 if (tr.preserveRects()) {
3162 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003163 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003164 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003165 // transformation too complex, can't do the
3166 // transparent region optimization.
3167 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003168 }
Mathias Agopianab028732010-03-16 16:41:46 -07003169 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170
Mathias Agopianab028732010-03-16 16:41:46 -07003171 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003172 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003173 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003174 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003175 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003176 // the opaque region is the layer's footprint
3177 opaqueRegion = visibleRegion;
3178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
3180 }
3181
Robert Carre5f4f692018-01-12 13:12:28 -08003182 if (visibleRegion.isEmpty()) {
3183 layer->clearVisibilityRegions();
3184 return;
3185 }
3186
Mathias Agopianab028732010-03-16 16:41:46 -07003187 // Clip the covered region to the visible region
3188 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3189
3190 // Update aboveCoveredLayers for next (lower) layer
3191 aboveCoveredLayers.orSelf(visibleRegion);
3192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 // subtract the opaque region covered by the layers above us
3194 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195
3196 // compute this layer's dirty region
3197 if (layer->contentDirty) {
3198 // we need to invalidate the whole region
3199 dirty = visibleRegion;
3200 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003201 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 layer->contentDirty = false;
3203 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003204 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003205 * the exposed region consists of two components:
3206 * 1) what's VISIBLE now and was COVERED before
3207 * 2) what's EXPOSED now less what was EXPOSED before
3208 *
3209 * note that (1) is conservative, we start with the whole
3210 * visible region but only keep what used to be covered by
3211 * something -- which mean it may have been exposed.
3212 *
3213 * (2) handles areas that were not covered by anything but got
3214 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003215 */
Mathias Agopianab028732010-03-16 16:41:46 -07003216 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003217 const Region oldVisibleRegion = layer->visibleRegion;
3218 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003219 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3220 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221 }
3222 dirty.subtractSelf(aboveOpaqueLayers);
3223
3224 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003225 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226
Mathias Agopianab028732010-03-16 16:41:46 -07003227 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003229
Jesse Halla8026d22012-09-25 13:25:04 -07003230 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231 layer->setVisibleRegion(visibleRegion);
3232 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003233 layer->setVisibleNonTransparentRegion(
3234 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003235 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236
Mathias Agopian87baae12012-07-31 12:38:26 -07003237 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238}
3239
Chia-I Wuab0c3192017-08-01 11:29:00 -07003240void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003241 for (const auto& [token, displayDevice] : mDisplays) {
3242 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003243 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003244 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003245 }
3246 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003247}
3248
Daniel Solomon42d04562019-01-20 21:03:19 -08003249void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3250 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3251 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3252 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3253 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3254 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3255 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3256 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3257 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3258 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3259 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3260 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3261 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3262}
3263
Dan Stoza6b9454d2014-11-07 16:00:59 -08003264bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003266 ALOGV("handlePageFlip");
3267
Brian Andersond6927fb2016-07-23 23:37:30 -07003268 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269
Mathias Agopian4fec8732012-06-29 14:12:52 -07003270 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003271 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003272 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003273
3274 // Store the set of layers that need updates. This set must not change as
3275 // buffers are being latched, as this could result in a deadlock.
3276 // Example: Two producers share the same command stream and:
3277 // 1.) Layer 0 is latched
3278 // 2.) Layer 0 gets a new frame
3279 // 2.) Layer 1 gets a new frame
3280 // 3.) Layer 1 is latched.
3281 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3282 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003283 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003284 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003285 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003286 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003287 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003288 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003289 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003290 } else {
3291 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003292 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003293 } else {
3294 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003295 }
Robert Carr2047fae2016-11-28 14:09:09 -08003296 });
3297
Lloyd Piquef2c79392018-12-20 16:23:33 -08003298 if (!mLayersWithQueuedFrames.empty()) {
3299 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3300 // writes to Layer current state. See also b/119481871
3301 Mutex::Autolock lock(mStateLock);
3302
3303 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003304 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003305 mLayersPendingRefresh.push_back(layer);
3306 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003307 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003308 if (layer->isBufferLatched()) {
3309 newDataLatched = true;
3310 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003311 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003312 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003313
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003314 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003315
3316 // If we will need to wake up at some time in the future to deal with a
3317 // queued frame that shouldn't be displayed during this vsync period, wake
3318 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003319 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003320 signalLayerUpdate();
3321 }
3322
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003323 // enter boot animation on first buffer latch
3324 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3325 ALOGI("Enter boot animation");
3326 mBootStage = BootStage::BOOTANIMATION;
3327 }
3328
Dan Stoza6b9454d2014-11-07 16:00:59 -08003329 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003330 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331}
3332
Mathias Agopianad456f92011-01-13 17:53:01 -08003333void SurfaceFlinger::invalidateHwcGeometry()
3334{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003335 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003336}
3337
Lloyd Pique32cbe282018-10-19 13:09:22 -07003338void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003339 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003340 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003341 // We only need to actually compose the display if:
3342 // 1) It is being handled by hardware composer, which may need this to
3343 // keep its virtual display state machine in sync, or
3344 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003345 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003346 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003347 return;
3348 }
3349
Dan Stoza9e56aa02015-11-02 13:00:03 -08003350 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003351 base::unique_fd readyFence;
3352 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003353
3354 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003355 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356}
3357
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003358bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3359 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003360 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003361 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003362
Lloyd Pique32cbe282018-10-19 13:09:22 -07003363 auto display = displayDevice->getCompositionDisplay();
3364 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003365 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003366
3367 const Region bounds(displayState.bounds);
3368 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003369 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003370 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003371
Peiyong Lind3788632018-09-18 16:01:31 -07003372 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003373 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003374
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003375 renderengine::DisplaySettings clientCompositionDisplay;
3376 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3377 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003378 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003379
Dan Stoza9e56aa02015-11-02 13:00:03 -08003380 if (hasClientComposition) {
3381 ALOGV("hasClientComposition");
3382
Alec Mouri6338c9d2019-02-07 16:57:51 -08003383 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003384 if (buf == nullptr) {
3385 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3386 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003387 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003388 return false;
3389 }
3390
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003391 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3392 clientCompositionDisplay.clip = displayState.scissor;
3393 const ui::Transform& displayTransform = displayState.transform;
3394 mat4 m;
3395 m[0][0] = displayTransform[0][0];
3396 m[0][1] = displayTransform[0][1];
3397 m[0][3] = displayTransform[0][2];
3398 m[1][0] = displayTransform[1][0];
3399 m[1][1] = displayTransform[1][1];
3400 m[1][3] = displayTransform[1][2];
3401 m[3][0] = displayTransform[2][0];
3402 m[3][1] = displayTransform[2][1];
3403 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003405
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003406 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003407 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003408 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003409 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003410 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003411 clientCompositionDisplay.outputDataspace = outputDataspace;
3412 clientCompositionDisplay.maxLuminance =
3413 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003414
Lloyd Pique441d5042018-10-18 16:49:51 -07003415 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003416 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003417 getHwComposer()
3418 .hasDisplayCapability(displayId,
3419 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003420
Peiyong Lind3788632018-09-18 16:01:31 -07003421 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003422 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3423 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003424 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003425 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003426 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003427
Mathias Agopian85d751c2012-08-29 16:59:24 -07003428 /*
3429 * and then, render the layers targeted at the framebuffer
3430 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003431
Dan Stoza9e56aa02015-11-02 13:00:03 -08003432 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003434 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003435 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003436 const Region viewportRegion(displayState.viewport);
3437 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003438 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003439 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003441 switch (layer->getCompositionType(displayDevice)) {
3442 case Hwc2::IComposerClient::Composition::CURSOR:
3443 case Hwc2::IComposerClient::Composition::DEVICE:
3444 case Hwc2::IComposerClient::Composition::SIDEBAND:
3445 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003446 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003447 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003448 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003449 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003450 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003451 // never clear the very first layer since we're
3452 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003453 renderengine::LayerSettings layerSettings;
3454 Region dummyRegion;
3455 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3456 layerSettings);
3457
3458 if (prepared) {
3459 layerSettings.source.buffer.buffer = nullptr;
3460 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3461 layerSettings.alpha = half(0.0);
3462 layerSettings.disableBlending = true;
3463 clientCompositionLayers.push_back(layerSettings);
3464 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003465 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003466 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003467 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003468 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003469 renderengine::LayerSettings layerSettings;
3470 bool prepared =
3471 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3472 if (prepared) {
3473 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003474 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003475 break;
3476 }
3477 default:
3478 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003479 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003480 } else {
3481 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003482 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003483 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003484 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003485
Alec Mouri820c7402019-01-23 13:02:39 -08003486 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003487 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003488 clientCompositionDisplay.clearRegion = clearRegion;
3489 if (!debugRegion.isEmpty()) {
3490 Region::const_iterator it = debugRegion.begin();
3491 Region::const_iterator end = debugRegion.end();
3492 while (it != end) {
3493 const Rect& rect = *it++;
3494 renderengine::LayerSettings layerSettings;
3495 layerSettings.source.buffer.buffer = nullptr;
3496 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3497 layerSettings.geometry.boundaries = rect.toFloatRect();
3498 layerSettings.alpha = half(1.0);
3499 clientCompositionLayers.push_back(layerSettings);
3500 }
3501 }
3502 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mouri6338c9d2019-02-07 16:57:51 -08003503 buf->getNativeBuffer(), std::move(fd), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003504 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003505 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506}
3507
Chia-I Wu28e3a252018-09-07 12:05:02 -07003508void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003509 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003510 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511}
3512
Dan Stoza7d89d062015-04-30 13:29:25 -07003513status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003514 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003515 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003516 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003517 const sp<Layer>& parent,
3518 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003519{
Dan Stoza7d89d062015-04-30 13:29:25 -07003520 // add this layer to the current state list
3521 {
3522 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003523 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003524 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3525 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003526 return NO_MEMORY;
3527 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003528 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003529 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003530 } else if (parent == nullptr) {
3531 lbc->onRemovedFromCurrentState();
3532 } else if (parent->isRemovedFromCurrentState()) {
3533 parent->addChild(lbc);
3534 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003535 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003536 parent->addChild(lbc);
3537 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003538
Yiwei Zhang243b3782018-05-15 17:40:04 -07003539 if (gbc != nullptr) {
3540 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3541 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3542 mMaxGraphicBufferProducerListSize,
3543 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3544 mGraphicBufferProducerList.size(),
3545 mMaxGraphicBufferProducerListSize, mNumLayers);
3546 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003547 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003548 }
3549
Mathias Agopian96f08192010-06-02 23:28:45 -07003550 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003551 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003552
Dan Stoza7d89d062015-04-30 13:29:25 -07003553 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003554}
3555
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003556uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003557 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003558}
3559
Mathias Agopian3f844832013-08-07 21:24:32 -07003560uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003561 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562}
3563
Mathias Agopian3f844832013-08-07 21:24:32 -07003564uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003565 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003566}
3567
3568uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003569 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003570 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003571 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003572 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003573 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 }
3575 return old;
3576}
3577
Marissa Wall713b63f2018-10-17 15:42:43 -07003578bool SurfaceFlinger::flushTransactionQueues() {
3579 Mutex::Autolock _l(mStateLock);
3580 auto it = mTransactionQueues.begin();
3581 while (it != mTransactionQueues.end()) {
3582 auto& [applyToken, transactionQueue] = *it;
3583
3584 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003585 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3586 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003587 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003588 break;
3589 }
Robert Carr14167e02019-02-13 13:50:55 -08003590 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003591 transactionQueue.pop();
3592 }
3593
3594 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3595 }
3596 return mTransactionQueues.empty();
3597}
3598
chaviwca27f252018-02-06 16:46:39 -08003599bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3600 for (const ComposerState& state : states) {
3601 // Here we need to check that the interface we're given is indeed
3602 // one of our own. A malicious client could give us a nullptr
3603 // IInterface, or one of its own or even one of our own but a
3604 // different type. All these situations would cause us to crash.
3605 if (state.client == nullptr) {
3606 return true;
3607 }
3608
3609 sp<IBinder> binder = IInterface::asBinder(state.client);
3610 if (binder == nullptr) {
3611 return true;
3612 }
3613
3614 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3615 return true;
3616 }
3617 }
3618 return false;
3619}
3620
Marissa Wall17b4e452018-12-26 16:32:34 -08003621bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3622 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003623 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003624 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3625 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3626 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3627 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3628 return false;
3629 }
3630
Marissa Wall713b63f2018-10-17 15:42:43 -07003631 for (const ComposerState& state : states) {
3632 const layer_state_t& s = state.state;
3633 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3634 continue;
3635 }
3636 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003637 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003638 }
3639 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003640 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003641}
3642
3643void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3644 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003645 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003646 const InputWindowCommands& inputWindowCommands,
3647 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003648 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003649
3650 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3651
Mathias Agopian698c0872011-06-28 19:09:31 -07003652 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003653
chaviwca27f252018-02-06 16:46:39 -08003654 if (containsAnyInvalidClientState(states)) {
3655 return;
3656 }
3657
Marissa Wall713b63f2018-10-17 15:42:43 -07003658 // If its TransactionQueue already has a pending TransactionState or if it is pending
3659 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003660 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003661 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3662 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003663 setTransactionFlags(eTransactionNeeded);
3664 return;
3665 }
3666
Robert Carr14167e02019-02-13 13:50:55 -08003667 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003668}
3669
3670void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003671 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003672 const InputWindowCommands& inputWindowCommands,
3673 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003674 uint32_t transactionFlags = 0;
3675
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003676 if (flags & eAnimation) {
3677 // For window updates that are part of an animation we must wait for
3678 // previous animation "frames" to be handled.
3679 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003680 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003681 if (CC_UNLIKELY(err != NO_ERROR)) {
3682 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003683 // caller after a few seconds.
3684 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3685 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003686 mAnimTransactionPending = false;
3687 break;
3688 }
3689 }
3690 }
3691
chaviwca27f252018-02-06 16:46:39 -08003692 for (const DisplayState& display : displays) {
3693 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003694 }
3695
Marissa Walle2ffb422018-10-12 11:33:52 -07003696 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003697 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003698 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003699 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003700 // If the state doesn't require a traversal and there are callbacks, send them now
3701 if (!(clientStateFlags & eTraversalNeeded)) {
3702 mTransactionCompletedThread.sendCallbacks();
3703 }
3704 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003705
chaviw273171b2018-12-26 11:46:30 -08003706 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3707
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003708 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3709 // anyway. This can be used as a flush mechanism for previous async transactions.
3710 // Empty animation transaction can be used to simulate back-pressure, so also force a
3711 // transaction for empty animation transactions.
3712 if (transactionFlags == 0 &&
3713 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003714 transactionFlags = eTransactionNeeded;
3715 }
3716
Mathias Agopian386aa982011-11-07 21:58:03 -08003717 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003718 if (mInterceptor->isEnabled()) {
3719 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003720 }
Irvel468051e2016-06-13 16:44:44 -07003721
Mathias Agopian386aa982011-11-07 21:58:03 -08003722 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003723 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3724 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003725 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003726
3727 // if this is a synchronous transaction, wait for it to take effect
3728 // before returning.
3729 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003730 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003731 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003732 if (flags & eAnimation) {
3733 mAnimTransactionPending = true;
3734 }
chaviw95ef3c42019-02-14 10:55:09 -08003735
3736 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3737 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003738 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3739 if (CC_UNLIKELY(err != NO_ERROR)) {
3740 // just in case something goes wrong in SF, return to the
3741 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003742 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3743 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003744 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003745 break;
3746 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 }
3749}
3750
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003751uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3752 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3753 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003754
Mathias Agopiane57f2922012-08-09 16:29:12 -07003755 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003756 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3757
3758 const uint32_t what = s.what;
3759 if (what & DisplayState::eSurfaceChanged) {
3760 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3761 state.surface = s.surface;
3762 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003763 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003764 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003765 if (what & DisplayState::eLayerStackChanged) {
3766 if (state.layerStack != s.layerStack) {
3767 state.layerStack = s.layerStack;
3768 flags |= eDisplayTransactionNeeded;
3769 }
3770 }
3771 if (what & DisplayState::eDisplayProjectionChanged) {
3772 if (state.orientation != s.orientation) {
3773 state.orientation = s.orientation;
3774 flags |= eDisplayTransactionNeeded;
3775 }
3776 if (state.frame != s.frame) {
3777 state.frame = s.frame;
3778 flags |= eDisplayTransactionNeeded;
3779 }
3780 if (state.viewport != s.viewport) {
3781 state.viewport = s.viewport;
3782 flags |= eDisplayTransactionNeeded;
3783 }
3784 }
3785 if (what & DisplayState::eDisplaySizeChanged) {
3786 if (state.width != s.width) {
3787 state.width = s.width;
3788 flags |= eDisplayTransactionNeeded;
3789 }
3790 if (state.height != s.height) {
3791 state.height = s.height;
3792 flags |= eDisplayTransactionNeeded;
3793 }
3794 }
3795
Mathias Agopiane57f2922012-08-09 16:29:12 -07003796 return flags;
3797}
3798
Robert Carr14167e02019-02-13 13:50:55 -08003799bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003800 IPCThreadState* ipc = IPCThreadState::self();
3801 const int pid = ipc->getCallingPid();
3802 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003803 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003804 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003805 return false;
3806 }
3807 return true;
3808}
3809
Robert Carr14167e02019-02-13 13:50:55 -08003810uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3811 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003812 const layer_state_t& s = composerState.state;
3813 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3814
Mathias Agopian13127d82013-03-05 17:47:11 -08003815 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003816 if (layer == nullptr) {
3817 return 0;
3818 }
3819
chaviw8b3871a2017-11-01 17:41:01 -07003820 uint32_t flags = 0;
3821
Garfield Tan8a3083e2018-12-03 13:21:07 -08003822 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003823 bool geometryAppliesWithResize =
3824 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003825
3826 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3827 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003828 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003829 layer->pushPendingState();
3830 }
3831
chaviw8b3871a2017-11-01 17:41:01 -07003832 if (what & layer_state_t::ePositionChanged) {
3833 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3834 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003835 }
chaviw8b3871a2017-11-01 17:41:01 -07003836 }
3837 if (what & layer_state_t::eLayerChanged) {
3838 // NOTE: index needs to be calculated before we update the state
3839 const auto& p = layer->getParent();
3840 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003841 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003842 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003843 mCurrentState.layersSortedByZ.removeAt(idx);
3844 mCurrentState.layersSortedByZ.add(layer);
3845 // we need traversal (state changed)
3846 // AND transaction (list changed)
3847 flags |= eTransactionNeeded|eTraversalNeeded;
3848 }
chaviw8b3871a2017-11-01 17:41:01 -07003849 } else {
3850 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003851 flags |= eTransactionNeeded|eTraversalNeeded;
3852 }
3853 }
chaviw8b3871a2017-11-01 17:41:01 -07003854 }
3855 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003856 // NOTE: index needs to be calculated before we update the state
3857 const auto& p = layer->getParent();
3858 if (p == nullptr) {
3859 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3860 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3861 mCurrentState.layersSortedByZ.removeAt(idx);
3862 mCurrentState.layersSortedByZ.add(layer);
3863 // we need traversal (state changed)
3864 // AND transaction (list changed)
3865 flags |= eTransactionNeeded|eTraversalNeeded;
3866 }
3867 } else {
3868 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3869 flags |= eTransactionNeeded|eTraversalNeeded;
3870 }
chaviw8b3871a2017-11-01 17:41:01 -07003871 }
3872 }
3873 if (what & layer_state_t::eSizeChanged) {
3874 if (layer->setSize(s.w, s.h)) {
3875 flags |= eTraversalNeeded;
3876 }
3877 }
3878 if (what & layer_state_t::eAlphaChanged) {
3879 if (layer->setAlpha(s.alpha))
3880 flags |= eTraversalNeeded;
3881 }
3882 if (what & layer_state_t::eColorChanged) {
3883 if (layer->setColor(s.color))
3884 flags |= eTraversalNeeded;
3885 }
Peiyong Lind3788632018-09-18 16:01:31 -07003886 if (what & layer_state_t::eColorTransformChanged) {
3887 if (layer->setColorTransform(s.colorTransform)) {
3888 flags |= eTraversalNeeded;
3889 }
3890 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003891 if (what & layer_state_t::eBackgroundColorChanged) {
3892 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3893 flags |= eTraversalNeeded;
3894 }
3895 }
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003897 // TODO: b/109894387
3898 //
3899 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3900 // rotation. To see the problem observe that if we have a square parent, and a child
3901 // of the same size, then we rotate the child 45 degrees around it's center, the child
3902 // must now be cropped to a non rectangular 8 sided region.
3903 //
3904 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3905 // private API, and the WindowManager only uses rotation in one case, which is on a top
3906 // level layer in which cropping is not an issue.
3907 //
3908 // However given that abuse of rotation matrices could lead to surfaces extending outside
3909 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3910 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3911 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003912 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003913 flags |= eTraversalNeeded;
3914 }
3915 if (what & layer_state_t::eTransparentRegionChanged) {
3916 if (layer->setTransparentRegionHint(s.transparentRegion))
3917 flags |= eTraversalNeeded;
3918 }
3919 if (what & layer_state_t::eFlagsChanged) {
3920 if (layer->setFlags(s.flags, s.mask))
3921 flags |= eTraversalNeeded;
3922 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003923 if (what & layer_state_t::eCropChanged_legacy) {
3924 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003925 flags |= eTraversalNeeded;
3926 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003927 if (what & layer_state_t::eCornerRadiusChanged) {
3928 if (layer->setCornerRadius(s.cornerRadius))
3929 flags |= eTraversalNeeded;
3930 }
chaviw8b3871a2017-11-01 17:41:01 -07003931 if (what & layer_state_t::eLayerStackChanged) {
3932 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3933 // We only allow setting layer stacks for top level layers,
3934 // everything else inherits layer stack from its parent.
3935 if (layer->hasParent()) {
3936 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3937 layer->getName().string());
3938 } else if (idx < 0) {
3939 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3940 "that also does not appear in the top level layer list. Something"
3941 " has gone wrong.", layer->getName().string());
3942 } else if (layer->setLayerStack(s.layerStack)) {
3943 mCurrentState.layersSortedByZ.removeAt(idx);
3944 mCurrentState.layersSortedByZ.add(layer);
3945 // we need traversal (state changed)
3946 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003947 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003948 }
3949 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003950 if (what & layer_state_t::eDeferTransaction_legacy) {
3951 if (s.barrierHandle_legacy != nullptr) {
3952 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3953 } else if (s.barrierGbp_legacy != nullptr) {
3954 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003955 if (authenticateSurfaceTextureLocked(gbp)) {
3956 const auto& otherLayer =
3957 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003958 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003959 } else {
3960 ALOGE("Attempt to defer transaction to to an"
3961 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003962 }
3963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 // We don't trigger a traversal here because if no other state is
3965 // changed, we don't want this to cause any more work
3966 }
3967 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003968 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003969 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003970 if (!hadParent) {
3971 mCurrentState.layersSortedByZ.remove(layer);
3972 }
chaviw8b3871a2017-11-01 17:41:01 -07003973 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003974 }
chaviw8b3871a2017-11-01 17:41:01 -07003975 }
3976 if (what & layer_state_t::eReparentChildren) {
3977 if (layer->reparentChildren(s.reparentHandle)) {
3978 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003979 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003980 }
chaviw8b3871a2017-11-01 17:41:01 -07003981 if (what & layer_state_t::eDetachChildren) {
3982 layer->detachChildren();
3983 }
3984 if (what & layer_state_t::eOverrideScalingModeChanged) {
3985 layer->setOverrideScalingMode(s.overrideScalingMode);
3986 // We don't trigger a traversal here because if no other state is
3987 // changed, we don't want this to cause any more work
3988 }
Marissa Wall61c58622018-07-18 10:12:20 -07003989 if (what & layer_state_t::eTransformChanged) {
3990 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3991 }
3992 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3993 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3994 flags |= eTraversalNeeded;
3995 }
3996 if (what & layer_state_t::eCropChanged) {
3997 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3998 }
Marissa Wall861616d2018-10-22 12:52:23 -07003999 if (what & layer_state_t::eFrameChanged) {
4000 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4001 }
Marissa Wall61c58622018-07-18 10:12:20 -07004002 if (what & layer_state_t::eAcquireFenceChanged) {
4003 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4004 }
4005 if (what & layer_state_t::eDataspaceChanged) {
4006 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4007 }
4008 if (what & layer_state_t::eHdrMetadataChanged) {
4009 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4010 }
4011 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4012 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4013 }
4014 if (what & layer_state_t::eApiChanged) {
4015 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4016 }
4017 if (what & layer_state_t::eSidebandStreamChanged) {
4018 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4019 }
Robert Carr720e5062018-07-30 17:45:14 -07004020 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004021 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4022 layer->setInputInfo(s.inputInfo);
4023 flags |= eTraversalNeeded;
4024 } else {
4025 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4026 }
Robert Carr720e5062018-07-30 17:45:14 -07004027 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004028 if (what & layer_state_t::eMetadataChanged) {
4029 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4030 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004031 std::vector<sp<CallbackHandle>> callbackHandles;
4032 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4033 mTransactionCompletedThread.run();
4034 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4035 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4036 }
4037 }
Marissa Wall73411622019-01-25 10:45:41 -08004038
4039 if (what & layer_state_t::eBufferChanged) {
4040 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4041 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4042 s.buffer);
4043 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004044 if (what & layer_state_t::eCachedBufferChanged) {
4045 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004046 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4047 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004048 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4049 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004050 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4051 // Do not put anything that updates layer state or modifies flags after
4052 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004053 return flags;
4054}
4055
chaviw273171b2018-12-26 11:46:30 -08004056uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4057 uint32_t flags = 0;
4058 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4059 flags |= eTraversalNeeded;
4060 }
4061
chaviwa911b102019-02-14 10:18:33 -08004062 if (inputWindowCommands.syncInputWindows) {
4063 flags |= eTraversalNeeded;
4064 }
4065
Vishnu Nairec0ab382019-02-13 15:32:56 -08004066 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004067 return flags;
4068}
4069
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004070status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4071 uint32_t h, PixelFormat format, uint32_t flags,
4072 LayerMetadata metadata, sp<IBinder>* handle,
4073 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004074 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004075 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004076 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004078 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004079
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004080 status_t result = NO_ERROR;
4081
4082 sp<Layer> layer;
4083
Cody Northropbc755282017-03-31 12:00:08 -06004084 String8 uniqueName = getUniqueLayerName(name);
4085
Mathias Agopian3165cc22012-08-08 19:42:09 -07004086 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004087 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004088 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4089 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004091 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004092 case ISurfaceComposerClient::eFXSurfaceBufferState:
4093 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4094 break;
chaviw13fdc492017-06-27 12:40:18 -07004095 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004096 // check if buffer size is set for color layer.
4097 if (w > 0 || h > 0) {
4098 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4099 int(w), int(h));
4100 return BAD_VALUE;
4101 }
4102
chaviw13fdc492017-06-27 12:40:18 -07004103 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004104 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004105 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004106 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004107 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004108 // check if buffer size is set for container layer.
4109 if (w > 0 || h > 0) {
4110 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4111 int(w), int(h));
4112 return BAD_VALUE;
4113 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004114 result = createContainerLayer(client,
4115 uniqueName, w, h, flags,
4116 handle, &layer);
4117 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004118 default:
4119 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 break;
4121 }
4122
Dan Stoza7d89d062015-04-30 13:29:25 -07004123 if (result != NO_ERROR) {
4124 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004126
Chia-I Wuab0c3192017-08-01 11:29:00 -07004127 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4128 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004129 if (metadata.has(METADATA_WINDOW_TYPE)) {
4130 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4131 if (windowType == 441731) {
4132 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4133 layer->setPrimaryDisplayOnly();
4134 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004135 }
4136
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004137 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004138
Robert Carrb89ea9d2018-12-10 13:01:14 -08004139 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4140 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4141 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004142 if (result != NO_ERROR) {
4143 return result;
4144 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004145 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004146
4147 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004149}
4150
Cody Northropbc755282017-03-31 12:00:08 -06004151String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4152{
4153 bool matchFound = true;
4154 uint32_t dupeCounter = 0;
4155
4156 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4157 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4158
Dan Stoza436ccf32018-06-21 12:10:12 -07004159 // Grab the state lock since we're accessing mCurrentState
4160 Mutex::Autolock lock(mStateLock);
4161
Cody Northropbc755282017-03-31 12:00:08 -06004162 // Loop over layers until we're sure there is no matching name
4163 while (matchFound) {
4164 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004165 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004166 if (layer->getName() == uniqueName) {
4167 matchFound = true;
4168 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4169 }
4170 });
4171 }
4172
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004173 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4174 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004175
4176 return uniqueName;
4177}
4178
Marissa Wallfd668622018-05-10 10:21:13 -07004179status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4180 uint32_t w, uint32_t h, uint32_t flags,
4181 PixelFormat& format, sp<IBinder>* handle,
4182 sp<IGraphicBufferProducer>* gbp,
4183 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004184 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004185 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004186 case PIXEL_FORMAT_TRANSPARENT:
4187 case PIXEL_FORMAT_TRANSLUCENT:
4188 format = PIXEL_FORMAT_RGBA_8888;
4189 break;
4190 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004191 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192 break;
4193 }
4194
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004195 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004196 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004197 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004199 *handle = layer->getHandle();
4200 *gbp = layer->getProducer();
4201 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004202 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004203
Marissa Wallfd668622018-05-10 10:21:13 -07004204 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004205 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004206}
4207
Marissa Wall61c58622018-07-18 10:12:20 -07004208status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4209 uint32_t w, uint32_t h, uint32_t flags,
4210 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004211 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004212 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004213 *handle = layer->getHandle();
4214 *outLayer = layer;
4215
4216 return NO_ERROR;
4217}
4218
chaviw13fdc492017-06-27 12:40:18 -07004219status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004220 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004221 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004222{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004223 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004224 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004225 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004226}
4227
Robert Carr6b3f6c52018-08-13 13:05:17 -07004228status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4229 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4230 sp<IBinder>* handle, sp<Layer>* outLayer)
4231{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004232 *outLayer =
4233 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004234 *handle = (*outLayer)->getHandle();
4235 return NO_ERROR;
4236}
4237
4238
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004239void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004240 mLayersPendingRemoval.add(layer);
4241 mLayersRemoved = true;
4242 setTransactionFlags(eTransactionNeeded);
4243}
4244
Robert Carr695d5282018-12-18 15:27:58 -08004245void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004246{
Robert Carr2e102c92018-10-23 12:11:15 -07004247 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004248 // If a layer has a parent, we allow it to out-live it's handle
4249 // with the idea that the parent holds a reference and will eventually
4250 // be cleaned up. However no one cleans up the top-level so we do so
4251 // here.
4252 if (layer->getParent() == nullptr) {
4253 mCurrentState.layersSortedByZ.remove(layer);
4254 }
4255 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004256 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004257}
4258
Mathias Agopianb60314a2012-04-10 22:09:54 -07004259// ---------------------------------------------------------------------------
4260
Andy McFadden13a082e2012-08-24 10:16:42 -07004261void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004262 const auto display = getDefaultDisplayDeviceLocked();
4263 if (!display) return;
4264
4265 const sp<IBinder> token = display->getDisplayToken().promote();
4266 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004267
Jesse Hall01e29052013-02-19 16:13:35 -08004268 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004269 Vector<ComposerState> state;
4270 Vector<DisplayState> displays;
4271 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004272 d.what = DisplayState::eDisplayProjectionChanged |
4273 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004274 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004275 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004276 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004277 d.frame.makeInvalid();
4278 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004279 d.width = 0;
4280 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004281 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004282 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004283
Dominik Laskowskie9774092018-12-11 10:04:24 -08004284 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004285
Dominik Laskowski83b88212018-12-11 13:34:06 -08004286 const nsecs_t vsyncPeriod = getVsyncPeriod();
4287 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004288
Brian Andersond0010582017-03-07 13:20:31 -08004289 // Use phase of 0 since phase is not known.
4290 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004291 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004292 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004293}
4294
4295void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004296 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004297 postMessageAsync(
4298 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004299}
4300
Dominik Laskowskie9774092018-12-11 10:04:24 -08004301void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302 if (display->isVirtual()) {
4303 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004304 return;
4305 }
4306
Dominik Laskowski075d3172018-05-24 15:50:06 -07004307 const auto displayId = display->getId();
4308 LOG_ALWAYS_FATAL_IF(!displayId);
4309
Dominik Laskowski34157762018-10-31 13:07:19 -07004310 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311
4312 int currentMode = display->getPowerMode();
4313 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004314 return;
4315 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004316
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 display->setPowerMode(mode);
4318
Lloyd Pique4dccc412018-01-22 17:21:36 -08004319 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004320 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004321 }
4322
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004323 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004324 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004325 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004327 mScheduler->onScreenAcquired(mAppConnectionHandle);
4328 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004329 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004330
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004331 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004332 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004333 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004334
4335 struct sched_param param = {0};
4336 param.sched_priority = 1;
4337 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4338 ALOGW("Couldn't set SCHED_FIFO on display on");
4339 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004340 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004341 // Turn off the display
4342 struct sched_param param = {0};
4343 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4344 ALOGW("Couldn't set SCHED_OTHER on display off");
4345 }
4346
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004347 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004348 mScheduler->disableHardwareVsync(true);
4349 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004350 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004351
Dominik Laskowski075d3172018-05-24 15:50:06 -07004352 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004353 mVisibleRegionsDirty = true;
4354 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004355 } else if (mode == HWC_POWER_MODE_DOZE ||
4356 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004357 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004358 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004359 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004360 mScheduler->onScreenAcquired(mAppConnectionHandle);
4361 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004362 }
4363 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4364 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004365 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004366 mScheduler->disableHardwareVsync(true);
4367 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004368 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004369 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004370 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004371 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004372 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004373 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004374
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004375 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004376 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004377 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004378 // Update refresh rate stats.
4379 mRefreshRateStats->setPowerMode(mode);
4380 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004381 }
4382
Dominik Laskowski34157762018-10-31 13:07:19 -07004383 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004384}
4385
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004386void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004387 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004388 const auto display = getDisplayDevice(displayToken);
4389 if (!display) {
4390 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4391 displayToken.get());
4392 } else if (display->isVirtual()) {
4393 ALOGW("Attempt to set power mode %d for virtual display", mode);
4394 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004395 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004396 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004397 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004398}
4399
4400// ---------------------------------------------------------------------------
4401
Dominik Laskowskic2867142019-01-21 11:33:38 -08004402status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4403 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004404 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004405
Mathias Agopianbd115332013-04-18 16:41:04 -07004406 IPCThreadState* ipc = IPCThreadState::self();
4407 const int pid = ipc->getCallingPid();
4408 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004409
Mathias Agopianbd115332013-04-18 16:41:04 -07004410 if ((uid != AID_SHELL) &&
4411 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004412 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4413 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004414 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004415 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004416 // (this would indicate SF is stuck, but we want to be able to
4417 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004418 status_t err = mStateLock.timedLock(s2ns(1));
4419 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004420 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004421 StringAppendF(&result,
4422 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4423 "(no locks held)\n",
4424 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004425 }
4426
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004428
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429 static const std::unordered_map<std::string, Dumper> dumpers = {
4430 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4431 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4432 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004433 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004434 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004435 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004436 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4437 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4439 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4440 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4441 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4442 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4443 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004444 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004445 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4446 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004447
Dominik Laskowskic2867142019-01-21 11:33:38 -08004448 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004449
Dominik Laskowskic2867142019-01-21 11:33:38 -08004450 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4451 (it->second)(args, asProto, result);
4452 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004453 if (asProto) {
4454 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4455 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4456 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004457 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004458 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004459 }
4460
Mathias Agopian9795c422009-08-26 16:36:26 -07004461 if (locked) {
4462 mStateLock.unlock();
4463 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004464 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004466 return NO_ERROR;
4467}
4468
Dominik Laskowskic2867142019-01-21 11:33:38 -08004469void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004470 mCurrentState.traverseInZOrder(
4471 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004472}
4473
Dominik Laskowskic2867142019-01-21 11:33:38 -08004474void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004475 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004476
Dominik Laskowskic2867142019-01-21 11:33:38 -08004477 if (args.size() > 1) {
4478 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004479 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004480 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004481 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004482 }
Robert Carr2047fae2016-11-28 14:09:09 -08004483 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004484 } else {
4485 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004486 }
4487}
4488
Dominik Laskowskic2867142019-01-21 11:33:38 -08004489void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004490 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004491 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004492 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004493 }
Robert Carr2047fae2016-11-28 14:09:09 -08004494 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004495
Svetoslavd85084b2014-03-20 10:28:31 -07004496 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004497}
4498
Dominik Laskowskic2867142019-01-21 11:33:38 -08004499void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4500 mTimeStats->parseArgs(asProto, args, result);
4501}
4502
Jamie Gennis6547ff42013-07-16 20:12:42 -07004503// This should only be called from the main thread. Otherwise it would need
4504// the lock and should use mCurrentState rather than mDrawingState.
4505void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004506 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004507 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004508 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004509
4510 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4511}
4512
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004514 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004515
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004516 if (isLayerTripleBufferingDisabled())
4517 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004518
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4520 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4521 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4522 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4523 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4524 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004525 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004526}
4527
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004528void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004529 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004530 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004531 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004532 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004533
Ana Krulecba13ab32019-02-20 14:14:12 -08004534 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4535 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4536 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004537 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004538}
4539
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4541 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004542 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4543 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004544 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004545 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004547 }
David Sodman4a36e932017-11-07 14:29:47 -08004548 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004549 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004550 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4552 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004553}
4554
Dan Stozae77c7662016-05-13 11:37:28 -07004555void SurfaceFlinger::recordBufferingStats(const char* layerName,
4556 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004557 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4558 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004559 for (const auto& segment : history) {
4560 if (!segment.usedThirdBuffer) {
4561 stats.twoBufferTime += segment.totalTime;
4562 }
4563 if (segment.occupancyAverage < 1.0f) {
4564 stats.doubleBufferedTime += segment.totalTime;
4565 } else if (segment.occupancyAverage < 2.0f) {
4566 stats.tripleBufferedTime += segment.totalTime;
4567 }
4568 ++stats.numSegments;
4569 stats.totalTime += segment.totalTime;
4570 }
4571}
4572
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4574 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004575
4576 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4577 const size_t count = currentLayers.size();
4578 for (size_t i=0 ; i<count ; i++) {
4579 currentLayers[i]->dumpFrameEvents(result);
4580 }
4581}
4582
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004584 result.append("Buffering stats:\n");
4585 result.append(" [Layer name] <Active time> <Two buffer> "
4586 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004587 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004588 typedef std::tuple<std::string, float, float, float> BufferTuple;
4589 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004590 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004591 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004592 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004593 if (stats.numSegments == 0) {
4594 continue;
4595 }
4596 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4597 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4598 stats.totalTime;
4599 float doubleBufferRatio = static_cast<float>(
4600 stats.doubleBufferedTime) / stats.totalTime;
4601 float tripleBufferRatio = static_cast<float>(
4602 stats.tripleBufferedTime) / stats.totalTime;
4603 sorted.insert({activeTime, {name, twoBufferRatio,
4604 doubleBufferRatio, tripleBufferRatio}});
4605 }
4606 for (const auto& sortedPair : sorted) {
4607 float activeTime = sortedPair.first;
4608 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4610 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004611 }
4612 result.append("\n");
4613}
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004616 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004617 const auto displayId = display->getId();
4618 if (!displayId) {
4619 continue;
4620 }
4621 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004622 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004623 continue;
4624 }
4625
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result,
4627 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4628 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004629 uint8_t port;
4630 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004631 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004632 result.append("no identification data\n");
4633 continue;
4634 }
4635
4636 if (!isEdid(data)) {
4637 result.append("unknown identification data: ");
4638 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004640 }
4641 result.append("\n");
4642 continue;
4643 }
4644
4645 const auto edid = parseEdid(data);
4646 if (!edid) {
4647 result.append("invalid EDID: ");
4648 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004650 }
4651 result.append("\n");
4652 continue;
4653 }
4654
Yiwei Zhang5434a782018-12-05 18:06:32 -08004655 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004656 result.append(edid->displayName.data(), edid->displayName.length());
4657 result.append("\"\n");
4658 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004659}
4660
Yiwei Zhang5434a782018-12-05 18:06:32 -08004661void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4662 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4663 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4664 StringAppendF(&result, "DisplayColorSetting: %s\n",
4665 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004666
4667 // TODO: print out if wide-color mode is active or not
4668
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004669 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004670 const auto displayId = display->getId();
4671 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004672 continue;
4673 }
4674
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004676 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004677 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004678 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004679 }
4680
Lloyd Pique32cbe282018-10-19 13:09:22 -07004681 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, " Current color mode: %s (%d)\n",
4683 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004684 }
4685 result.append("\n");
4686}
4687
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004688LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004689 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004690 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4691 const State& state = useDrawing ? mDrawingState : mCurrentState;
4692 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004693 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004694 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004695 });
4696
4697 return layersProto;
4698}
4699
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004700LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4701 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004702 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004703
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004704 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004705 resolution->set_w(displayDevice->getWidth());
4706 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004707
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004708 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004709 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004710
Lloyd Pique32cbe282018-10-19 13:09:22 -07004711 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4712 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4713 layersProto.set_global_transform(displayState.orientation);
4714
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004715 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004716 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004717 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004718 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004719 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004720 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004721 }
4722 });
4723
4724 return layersProto;
4725}
4726
Dominik Laskowskic2867142019-01-21 11:33:38 -08004727void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4728 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004729 Colorizer colorizer(colorize);
4730
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731 // figure out if we're stuck somewhere
4732 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004733 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4735
4736 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004737 * Dump library configuration.
4738 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739
4740 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004741 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004742 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004743 appendSfConfigString(result);
4744 appendUiConfigString(result);
4745 appendGuiConfigString(result);
4746 result.append("\n");
4747
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004748 result.append("\nDisplay identification data:\n");
4749 dumpDisplayIdentificationData(result);
4750
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004751 result.append("\nWide-Color information:\n");
4752 dumpWideColorInfo(result);
4753
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004755 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004757 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004758 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004759
Andy McFadden41d67d72014-04-25 16:58:34 -07004760 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004761 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004762 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004763 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004764 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004765
Dan Stozab90cf072015-03-05 11:05:59 -08004766 dumpStaticScreenStats(result);
4767 result.append("\n");
4768
Yiwei Zhang5434a782018-12-05 18:06:32 -08004769 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004770
Dan Stozae77c7662016-05-13 11:37:28 -07004771 dumpBufferingStats(result);
4772
Andy McFadden4803b742012-09-24 19:07:20 -07004773 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774 * Dump the visible layer list
4775 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4778 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4779 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004780 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004781
Chia-I Wu2f884132018-09-13 15:17:58 -07004782 {
4783 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4784 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004786 result.append("\n");
4787 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004788
4789 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004790 * Dump Display state
4791 */
4792
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004793 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004795 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004796 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004797 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004798 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004799 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004800
4801 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004802 * Dump SurfaceFlinger global state
4803 */
4804
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004805 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004806 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004807 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004809 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004810
Dominik Laskowski075d3172018-05-24 15:50:06 -07004811 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004812 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4813 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004814 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4815 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004816 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result,
4818 " transaction-flags : %08x\n"
4819 " gpu_to_cpu_unsupported : %d\n",
4820 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004821
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004822 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004823 displayId && getHwComposer().isConnected(*displayId)) {
4824 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result,
4826 " refresh-rate : %f fps\n"
4827 " x-dpi : %f\n"
4828 " y-dpi : %f\n",
4829 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4830 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004831 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832
Yiwei Zhang5434a782018-12-05 18:06:32 -08004833 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004834
Dan Stozae22aec72016-08-01 13:20:59 -07004835 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004836 * Tracing state
4837 */
4838 mTracing.dump(result);
4839 result.append("\n");
4840
4841 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004842 * HWC layer minidump
4843 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004844 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004845 const auto displayId = display->getId();
4846 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004847 continue;
4848 }
4849
Yiwei Zhang5434a782018-12-05 18:06:32 -08004850 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004851 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004852 const sp<DisplayDevice> displayDevice = display;
4853 mCurrentState.traverseInZOrder(
4854 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004855 result.append("\n");
4856 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004857
4858 /*
4859 * Dump HWComposer state
4860 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004861 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004862 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004863 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004864 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004865 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004866 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004867
4868 /*
4869 * Dump gralloc state
4870 */
4871 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4872 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004873
4874 /*
4875 * Dump VrFlinger state if in use.
4876 */
4877 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4878 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004880 result.append("\n");
4881 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004882
4883 /**
4884 * Scheduler dump state.
4885 */
Ana Krulecc2870422019-01-29 19:00:58 -08004886 result.append("\nScheduler state:\n");
4887 result.append(mScheduler->doDump() + "\n");
4888 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889}
4890
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004892 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004893 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004894 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004895 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004896 }
4897 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004898
Dominik Laskowski34157762018-10-31 13:07:19 -07004899 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004900 static const Vector<sp<Layer>> empty;
4901 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004902}
4903
Chia-I Wu28f320b2018-05-03 11:02:56 -07004904void SurfaceFlinger::updateColorMatrixLocked() {
4905 mat4 colorMatrix;
4906 if (mGlobalSaturationFactor != 1.0f) {
4907 // Rec.709 luma coefficients
4908 float3 luminance{0.213f, 0.715f, 0.072f};
4909 luminance *= 1.0f - mGlobalSaturationFactor;
4910 mat4 saturationMatrix = mat4(
4911 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4912 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4913 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4914 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4915 );
4916 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4917 } else {
4918 colorMatrix = mClientColorMatrix * mDaltonizer();
4919 }
4920
4921 if (mCurrentState.colorMatrix != colorMatrix) {
4922 mCurrentState.colorMatrix = colorMatrix;
4923 mCurrentState.colorMatrixChanged = true;
4924 setTransactionFlags(eTransactionNeeded);
4925 }
4926}
4927
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004928status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004929#pragma clang diagnostic push
4930#pragma clang diagnostic error "-Wswitch-enum"
4931 switch (static_cast<ISurfaceComposerTag>(code)) {
4932 // These methods should at minimum make sure that the client requested
4933 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004934 case BOOT_FINISHED:
4935 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 case CREATE_DISPLAY:
4937 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004938 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 case GET_ACTIVE_COLOR_MODE:
4940 case GET_ANIMATION_FRAME_STATS:
4941 case GET_HDR_CAPABILITIES:
4942 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004943 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004944 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004945 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004946 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004947 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004948 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004949 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4950 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004951 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4952 IPCThreadState* ipc = IPCThreadState::self();
4953 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4954 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004955 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004956 }
Robert Carr1db73f62016-12-21 12:58:51 -08004957 return OK;
4958 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004959 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004960 IPCThreadState* ipc = IPCThreadState::self();
4961 const int pid = ipc->getCallingPid();
4962 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004963 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4964 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004965 return PERMISSION_DENIED;
4966 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004968 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004969 // Used by apps to hook Choreographer to SurfaceFlinger.
4970 case CREATE_DISPLAY_EVENT_CONNECTION:
4971 // The following calls are currently used by clients that do not
4972 // request necessary permissions. However, they do not expose any secret
4973 // information, so it is OK to pass them.
4974 case AUTHENTICATE_SURFACE:
4975 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004976 case GET_PHYSICAL_DISPLAY_IDS:
4977 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004978 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004979 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004980 case GET_DISPLAY_CONFIGS:
4981 case GET_DISPLAY_STATS:
4982 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4983 // Calling setTransactionState is safe, because you need to have been
4984 // granted a reference to Client* and Handle* to do anything with it.
4985 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004986 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004987 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004988 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004989 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004990 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991 return OK;
4992 }
4993 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004994 case CAPTURE_SCREEN:
4995 case ADD_REGION_SAMPLING_LISTENER:
4996 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004997 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004998 IPCThreadState* ipc = IPCThreadState::self();
4999 const int pid = ipc->getCallingPid();
5000 const int uid = ipc->getCallingUid();
5001 if ((uid != AID_GRAPHICS) &&
5002 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5003 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5004 return PERMISSION_DENIED;
5005 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005006 return OK;
5007 }
5008 // The following codes are deprecated and should never be allowed to access SF.
5009 case CONNECT_DISPLAY_UNUSED:
5010 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5011 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5012 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005013 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005014 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005015
5016 // These codes are used for the IBinder protocol to either interrogate the recipient
5017 // side of the transaction for its canonical interface descriptor or to dump its state.
5018 // We let them pass by default.
5019 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5020 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5021 code == IBinder::SYSPROPS_TRANSACTION) {
5022 return OK;
5023 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005024 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005025 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005026 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005027 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5028 return OK;
5029 }
5030 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5031 return PERMISSION_DENIED;
5032#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005033}
5034
Ana Krulec13be8ad2018-08-21 02:43:56 +00005035status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5036 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005037 status_t credentialCheck = CheckTransactCodeCredentials(code);
5038 if (credentialCheck != OK) {
5039 return credentialCheck;
5040 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005042 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5043 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005044 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005045 IPCThreadState* ipc = IPCThreadState::self();
5046 const int uid = ipc->getCallingUid();
5047 if (CC_UNLIKELY(uid != AID_SYSTEM
5048 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005049 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005050 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005051 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005052 return PERMISSION_DENIED;
5053 }
5054 int n;
5055 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005056 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005057 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005058 return NO_ERROR;
5059 case 1002: // SHOW_UPDATES
5060 n = data.readInt32();
5061 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005062 invalidateHwcGeometry();
5063 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005064 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005066 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005067 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005068 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005069 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005070 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005071 setTransactionFlags(
5072 eTransactionNeeded|
5073 eDisplayTransactionNeeded|
5074 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005075 return NO_ERROR;
5076 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005077 case 1006:{ // send empty update
5078 signalRefresh();
5079 return NO_ERROR;
5080 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005081 case 1008: // toggle use of hw composer
5082 n = data.readInt32();
5083 mDebugDisableHWC = n ? 1 : 0;
5084 invalidateHwcGeometry();
5085 repaintEverything();
5086 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005087 case 1009: // toggle use of transform hint
5088 n = data.readInt32();
5089 mDebugDisableTransformHint = n ? 1 : 0;
5090 invalidateHwcGeometry();
5091 repaintEverything();
5092 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005093 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005094 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005095 reply->writeInt32(0);
5096 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005097 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005098 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005099 return NO_ERROR;
5100 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005101 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005102 if (!display) {
5103 return NAME_NOT_FOUND;
5104 }
5105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005106 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005107 return NO_ERROR;
5108 }
5109 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005110 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005111 // daltonize
5112 n = data.readInt32();
5113 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005114 case 1:
5115 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5116 break;
5117 case 2:
5118 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5119 break;
5120 case 3:
5121 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5122 break;
5123 default:
5124 mDaltonizer.setType(ColorBlindnessType::None);
5125 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005126 }
5127 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005128 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005129 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005130 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005131 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005132
5133 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005134 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005135 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005136 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005137 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005138 // apply a color matrix
5139 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005140 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005141 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005142 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005143 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005144 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005145 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005146 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005147 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005148 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005149 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005150
5151 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5152 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005153 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005154 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5155 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5156 }
5157
Chia-I Wu28f320b2018-05-03 11:02:56 -07005158 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005159 return NO_ERROR;
5160 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005161 // This is an experimental interface
5162 // Needs to be shifted to proper binder interface when we productize
5163 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005164 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005165 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005166 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005167 return NO_ERROR;
5168 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005169 case 1017: {
5170 n = data.readInt32();
5171 mForceFullDamage = static_cast<bool>(n);
5172 return NO_ERROR;
5173 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005174 case 1018: { // Modify Choreographer's phase offset
5175 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005176 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005177 return NO_ERROR;
5178 }
5179 case 1019: { // Modify SurfaceFlinger's phase offset
5180 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005181 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005182 return NO_ERROR;
5183 }
Irvel468051e2016-06-13 16:44:44 -07005184 case 1020: { // Layer updates interceptor
5185 n = data.readInt32();
5186 if (n) {
5187 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005188 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005189 }
5190 else{
5191 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005192 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005193 }
5194 return NO_ERROR;
5195 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005196 case 1021: { // Disable HWC virtual displays
5197 n = data.readInt32();
5198 mUseHwcVirtualDisplays = !n;
5199 return NO_ERROR;
5200 }
Romain Guy0147a172017-06-01 13:53:56 -07005201 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005202 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005203 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005204
Chia-I Wu28f320b2018-05-03 11:02:56 -07005205 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005206 return NO_ERROR;
5207 }
Romain Guy54f154a2017-10-24 21:40:32 +01005208 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005209 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005210 invalidateHwcGeometry();
5211 repaintEverything();
5212 return NO_ERROR;
5213 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005214 // Deprecate, use 1030 to check whether the device is color managed.
5215 case 1024: {
5216 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005217 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005218 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005219 n = data.readInt32();
5220 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005221 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005222 mTracing.enable();
5223 doTracing("tracing.enable");
5224 reply->writeInt32(NO_ERROR);
5225 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005226 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005227 status_t err = mTracing.disable();
5228 reply->writeInt32(err);
5229 }
5230 return NO_ERROR;
5231 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005232 case 1026: { // Get layer tracing status
5233 reply->writeBool(mTracing.isEnabled());
5234 return NO_ERROR;
5235 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005236 // Is a DisplayColorSetting supported?
5237 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005238 const auto display = getDefaultDisplayDevice();
5239 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005240 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005241 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005242
5243 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5244 switch (setting) {
5245 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005246 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005247 break;
5248 case DisplayColorSetting::UNMANAGED:
5249 reply->writeBool(true);
5250 break;
5251 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005252 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005253 break;
5254 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005255 reply->writeBool(
5256 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005257 break;
5258 }
5259 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005260 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005261 // Is VrFlinger active?
5262 case 1028: {
5263 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005264 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005265 return NO_ERROR;
5266 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005267 // Is device color managed?
5268 case 1030: {
5269 reply->writeBool(useColorManagement);
5270 return NO_ERROR;
5271 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005272 // Override default composition data space
5273 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5274 // && adb shell stop zygote && adb shell start zygote
5275 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5276 // adb shell stop zygote && adb shell start zygote
5277 case 1031: {
5278 Mutex::Autolock _l(mStateLock);
5279 n = data.readInt32();
5280 if (n) {
5281 n = data.readInt32();
5282 if (n) {
5283 Dataspace dataspace = static_cast<Dataspace>(n);
5284 if (!validateCompositionDataspace(dataspace)) {
5285 return BAD_VALUE;
5286 }
5287 mDefaultCompositionDataspace = dataspace;
5288 }
5289 n = data.readInt32();
5290 if (n) {
5291 Dataspace dataspace = static_cast<Dataspace>(n);
5292 if (!validateCompositionDataspace(dataspace)) {
5293 return BAD_VALUE;
5294 }
5295 mWideColorGamutCompositionDataspace = dataspace;
5296 }
5297 } else {
5298 // restore composition data space.
5299 mDefaultCompositionDataspace = defaultCompositionDataspace;
5300 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5301 }
5302 return NO_ERROR;
5303 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005304 }
5305 }
5306 return err;
5307}
5308
Steven Thomas6d8110b2017-08-31 18:24:21 -07005309void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005310 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005311 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005312}
5313
Ana Krulec7d1d6832018-12-27 11:10:09 -08005314void SurfaceFlinger::repaintEverythingForHWC() {
5315 mRepaintEverything = true;
5316 mEventQueue->invalidateForHWC();
5317}
5318
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005319// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5320class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005321public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005322 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5323 ~WindowDisconnector() {
5324 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005325 }
5326
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005327private:
5328 ANativeWindow* mWindow;
5329 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005330};
5331
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005332status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005333 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5334 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005335 uint32_t reqWidth, uint32_t reqHeight,
5336 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005337 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005338 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005339
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005340 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005341
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005342 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5343
Chia-I Wu20261cb2018-08-23 12:55:44 -07005344 sp<DisplayDevice> display;
5345 {
5346 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005347
Chia-I Wu20261cb2018-08-23 12:55:44 -07005348 display = getDisplayDeviceLocked(displayToken);
5349 if (!display) return BAD_VALUE;
5350
Chia-I Wucb023152018-08-28 12:57:23 -07005351 // set the requested width/height to the logical display viewport size
5352 // by default
5353 if (reqWidth == 0 || reqHeight == 0) {
5354 reqWidth = uint32_t(display->getViewport().width());
5355 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005356 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005357 }
5358
Peiyong Lin0e003c92018-09-17 11:09:51 -07005359 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5360 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005361
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005362 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5363 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005364 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5365 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005366}
5367
5368status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005369 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5370 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005371 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005372 ATRACE_CALL();
5373
5374 class LayerRenderArea : public RenderArea {
5375 public:
Robert Carr578038f2018-03-09 12:25:24 -08005376 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005377 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5378 bool childrenOnly)
5379 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005380 mLayer(layer),
5381 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005382 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005383 mFlinger(flinger),
5384 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005385 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005386 Rect getBounds() const override {
5387 const Layer::State& layerState(mLayer->getDrawingState());
5388 return mLayer->getBufferSize(layerState);
5389 }
Marissa Wall61c58622018-07-18 10:12:20 -07005390 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005391 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005392 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005393 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005394 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005395 }
chaviwa76b2712017-09-20 12:02:26 -07005396 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005397 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005398 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005399 Rect getSourceCrop() const override {
5400 if (mCrop.isEmpty()) {
5401 return getBounds();
5402 } else {
5403 return mCrop;
5404 }
5405 }
Robert Carr578038f2018-03-09 12:25:24 -08005406 class ReparentForDrawing {
5407 public:
5408 const sp<Layer>& oldParent;
5409 const sp<Layer>& newParent;
5410
Vishnu Nair4351ad52019-02-11 14:13:02 -08005411 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5412 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005413 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005414 // Compute and cache the bounds for the new parent layer.
5415 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005416 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005417 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005418 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005419 };
5420
5421 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005422 const Rect sourceCrop = getSourceCrop();
5423 // no need to check rotation because there is none
5424 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5425 sourceCrop.height() != getReqHeight();
5426
Robert Carr578038f2018-03-09 12:25:24 -08005427 if (!mChildrenOnly) {
5428 mTransform = mLayer->getTransform().inverse();
5429 drawLayers();
5430 } else {
5431 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005432 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005433 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5434 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005435
Vishnu Nair4351ad52019-02-11 14:13:02 -08005436 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005437 drawLayers();
5438 }
5439 }
chaviwa76b2712017-09-20 12:02:26 -07005440
chaviwa76b2712017-09-20 12:02:26 -07005441 private:
chaviw7206d492017-11-10 16:16:12 -08005442 const sp<Layer> mLayer;
5443 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005444
5445 // In the "childrenOnly" case we reparent the children to a screenshot
5446 // layer which has no properties set and which does not draw.
5447 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005448 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005449 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005450
5451 SurfaceFlinger* mFlinger;
5452 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005453 };
5454
5455 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5456 auto parent = layerHandle->owner.promote();
5457
Robert Carr2e102c92018-10-23 12:11:15 -07005458 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005459 ALOGE("captureLayers called with a removed parent");
5460 return NAME_NOT_FOUND;
5461 }
5462
Robert Carr578038f2018-03-09 12:25:24 -08005463 const int uid = IPCThreadState::self()->getCallingUid();
5464 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005465 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005466 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5467 return PERMISSION_DENIED;
5468 }
5469
chaviw7206d492017-11-10 16:16:12 -08005470 Rect crop(sourceCrop);
5471 if (sourceCrop.width() <= 0) {
5472 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005473 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005474 }
5475
5476 if (sourceCrop.height() <= 0) {
5477 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005479 }
5480
5481 int32_t reqWidth = crop.width() * frameScale;
5482 int32_t reqHeight = crop.height() * frameScale;
5483
Chia-I Wu20261cb2018-08-23 12:55:44 -07005484 // really small crop or frameScale
5485 if (reqWidth <= 0) {
5486 reqWidth = 1;
5487 }
5488 if (reqHeight <= 0) {
5489 reqHeight = 1;
5490 }
5491
Peiyong Lin0e003c92018-09-17 11:09:51 -07005492 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005493
Robert Carr578038f2018-03-09 12:25:24 -08005494 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005495 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5496 if (!layer->isVisible()) {
5497 return;
Robert Carr578038f2018-03-09 12:25:24 -08005498 } else if (childrenOnly && layer == parent.get()) {
5499 return;
chaviwa76b2712017-09-20 12:02:26 -07005500 }
5501 visitor(layer);
5502 });
5503 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005504 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005505}
5506
5507status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5508 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005509 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005510 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005511 bool useIdentityTransform) {
5512 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005513
Peiyong Lin0e003c92018-09-17 11:09:51 -07005514 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005515 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5516 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005517 *outBuffer =
5518 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5519 static_cast<android_pixel_format>(reqPixelFormat), 1,
5520 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005521
Dan Stozaec460082018-12-17 15:35:09 -08005522 return captureScreenCore(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
5523}
5524
5525status_t SurfaceFlinger::captureScreenCore(RenderArea& renderArea,
5526 TraverseLayersFunction traverseLayers,
5527 const sp<GraphicBuffer>& buffer,
5528 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005529 // This mutex protects syncFd and captureResult for communication of the return values from the
5530 // main thread back to this Binder thread
5531 std::mutex captureMutex;
5532 std::condition_variable captureCondition;
5533 std::unique_lock<std::mutex> captureLock(captureMutex);
5534 int syncFd = -1;
5535 std::optional<status_t> captureResult;
5536
Robert Carr03480e22018-01-04 16:02:06 -08005537 const int uid = IPCThreadState::self()->getCallingUid();
5538 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5539
Dominik Laskowski8c001672018-05-30 16:52:06 -07005540 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005541 // If there is a refresh pending, bug out early and tell the binder thread to try again
5542 // after the refresh.
5543 if (mRefreshPending) {
5544 ATRACE_NAME("Skipping screenshot for now");
5545 std::unique_lock<std::mutex> captureLock(captureMutex);
5546 captureResult = std::make_optional<status_t>(EAGAIN);
5547 captureCondition.notify_one();
5548 return;
5549 }
5550
5551 status_t result = NO_ERROR;
5552 int fd = -1;
5553 {
5554 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005555 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005556 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005557 useIdentityTransform, forSystem, &fd);
5558 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005559 }
5560
5561 {
5562 std::unique_lock<std::mutex> captureLock(captureMutex);
5563 syncFd = fd;
5564 captureResult = std::make_optional<status_t>(result);
5565 captureCondition.notify_one();
5566 }
5567 });
5568
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005569 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005570 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005571 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005572 while (*captureResult == EAGAIN) {
5573 captureResult.reset();
5574 result = postMessageAsync(message);
5575 if (result != NO_ERROR) {
5576 return result;
5577 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005578 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005579 }
5580 result = *captureResult;
5581 }
5582
5583 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005584 sync_wait(syncFd, -1);
5585 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005586 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005587
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005588 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005589}
5590
chaviwa76b2712017-09-20 12:02:26 -07005591void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005592 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005593 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5594 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005595 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005596
chaviwa76b2712017-09-20 12:02:26 -07005597 const auto reqWidth = renderArea.getReqWidth();
5598 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005599 const auto sourceCrop = renderArea.getSourceCrop();
5600 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005601
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005602 renderengine::DisplaySettings clientCompositionDisplay;
5603 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005604
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005605 // assume that bounds are never offset, and that they are the same as the
5606 // buffer bounds.
5607 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5608 ui::Transform transform = renderArea.getTransform();
5609 mat4 m;
5610 m[0][0] = transform[0][0];
5611 m[0][1] = transform[0][1];
5612 m[0][3] = transform[0][2];
5613 m[1][0] = transform[1][0];
5614 m[1][1] = transform[1][1];
5615 m[1][3] = transform[1][2];
5616 m[3][0] = transform[2][0];
5617 m[3][1] = transform[2][1];
5618 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005619
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005620 clientCompositionDisplay.globalTransform = m;
5621 mat4 rotMatrix;
5622 // Displacement for repositioning the clipping rectangle after rotating it
5623 // with the rotation hint.
5624 int displacementX = 0;
5625 int displacementY = 0;
5626 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5627 switch (rotation) {
5628 case ui::Transform::ROT_90:
5629 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5630 displacementX = reqWidth;
5631 break;
5632 case ui::Transform::ROT_180:
5633 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5634 displacementX = reqWidth;
5635 displacementY = reqHeight;
5636 break;
5637 case ui::Transform::ROT_270:
5638 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5639 displacementY = reqHeight;
5640 break;
5641 default:
5642 break;
5643 }
5644 // We need to transform the clipping window into the right spot.
5645 // First, rotate the clipping rectangle by the rotation hint to get the
5646 // right orientation
5647 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5648 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5649 const vec4 rotClipTL = rotMatrix * clipTL;
5650 const vec4 rotClipBR = rotMatrix * clipBR;
5651 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5652 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5653 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5654 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5655
5656 // Now reposition the clipping rectangle with the displacement vector
5657 // computed above.
5658 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5659
5660 clientCompositionDisplay.clip =
5661 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5662 newClipRight + displacementX, newClipBottom + displacementY);
5663
5664 // We need to perform the same transformation in layer space, so propagate
5665 // it to the global transform.
5666 mat4 clipTransform = displacementMat * rotMatrix;
5667 clientCompositionDisplay.globalTransform *= clipTransform;
5668 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5669 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005670
chaviw50da5042018-04-09 13:49:37 -07005671 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005672
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005673 renderengine::LayerSettings fillLayer;
5674 fillLayer.source.buffer.buffer = nullptr;
5675 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5676 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5677 fillLayer.alpha = half(alpha);
5678 clientCompositionLayers.push_back(fillLayer);
5679
5680 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005681 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005682 renderengine::LayerSettings layerSettings;
5683 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5684 layerSettings);
5685 if (prepared) {
5686 clientCompositionLayers.push_back(layerSettings);
5687 }
chaviwa76b2712017-09-20 12:02:26 -07005688 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005689
5690 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005691 // Use an empty fence for the buffer fence, since we just created the buffer so
5692 // there is no need for synchronization with the GPU.
5693 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694 base::unique_fd drawFence;
5695 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005696 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005697
5698 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005699}
5700
chaviwa76b2712017-09-20 12:02:26 -07005701status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5702 TraverseLayersFunction traverseLayers,
5703 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005704 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005705 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005706 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005707 ATRACE_CALL();
5708
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005709 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005710
5711 traverseLayers([&](Layer* layer) {
5712 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5713 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005714
Robert Carr03480e22018-01-04 16:02:06 -08005715 // We allow the system server to take screenshots of secure layers for
5716 // use in situations like the Screen-rotation animation and place
5717 // the impetus on WindowManager to not persist them.
5718 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005719 ALOGW("FB is protected: PERMISSION_DENIED");
5720 return PERMISSION_DENIED;
5721 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005722 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005723 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005724}
5725
chaviw95ef3c42019-02-14 10:55:09 -08005726void SurfaceFlinger::setInputWindowsFinished() {
5727 Mutex::Autolock _l(mStateLock);
5728
5729 mPendingSyncInputWindows = false;
5730 mTransactionCV.broadcast();
5731}
chaviw5f21a5e2019-02-14 10:00:34 -08005732
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005733// ---------------------------------------------------------------------------
5734
Dan Stoza412903f2017-04-27 13:42:17 -07005735void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5736 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005737}
5738
Dan Stoza412903f2017-04-27 13:42:17 -07005739void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5740 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005741}
5742
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005743void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005744 const LayerVector::Visitor& visitor) {
5745 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005746 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005747 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005748 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005749 continue;
5750 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005751 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005752 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005753 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005754 return;
5755 }
chaviwa76b2712017-09-20 12:02:26 -07005756 if (!layer->isVisible()) {
5757 return;
5758 }
5759 visitor(layer);
5760 });
5761 }
5762}
5763
Ady Abraham838de062019-02-04 10:24:03 -08005764void SurfaceFlinger::setAllowedDisplayConfigsInternal(
5765 const android::sp<android::IBinder>& displayToken,
5766 std::unique_ptr<const AllowedDisplayConfigs>&& allowedConfigs) {
5767 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5768 if (!displayId) {
5769 ALOGE("setAllowedDisplayConfigsInternal: getPhysicalDisplayId failed");
5770 return;
5771 }
5772
5773 ALOGV("Updating allowed configs");
5774 {
5775 std::lock_guard lock(mAllowedConfigsLock);
5776 mAllowedConfigs[*displayId] = std::move(allowedConfigs);
5777 }
5778
5779 // make sure that the current config is still allowed
5780 int currentConfigIndex = getHwComposer().getActiveConfigIndex(*displayId);
5781 if (!isConfigAllowed(*displayId, currentConfigIndex)) {
5782 // TODO(b/122906558): stop querying HWC for the available configs and instead use the cached
5783 // configs queried on boot
5784 auto configs = getHwComposer().getConfigs(*displayId);
5785
5786 for (int i = 0; i < configs.size(); i++) {
5787 if (isConfigAllowed(*displayId, i)) {
5788 // TODO: we switch to the first allowed config. In the future
5789 // we may want to enhance this logic to pick a similar config
5790 // to the current one
5791 ALOGV("Old config is not allowed - switching to config %d", i);
Ady Abraham447052e2019-02-13 16:07:27 -08005792 setDesiredActiveConfig(displayToken, i, ConfigEvent::Changed);
Ady Abraham838de062019-02-04 10:24:03 -08005793 break;
5794 }
5795 }
5796 }
5797}
5798
5799status_t SurfaceFlinger::setAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5800 const std::vector<int32_t>& allowedConfigs) {
5801 ATRACE_CALL();
5802
5803 if (!displayToken) {
5804 ALOGE("setAllowedDisplayConfigs: displayToken is null");
5805 return BAD_VALUE;
5806 }
5807
5808 if (!allowedConfigs.size()) {
5809 ALOGE("setAllowedDisplayConfigs: empty config set provided");
5810 return BAD_VALUE;
5811 }
5812
5813 {
5814 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5815 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5816 if (!displayId) {
5817 ALOGE("setAllowedDisplayConfigs: display not found");
5818 return NAME_NOT_FOUND;
5819 }
5820 }
5821
5822 auto allowedDisplayConfigsBuilder = AllowedDisplayConfigs::Builder();
5823 for (int config : allowedConfigs) {
5824 ALOGV("setAllowedDisplayConfigs: Adding config to the allowed configs = %d", config);
5825 allowedDisplayConfigsBuilder.addConfig(config);
5826 }
5827 auto allowedDisplayConfigs = allowedDisplayConfigsBuilder.build();
5828 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
5829 setAllowedDisplayConfigsInternal(displayToken, std::move(allowedDisplayConfigs));
5830 }));
5831 return NO_ERROR;
5832}
5833
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005834status_t SurfaceFlinger::getAllowedDisplayConfigs(const android::sp<android::IBinder>& displayToken,
5835 std::vector<int32_t>* outAllowedConfigs) {
5836 ATRACE_CALL();
5837
5838 if (!displayToken) {
5839 ALOGE("getAllowedDisplayConfigs: displayToken is null");
5840 return BAD_VALUE;
5841 }
5842
5843 if (!outAllowedConfigs) {
5844 ALOGE("getAllowedDisplayConfigs: outAllowedConfigs is null");
5845 return BAD_VALUE;
5846 }
5847
5848 ConditionalLock stateLock(mStateLock, std::this_thread::get_id() != mMainThreadId);
5849 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
5850 if (!displayId) {
5851 ALOGE("getAllowedDisplayConfigs: display not found");
5852 return NAME_NOT_FOUND;
5853 }
5854
5855 std::lock_guard allowedConfigLock(mAllowedConfigsLock);
5856 auto allowedConfigIterator = mAllowedConfigs.find(displayId.value());
5857 if (allowedConfigIterator != mAllowedConfigs.end()) {
5858 allowedConfigIterator->second->getAllowedConfigs(outAllowedConfigs);
5859 }
5860
5861 return NO_ERROR;
5862}
5863
chaviw291d88a2019-02-14 10:33:58 -08005864// ----------------------------------------------------------------------------
5865
5866void SetInputWindowsListener::onSetInputWindowsFinished() {
5867 mFlinger->setInputWindowsFinished();
5868}
5869
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005870}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005871
Lloyd Pique074e8122018-07-26 12:57:23 -07005872
Mathias Agopian3f844832013-08-07 21:24:32 -07005873#if defined(__gl_h_)
5874#error "don't include gl/gl.h in this file"
5875#endif
5876
5877#if defined(__gl2_h_)
5878#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005879#endif