blob: bf17d50b372ae1987a1aed847c8358b5f1ce594f [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 Krulec757f63a2019-01-25 10:46:18 -0800401 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
402 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700403
Romain Guy11d63f42017-07-20 12:47:14 -0700404 // We should be reading 'persist.sys.sf.color_saturation' here
405 // but since /data may be encrypted, we need to wait until after vold
406 // comes online to attempt to read the property. The property is
407 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800408
409 if (useTrebleTestingOverride()) {
410 // Without the override SurfaceFlinger cannot connect to HIDL
411 // services that are not listed in the manifests. Considered
412 // deriving the setting from the set service name, but it
413 // would be brittle if the name that's not 'default' is used
414 // for production purposes later on.
415 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
416 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800417}
418
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419void SurfaceFlinger::onFirstRef()
420{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800421 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422}
423
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424SurfaceFlinger::~SurfaceFlinger()
425{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426}
427
Dan Stozac7014012014-02-14 15:03:43 -0800428void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429{
430 // the window manager died on us. prepare its eulogy.
431
Andy McFadden13a082e2012-08-24 10:16:42 -0700432 // restore initial conditions (default device unblank, etc)
433 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434
435 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700436 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437}
438
Robert Carr1db73f62016-12-21 12:58:51 -0800439static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700440 status_t err = client->initCheck();
441 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800443 }
Robert Carr1db73f62016-12-21 12:58:51 -0800444 return nullptr;
445}
446
447sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
448 return initClient(new Client(this));
449}
450
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700451sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
452 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453{
454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 // Display ID is assigned when virtual display is allocated by HWC.
472 DisplayDeviceState state;
473 state.isSecure = secure;
474 state.displayName = displayName;
475 mCurrentState.displays.add(token, state);
476 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 Mutex::Autolock _l(mStateLock);
482
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
484 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
490 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 ALOGE("destroyDisplay called for non-virtual display");
492 return;
493 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 mInterceptor->saveDisplayDeletion(state.sequenceId);
495 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
500 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800502 const auto internalDisplayId = getInternalDisplayIdLocked();
503 if (!internalDisplayId) {
504 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700505 }
506
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800507 std::vector<PhysicalDisplayId> displayIds;
508 displayIds.reserve(mPhysicalDisplayTokens.size());
509 displayIds.push_back(internalDisplayId->value);
510
511 for (const auto& [id, token] : mPhysicalDisplayTokens) {
512 if (id != *internalDisplayId) {
513 displayIds.push_back(id.value);
514 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700515 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700516
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800517 return displayIds;
518}
519
520sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
521 Mutex::Autolock lock(mStateLock);
522 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700523}
524
Ady Abraham37965d42018-11-01 13:43:32 -0700525status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
526 if (!outGetColorManagement) {
527 return BAD_VALUE;
528 }
529 *outGetColorManagement = useColorManagement;
530 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700531}
532
Lloyd Pique441d5042018-10-18 16:49:51 -0700533HWComposer& SurfaceFlinger::getHwComposer() const {
534 return mCompositionEngine->getHwComposer();
535}
536
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700537renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
538 return mCompositionEngine->getRenderEngine();
539}
540
Lloyd Pique70d91362018-10-18 16:02:55 -0700541compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
542 return *mCompositionEngine.get();
543}
544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545void SurfaceFlinger::bootFinished()
546{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700547 if (mStartPropertySetThread->join() != NO_ERROR) {
548 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800549 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550 const nsecs_t now = systemTime();
551 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000552 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700553
554 // wait patiently for the window manager death
555 const String16 name("window");
556 sp<IBinder> window(defaultServiceManager()->getService(name));
557 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700558 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 }
Robert Carr720e5062018-07-30 17:45:14 -0700560 sp<IBinder> input(defaultServiceManager()->getService(
561 String16("inputflinger")));
562 if (input == nullptr) {
563 ALOGE("Failed to link to input service");
564 } else {
565 mInputFlinger = interface_cast<IInputFlinger>(input);
566 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567
Steven Thomas050b2c82017-03-06 11:45:16 -0800568 if (mVrFlinger) {
569 mVrFlinger->OnBootFinished();
570 }
571
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700573 // formerly we would just kill the process, but we now ask it to exit so it
574 // can choose where to stop the animation.
575 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700576
577 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
578 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
579 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700580
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800581 postMessageAsync(new LambdaMessage([this] {
582 readPersistentProperties();
583 mBootStage = BootStage::FINISHED;
584 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585}
586
Dan Stoza436ccf32018-06-21 12:10:12 -0700587uint32_t SurfaceFlinger::getNewTexture() {
588 {
589 std::lock_guard lock(mTexturePoolMutex);
590 if (!mTexturePool.empty()) {
591 uint32_t name = mTexturePool.back();
592 mTexturePool.pop_back();
593 ATRACE_INT("TexturePoolSize", mTexturePool.size());
594 return name;
595 }
596
597 // The pool was too small, so increase it for the future
598 ++mTexturePoolSize;
599 }
600
601 // The pool was empty, so we need to get a new texture name directly using a
602 // blocking call to the main thread
603 uint32_t name = 0;
604 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
605 return name;
606}
607
Mathias Agopian3f844832013-08-07 21:24:32 -0700608void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700609 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
617
Ana Krulec757f63a2019-01-25 10:46:18 -0800618 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800622 mScheduler =
623 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
624 auto resyncCallback =
625 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800626
Ana Krulecc2870422019-01-29 19:00:58 -0800627 mAppConnectionHandle =
628 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
629 resyncCallback,
630 impl::EventThread::InterceptVSyncsCallback());
631 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
632 resyncCallback, [this](nsecs_t timestamp) {
633 mInterceptor->saveVSyncEvent(timestamp);
634 });
635
636 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
637 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
638 mSfConnectionHandle.get());
639
640 if (mUse90Hz) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800641 mPhaseOffsets->setRefreshRateType(
642 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Ana Krulec98b5b242018-08-10 15:03:23 -0700643 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800644
Steven Thomasb02664d2017-07-26 18:48:28 -0700645 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700646 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700647 renderEngineFeature |= (useColorManagement ?
648 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700649 renderEngineFeature |= (useContextPriority ?
650 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700651
652 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700653 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700654 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700655 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700656
657 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
658 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700659 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
660 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800661 // Process any initial hotplug and resulting display changes.
662 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 const auto display = getDefaultDisplayDeviceLocked();
664 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700665 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800667
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700669 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700670 // This callback is called from the vr flinger dispatch thread. We
671 // need to call signalTransaction(), which requires holding
672 // mStateLock when we're not on the main thread. Acquiring
673 // mStateLock from the vr flinger dispatch thread might trigger a
674 // deadlock in surface flinger (see b/66916578), so post a message
675 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700676 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700677 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
678 mVrFlingerRequestsDisplay = requestDisplay;
679 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800681 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
683 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 .value_or(0),
686 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (!mVrFlinger) {
688 ALOGE("Failed to start vrflinger");
689 }
690 }
691
Mathias Agopian92a979a2012-08-02 18:32:23 -0700692 // initialize our drawing state
693 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700694
Andy McFadden13a082e2012-08-24 10:16:42 -0700695 // set initial conditions (e.g. unblank default device)
696 initializeDisplays();
697
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700698 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700699
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700701
702 const bool presentFenceReliable =
703 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
704 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705
706 if (mStartPropertySetThread->Start() != NO_ERROR) {
707 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800709
Ana Krulecc2870422019-01-29 19:00:58 -0800710 mScheduler->setExpiredIdleTimerCallback([this] {
711 Mutex::Autolock lock(mStateLock);
712 setRefreshRateTo(RefreshRateType::DEFAULT);
713 });
714 mScheduler->setResetIdleTimerCallback([this] {
715 Mutex::Autolock lock(mStateLock);
716 setRefreshRateTo(RefreshRateType::PERFORMANCE);
717 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800718
Ana Krulecc2870422019-01-29 19:00:58 -0800719 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
720 *display->getId()),
721 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700724}
725
Romain Guy11d63f42017-07-20 12:47:14 -0700726void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700727 Mutex::Autolock _l(mStateLock);
728
Romain Guy11d63f42017-07-20 12:47:14 -0700729 char value[PROPERTY_VALUE_MAX];
730
731 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800734 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100735
736 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700737 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800738
739 property_get("persist.sys.sf.color_mode", value, "0");
740 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700741}
742
Mathias Agopiana67e4182012-06-19 17:26:12 -0700743void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800744 // Start boot animation service by setting a property mailbox
745 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800747 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700748 if (mStartPropertySetThread->join() != NO_ERROR) {
749 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751}
752
Mathias Agopian875d8e12013-06-07 15:35:48 -0700753size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700754 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700755}
756
Mathias Agopian875d8e12013-06-07 15:35:48 -0700757size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700758 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700759}
760
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800761// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800762
Jamie Gennis582270d2011-08-17 18:19:00 -0700763bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800764 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800765 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800766 return authenticateSurfaceTextureLocked(bufferProducer);
767}
768
769bool SurfaceFlinger::authenticateSurfaceTextureLocked(
770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800771 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800772 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800773}
774
Brian Anderson6b376712017-04-04 10:51:39 -0700775status_t SurfaceFlinger::getSupportedFrameTimestamps(
776 std::vector<FrameEvent>* outSupported) const {
777 *outSupported = {
778 FrameEvent::REQUESTED_PRESENT,
779 FrameEvent::ACQUIRE,
780 FrameEvent::LATCH,
781 FrameEvent::FIRST_REFRESH_START,
782 FrameEvent::LAST_REFRESH_START,
783 FrameEvent::GPU_COMPOSITION_DONE,
784 FrameEvent::DEQUEUE_READY,
785 FrameEvent::RELEASE,
786 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 ConditionalLock _l(mStateLock,
788 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700789 if (!getHwComposer().hasCapability(
790 HWC2::Capability::PresentFenceIsNotReliable)) {
791 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
792 }
793 return NO_ERROR;
794}
795
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800796status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
797 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800802 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700803 if (!displayId) {
804 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700805 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 // TODO: Not sure if display density should handled by SF any longer
808 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700811 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800812 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700813 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 }
815 return density;
816 }
817 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("ro.sf.lcd_density"); }
822 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 DisplayInfo info = DisplayInfo();
828
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 float xdpi = hwConfig->getDpiX();
830 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
834 // Default display viewport to display width and height
835 info.viewportW = info.w;
836 info.viewportH = info.h;
837
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800838 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 // The density of the device is provided by a build property
840 float density = Density::getBuildDensity() / 160.0f;
841 if (density == 0) {
842 // the build doesn't provide a density -- this is wrong!
843 // use xdpi instead
844 ALOGE("ro.sf.lcd_density must be defined as a build property");
845 density = xdpi / 160.0f;
846 }
847 if (Density::getEmuDensity()) {
848 // if "qemu.sf.lcd_density" is specified, it overrides everything
849 xdpi = ydpi = density = Density::getEmuDensity();
850 density /= 160.0f;
851 }
852 info.density = density;
853
854 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855 const auto display = getDefaultDisplayDeviceLocked();
856 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700857
858 // This is for screenrecord
859 const Rect viewport = display->getViewport();
860 if (viewport.isValid()) {
861 info.viewportW = uint32_t(viewport.getWidth());
862 info.viewportH = uint32_t(viewport.getHeight());
863 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 } else {
865 // TODO: where should this value come from?
866 static const int TV_DENSITY = 213;
867 info.density = TV_DENSITY / 160.0f;
868 info.orientation = 0;
869 }
870
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 info.xdpi = xdpi;
872 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800874 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875
Andy McFadden91b2ca82014-06-13 14:04:23 -0700876 // This is how far in advance a buffer must be queued for
877 // presentation at a given time. If you want a buffer to appear
878 // on the screen at time N, you must submit the buffer before
879 // (N - presentationDeadline).
880 //
881 // Normally it's one full refresh period (to give SF a chance to
882 // latch the buffer), but this can be reduced by configuring a
883 // DispSync offset. Any additional delays introduced by the hardware
884 // composer or panel must be accounted for here.
885 //
886 // We add an additional 1ms to allow for processing time and
887 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800888 info.presentationDeadline =
889 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700890
891 // All non-virtual displays are currently considered secure.
892 info.secure = true;
893
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800894 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700895 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800896 std::swap(info.w, info.h);
897 }
898
Michael Wright28f24d02016-07-12 13:30:53 -0700899 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700900 }
901
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 return NO_ERROR;
903}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700904
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700905status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
906 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return BAD_VALUE;
908 }
909
Ana Krulecc2870422019-01-29 19:00:58 -0800910 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700911 return NO_ERROR;
912}
913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
915 const auto display = getDisplayDevice(displayToken);
916 if (!display) {
917 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800918 return BAD_VALUE;
919 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700920
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700921 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
925 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800926
Ana Krulec7d1d6832018-12-27 11:10:09 -0800927 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928 // Lock is acquired by setRefreshRateTo.
929 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800930 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
931 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
932 return;
933 }
934
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800935 // Lock is acquired by setRefreshRateTo.
936 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800937 if (!display) {
938 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
939 displayToken.get());
940 return;
941 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700942 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800943 ALOGW("Attempt to set active config %d for virtual display", mode);
944 return;
945 }
946 int currentDisplayPowerMode = display->getPowerMode();
947 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
948 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700949 return;
950 }
951
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952 // Don't check against the current mode yet. Worst case we set the desired
953 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954 std::lock_guard<std::mutex> lock(mActiveConfigLock);
955 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
956
957 if (!mDesiredActiveConfigChanged) {
958 // This is the first time we set the desired
959 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
960
961 // This will trigger HWC refresh without resetting the idle timer.
962 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800964 mDesiredActiveConfigChanged = true;
965 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966}
967
968status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
969 ATRACE_CALL();
970 postMessageSync(new LambdaMessage(
971 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
972 return NO_ERROR;
973}
974
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975void SurfaceFlinger::setActiveConfigInternal() {
976 ATRACE_CALL();
977
978 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800979 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980
981 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
982 display->setActiveConfig(mUpcomingActiveConfig.configId);
983
Ana Krulecc2870422019-01-29 19:00:58 -0800984 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
986}
987
Ady Abrahamb838aed2019-02-12 15:30:16 -0800988bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
989 // we may be in the process of changing the active state
990 if (mWaitForNextInvalidate) {
991 mWaitForNextInvalidate = false;
992
993 repaintEverythingForHWC();
994 // We do not want to give another frame to HWC while we are transitioning.
995 return true;
996 }
997
998 if (mCheckPendingFence) {
999 if (mPreviousPresentFence != Fence::NO_FENCE &&
1000 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1001 // fence has not signaled yet. wait for the next invalidate
1002 repaintEverythingForHWC();
1003 return true;
1004 }
1005
1006 // We received the present fence from the HWC, so we assume it successfully updated
1007 // the config, hence we update SF.
1008 mCheckPendingFence = false;
1009 setActiveConfigInternal();
1010 }
1011
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012 // Store the local variable to release the lock.
1013 ActiveConfigInfo desiredActiveConfig;
1014 {
1015 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 if (!mDesiredActiveConfigChanged) {
1017 return false;
1018 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001019 desiredActiveConfig = mDesiredActiveConfig;
1020 }
1021
1022 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001023 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1024 // display is not valid or we are already in the requested mode
1025 // on both cases there is nothing left to do
1026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1027 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1028 mDesiredActiveConfigChanged = false;
1029 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1030 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032
1033 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1034 mUpcomingActiveConfig = desiredActiveConfig;
1035 const auto displayId = display->getId();
1036 LOG_ALWAYS_FATAL_IF(!displayId);
1037
1038 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1039 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1040
1041 // we need to submit an empty frame to HWC to start the process
1042 mWaitForNextInvalidate = true;
1043 mCheckPendingFence = true;
1044
1045 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001046}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1049 Vector<ColorMode>* outColorModes) {
1050 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001051 return BAD_VALUE;
1052 }
1053
Peiyong Lina52f0292018-03-14 17:26:31 -07001054 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001055 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001056 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1057
1058 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1059 if (!displayId) {
1060 return NAME_NOT_FOUND;
1061 }
1062
Dominik Laskowski075d3172018-05-24 15:50:06 -07001063 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001064 }
Michael Wright28f24d02016-07-12 13:30:53 -07001065 outColorModes->clear();
1066 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1067
1068 return NO_ERROR;
1069}
1070
Daniel Solomon42d04562019-01-20 21:03:19 -08001071status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1072 ui::DisplayPrimaries &primaries) {
1073 if (!displayToken) {
1074 return BAD_VALUE;
1075 }
1076
1077 // Currently we only support this API for a single internal display.
1078 if (getInternalDisplayToken() != displayToken) {
1079 return BAD_VALUE;
1080 }
1081
1082 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1087 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001088 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001089 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001090 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001091}
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001094 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 Vector<ColorMode> modes;
1096 getDisplayColorModes(displayToken, &modes);
1097 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1098 if (mode < ColorMode::NATIVE || !exists) {
1099 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1100 decodeColorMode(mode).c_str(), mode, displayToken.get());
1101 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001102 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 const auto display = getDisplayDevice(displayToken);
1104 if (!display) {
1105 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1106 decodeColorMode(mode).c_str(), mode, displayToken.get());
1107 } else if (display->isVirtual()) {
1108 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1109 decodeColorMode(mode).c_str(), mode);
1110 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001111 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1112 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113 }
1114 }));
1115
Michael Wright28f24d02016-07-12 13:30:53 -07001116 return NO_ERROR;
1117}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001118
Svetoslavd85084b2014-03-20 10:28:31 -07001119status_t SurfaceFlinger::clearAnimationFrameStats() {
1120 Mutex::Autolock _l(mStateLock);
1121 mAnimFrameTracker.clearStats();
1122 return NO_ERROR;
1123}
1124
1125status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1126 Mutex::Autolock _l(mStateLock);
1127 mAnimFrameTracker.getStats(outStats);
1128 return NO_ERROR;
1129}
1130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1132 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001133 Mutex::Autolock _l(mStateLock);
1134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135 const auto display = getDisplayDeviceLocked(displayToken);
1136 if (!display) {
1137 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001138 return BAD_VALUE;
1139 }
1140
Peiyong Linfb069302018-04-25 14:34:31 -07001141 // At this point the DisplayDeivce should already be set up,
1142 // meaning the luminance information is already queried from
1143 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001144 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001145 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1146 capabilities.getDesiredMaxLuminance(),
1147 capabilities.getDesiredMaxAverageLuminance(),
1148 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001149
1150 return NO_ERROR;
1151}
1152
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001153status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1154 ui::PixelFormat* outFormat,
1155 ui::Dataspace* outDataspace,
1156 uint8_t* outComponentMask) const {
1157 if (!outFormat || !outDataspace || !outComponentMask) {
1158 return BAD_VALUE;
1159 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001160 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001161 if (!display || !display->getId()) {
1162 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1163 return BAD_VALUE;
1164 }
1165 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1166 outDataspace, outComponentMask);
1167}
1168
Kevin DuBois74e53772018-11-19 10:52:38 -08001169status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1170 bool enable, uint8_t componentMask,
1171 uint64_t maxFrames) const {
1172 const auto display = getDisplayDevice(displayToken);
1173 if (!display || !display->getId()) {
1174 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1175 return BAD_VALUE;
1176 }
1177
1178 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1179 componentMask, maxFrames);
1180}
1181
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001182status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1183 uint64_t maxFrames, uint64_t timestamp,
1184 DisplayedFrameStats* outStats) const {
1185 const auto display = getDisplayDevice(displayToken);
1186 if (!display || !display->getId()) {
1187 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1188 return BAD_VALUE;
1189 }
1190
1191 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1192 outStats);
1193}
1194
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001195status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1196 if (!outSupported) {
1197 return BAD_VALUE;
1198 }
1199 *outSupported = getRenderEngine().supportsProtectedContent();
1200 return NO_ERROR;
1201}
1202
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001203status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1204 bool* outIsWideColorDisplay) const {
1205 if (!displayToken || !outIsWideColorDisplay) {
1206 return BAD_VALUE;
1207 }
1208 Mutex::Autolock _l(mStateLock);
1209 const auto display = getDisplayDeviceLocked(displayToken);
1210 if (!display) {
1211 return BAD_VALUE;
1212 }
1213 *outIsWideColorDisplay = display->hasWideColorGamut();
1214 return NO_ERROR;
1215}
1216
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001217status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001218 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001219 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001220
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 if (mInjectVSyncs == enable) {
1222 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001223 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001224
Ana Krulecc2870422019-01-29 19:00:58 -08001225 auto resyncCallback =
1226 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001227
Ana Krulec98b5b242018-08-10 15:03:23 -07001228 // TODO(akrulec): Part of the Injector should be refactored, so that it
1229 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 if (enable) {
1231 ALOGV("VSync Injections enabled");
1232 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001233 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001234 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001235 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001236 impl::EventThread::InterceptVSyncsCallback(),
1237 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001238 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001239 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001240 } else {
1241 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001242 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1243 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001244 }
1245
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001246 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001247 }));
1248
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001249 return NO_ERROR;
1250}
1251
1252status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 Mutex::Autolock _l(mStateLock);
1254
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001255 if (!mInjectVSyncs) {
1256 ALOGE("VSync Injections not enabled");
1257 return BAD_VALUE;
1258 }
1259 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1260 ALOGV("Injecting VSync inside SurfaceFlinger");
1261 mVSyncInjector->onInjectSyncEvent(when);
1262 }
1263 return NO_ERROR;
1264}
1265
Lloyd Pique755e3192018-01-31 16:46:15 -08001266status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1267 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001268 // Try to acquire a lock for 1s, fail gracefully
1269 const status_t err = mStateLock.timedLock(s2ns(1));
1270 const bool locked = (err == NO_ERROR);
1271 if (!locked) {
1272 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1273 return TIMED_OUT;
1274 }
1275
1276 outLayers->clear();
1277 mCurrentState.traverseInZOrder([&](Layer* layer) {
1278 outLayers->push_back(layer->getLayerDebugInfo());
1279 });
1280
1281 mStateLock.unlock();
1282 return NO_ERROR;
1283}
1284
Peiyong Linc6780972018-10-28 15:24:08 -07001285status_t SurfaceFlinger::getCompositionPreference(
1286 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1287 Dataspace* outWideColorGamutDataspace,
1288 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001289 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001290 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001291 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001292 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001293 return NO_ERROR;
1294}
1295
Dan Stoza84ab9372018-12-17 15:27:57 -08001296status_t SurfaceFlinger::addRegionSamplingListener(
1297 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1298 const sp<IRegionSamplingListener>& /*listener*/) {
1299 return NO_ERROR;
1300}
1301
1302status_t SurfaceFlinger::removeRegionSamplingListener(
1303 const sp<IRegionSamplingListener>& /*listener*/) {
1304 return NO_ERROR;
1305}
1306
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001307// ----------------------------------------------------------------------------
1308
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001309sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1310 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001311 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001312 Mutex::Autolock lock(mStateLock);
1313 return getVsyncPeriod();
1314 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001315
Ana Krulecc2870422019-01-29 19:00:58 -08001316 const auto& handle =
1317 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001318
Ana Krulecc2870422019-01-29 19:00:58 -08001319 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001320}
1321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001322// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001323
1324void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001325 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001326}
1327
1328void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001329 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001330}
1331
1332void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001333 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334}
1335
1336void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001337 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001338 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001339}
1340
1341status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001342 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001343 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344}
1345
1346status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001347 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349 if (res == NO_ERROR) {
1350 msg->wait();
1351 }
1352 return res;
1353}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001355void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001356 do {
1357 waitForEvent();
1358 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001359}
1360
Dominik Laskowski83b88212018-12-11 13:34:06 -08001361nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001362 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001363 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1364 return 0;
1365 }
1366
1367 const auto config = getHwComposer().getActiveConfig(*displayId);
1368 return config ? config->getVsyncPeriod() : 0;
1369}
1370
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001371void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1372 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 ATRACE_NAME("SF onVsync");
1374
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
1379 }
1380
Dominik Laskowski075d3172018-05-24 15:50:06 -07001381 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001382 return;
1383 }
1384
Dominik Laskowski075d3172018-05-24 15:50:06 -07001385 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001386 // For now, we don't do anything with external display vsyncs.
1387 return;
1388 }
1389
Ana Krulecc2870422019-01-29 19:00:58 -08001390 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001391}
1392
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001393void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001394 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1395 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396}
1397
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001398void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1399 mPhaseOffsets->setRefreshRateType(refreshRate);
1400
1401 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1402 mVsyncModulator.setPhaseOffsets(early, gl, late);
1403
1404 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001405 return;
1406 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001407
Ana Krulec7d1d6832018-12-27 11:10:09 -08001408 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1409 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1410 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1411 // refresh cycle.
1412
1413 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001414 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001415 if (currentVsyncPeriod == 0) {
1416 return;
1417 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001418
Ana Krulec7d1d6832018-12-27 11:10:09 -08001419 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1420 // floating numbers.
1421 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001422 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1423 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001424 if (std::abs(currentFps - newFps) <= 1) {
1425 return;
1426 }
1427
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001428 const auto displayId = getInternalDisplayIdLocked();
1429 LOG_ALWAYS_FATAL_IF(!displayId);
1430
1431 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001432 for (int i = 0; i < configs.size(); i++) {
1433 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1434 if (vsyncPeriod == 0) {
1435 continue;
1436 }
1437 const float fps = 1e9 / vsyncPeriod;
1438 // TODO(b/113612090): There should be a better way at determining which config
1439 // has the right refresh rate.
1440 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001441 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001442 }
1443 }
1444}
1445
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001446void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001447 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001448 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001449 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
Lloyd Piqueba04e622017-12-14 17:11:26 -08001451 // Ignore events that do not have the right sequenceId.
1452 if (sequenceId != getBE().mComposerSequenceId) {
1453 return;
1454 }
1455
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 // Only lock if we're not on the main thread. This function is normally
1457 // called on a hwbinder thread, but for the primary display it's called on
1458 // the main thread with the state lock already held, so don't attempt to
1459 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001460 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001461
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001462 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001463
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001464 if (std::this_thread::get_id() == mMainThreadId) {
1465 // Process all pending hot plug events immediately if we are on the main thread.
1466 processDisplayHotplugEventsLocked();
1467 }
1468
Lloyd Piqueba04e622017-12-14 17:11:26 -08001469 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001470}
1471
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001472void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001473 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001474 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001476 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001477 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001478}
1479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001480void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001481 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001482 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001483 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001484 getHwComposer().setVsyncEnabled(*displayId,
1485 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1486 }
Mathias Agopian86303202012-07-24 22:46:10 -07001487}
1488
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001489// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001490void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001491 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001492 // Clear the drawing state so that the logic inside of
1493 // handleTransactionLocked will fire. It will determine the delta between
1494 // mCurrentState and mDrawingState and re-apply all changes when we make the
1495 // transition.
1496 mDrawingState.displays.clear();
1497 mDisplays.clear();
1498}
1499
Steven Thomas050b2c82017-03-06 11:45:16 -08001500void SurfaceFlinger::updateVrFlinger() {
1501 if (!mVrFlinger)
1502 return;
1503 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001504 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001505 return;
1506 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001507
Lloyd Pique441d5042018-10-18 16:49:51 -07001508 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001509 ALOGE("Vr flinger is only supported for remote hardware composer"
1510 " service connections. Ignoring request to transition to vr"
1511 " flinger.");
1512 mVrFlingerRequestsDisplay = false;
1513 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001514 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001515
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001516 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517
Steven Thomas0123ac62018-07-12 11:32:34 -07001518 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001519 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001520
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001521 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001522
1523 // Clear out all the output layers from the composition engine for all
1524 // displays before destroying the hardware composer interface. This ensures
1525 // any HWC layers are destroyed through that interface before it becomes
1526 // invalid.
1527 for (const auto& [token, displayDevice] : mDisplays) {
1528 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1529 compositionengine::Output::OutputLayers());
1530 }
1531
Steven Thomas0123ac62018-07-12 11:32:34 -07001532 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1533 // called below. Clear the reference now so we don't accidentally use it
1534 // later.
1535 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001536
Steven Thomasb02664d2017-07-26 18:48:28 -07001537 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001542 // Delete the current instance before creating the new one
1543 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1544 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1545 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1546 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001547
Lloyd Pique441d5042018-10-18 16:49:51 -07001548 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001549 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001550
1551 if (vrFlingerRequestsDisplay) {
1552 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001554
1555 mVisibleRegionsDirty = true;
1556 invalidateHwcGeometry();
1557
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001558 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001559 display = getDefaultDisplayDeviceLocked();
1560 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001561 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001562
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001564 const nsecs_t vsyncPeriod = getVsyncPeriod();
1565 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001566
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001567 // The present fences returned from vr_hwc are not an accurate
1568 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001569 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570
Steven Thomasb02664d2017-07-26 18:48:28 -07001571 // Use phase of 0 since phase is not known.
1572 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001573 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001574 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001575
Ana Krulecc2870422019-01-29 19:00:58 -08001576 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001577
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001578 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001579 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001580}
1581
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001583 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001584 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001585 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001586 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001587 break;
1588 }
1589
Ana Krulecc2870422019-01-29 19:00:58 -08001590 // This call is made each time SF wakes up and creates a new frame.
1591 mScheduler->incrementFrameCounter();
1592
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001593 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1594 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001595 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001596 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001597 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001598 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001599 if (mPropagateBackpressure) {
1600 signalLayerUpdate();
1601 break;
1602 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001603 }
Dan Stoza50182882016-07-08 12:02:20 -07001604
Steven Thomas050b2c82017-03-06 11:45:16 -08001605 // Now that we're going to make it to the handleMessageTransaction()
1606 // call below it's safe to call updateVrFlinger(), which will
1607 // potentially trigger a display handoff.
1608 updateVrFlinger();
1609
Dan Stoza6b9454d2014-11-07 16:00:59 -08001610 bool refreshNeeded = handleMessageTransaction();
1611 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001612
1613 updateCursorAsync();
1614 updateInputFlinger();
1615
Dan Stoza58784442014-12-02 16:58:17 -08001616 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001617 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001618 // Signal a refresh if a transaction modified the window state,
1619 // a new buffer was latched, or if HWC has requested a full
1620 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001621 signalRefresh();
1622 }
1623 break;
1624 }
1625 case MessageQueue::REFRESH: {
1626 handleMessageRefresh();
1627 break;
1628 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001629 }
1630}
1631
Dan Stoza6b9454d2014-11-07 16:00:59 -08001632bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001633 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001634
1635 // Apply any ready transactions in the queues if there are still transactions that have not been
1636 // applied, wake up during the next vsync period and check again
1637 bool transactionNeeded = false;
1638 if (!flushTransactionQueues()) {
1639 transactionNeeded = true;
1640 }
1641
Mathias Agopian4fec8732012-06-29 14:12:52 -07001642 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001643 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001645
1646 if (transactionNeeded) {
1647 setTransactionFlags(eTransactionNeeded);
1648 }
1649
1650 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001651}
1652
Mathias Agopian4fec8732012-06-29 14:12:52 -07001653void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001654 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001655
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001656 mRefreshPending = false;
1657
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001658 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001659 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001660 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001661 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001662 for (const auto& [token, display] : mDisplays) {
1663 beginFrame(display);
1664 prepareFrame(display);
1665 doDebugFlashRegions(display, repaintEverything);
1666 doComposition(display, repaintEverything);
1667 }
1668
Adrian Roos1e1a1282017-11-01 19:05:31 +01001669 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001670 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001671
1672 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001673 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001674
Dan Stozabfbffeb2016-07-21 14:49:33 -07001675 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001676 for (const auto& [token, displayDevice] : mDisplays) {
1677 auto display = displayDevice->getCompositionDisplay();
1678 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001679 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001680 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001681 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682
Jorim Jaggi90535212018-05-23 23:44:06 +02001683 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001684
David Sodman7e4ae112018-02-09 15:02:28 -08001685 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001686
1687 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001688}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001689
David Sodmanfa9b2af2017-12-24 13:28:59 -08001690
1691bool SurfaceFlinger::handleMessageInvalidate() {
1692 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001693 bool refreshNeeded = handlePageFlip();
1694
Vishnu Nair4351ad52019-02-11 14:13:02 -08001695 if (mVisibleRegionsDirty) {
1696 computeLayerBounds();
1697 }
1698
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001699 for (auto& layer : mLayersPendingRefresh) {
1700 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001701 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001702 invalidateLayerStack(layer, visibleReg);
1703 }
1704 mLayersPendingRefresh.clear();
1705 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706}
1707
David Sodman79bba0e2018-08-05 18:07:49 -07001708void SurfaceFlinger::calculateWorkingSet() {
1709 ATRACE_CALL();
1710 ALOGV(__FUNCTION__);
1711
David Sodman79bba0e2018-08-05 18:07:49 -07001712 // build the h/w work list
1713 if (CC_UNLIKELY(mGeometryInvalid)) {
1714 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 for (const auto& [token, displayDevice] : mDisplays) {
1716 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001717 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001718 if (!displayId) {
1719 continue;
1720 }
David Sodman79bba0e2018-08-05 18:07:49 -07001721
Lloyd Pique32cbe282018-10-19 13:09:22 -07001722 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001723 for (size_t i = 0; i < currentLayers.size(); i++) {
1724 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001725
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001726 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001727 layer->forceClientComposition(displayDevice);
1728 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001729 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001730
Lloyd Pique32cbe282018-10-19 13:09:22 -07001731 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001733 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001734 }
David Sodman79bba0e2018-08-05 18:07:49 -07001735 }
1736 }
1737 }
1738
1739 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001740 for (const auto& [token, displayDevice] : mDisplays) {
1741 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001742 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001743 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001744 continue;
1745 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001746 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001747
1748 if (mDrawingState.colorMatrixChanged) {
1749 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001750 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001751 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001752 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001753 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001754 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1755 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001756 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001757 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001758 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1759 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001760 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001761 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001762 }
1763
Peiyong Lind3788632018-09-18 16:01:31 -07001764 // TODO(b/111562338) remove when composer 2.3 is shipped.
1765 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001766 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001767 }
1768
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001769 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001770 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001771 }
1772
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001773 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001774 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001775 layer->setCompositionType(displayDevice,
1776 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001777 continue;
1778 }
1779
Lloyd Pique32cbe282018-10-19 13:09:22 -07001780 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001781 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001782 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001783 }
1784
Peiyong Lin13effd12018-07-24 17:01:47 -07001785 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001786 ColorMode colorMode;
1787 Dataspace dataSpace;
1788 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001789 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001790 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001791 }
1792 }
1793
1794 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001795
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001796 for (const auto& [token, displayDevice] : mDisplays) {
1797 auto display = displayDevice->getCompositionDisplay();
1798 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001799 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001800 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1801 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1802 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001803 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001804 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001805 }
1806 }
David Sodman79bba0e2018-08-05 18:07:49 -07001807}
1808
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1810 bool repaintEverything) {
1811 auto display = displayDevice->getCompositionDisplay();
1812 const auto& displayState = display->getState();
1813
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814 // is debugging enabled
1815 if (CC_LIKELY(!mDebugRegion))
1816 return;
1817
Lloyd Pique32cbe282018-10-19 13:09:22 -07001818 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001819 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001820 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001821 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001822 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001823 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001824 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001826 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827 }
1828 }
1829
Lloyd Pique32cbe282018-10-19 13:09:22 -07001830 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831
1832 if (mDebugRegion > 1) {
1833 usleep(mDebugRegion * 1000);
1834 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001835
Lloyd Pique32cbe282018-10-19 13:09:22 -07001836 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001837}
1838
Adrian Roos1e1a1282017-11-01 19:05:31 +01001839void SurfaceFlinger::doTracing(const char* where) {
1840 ATRACE_CALL();
1841 ATRACE_NAME(where);
1842 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001843 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001844 }
1845}
1846
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001847void SurfaceFlinger::logLayerStats() {
1848 ATRACE_CALL();
1849 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001850 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001851 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001852 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001853 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001854 }
1855 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001856
1857 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001858 }
1859}
1860
David Sodman2b406362017-12-15 13:33:47 -08001861void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 ATRACE_CALL();
1864 ALOGV("preComposition");
1865
David Sodman2b406362017-12-15 13:33:47 -08001866 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1867
Mathias Agopiancd60f992012-08-16 16:28:27 -07001868 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001869 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001870 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871 needExtraInvalidate = true;
1872 }
Robert Carr2047fae2016-11-28 14:09:09 -08001873 });
1874
Mathias Agopiancd60f992012-08-16 16:28:27 -07001875 if (needExtraInvalidate) {
1876 signalLayerUpdate();
1877 }
1878}
1879
Ana Krulece588e312018-09-18 12:32:24 -07001880void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1881 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001882 // Update queue of past composite+present times and determine the
1883 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001884 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001885 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001886 while (!getBE().mCompositePresentTimes.empty()) {
1887 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001888 // Cached values should have been updated before calling this method,
1889 // which helps avoid duplicate syscalls.
1890 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1891 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1892 break;
1893 }
1894 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001895 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896 }
1897
1898 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001899 while (getBE().mCompositePresentTimes.size() > 16) {
1900 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001901 }
1902
Ana Krulece588e312018-09-18 12:32:24 -07001903 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001904}
1905
Ana Krulece588e312018-09-18 12:32:24 -07001906void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1907 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 // Integer division and modulo round toward 0 not -inf, so we need to
1909 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001910 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1911 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1912 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001913
Ana Krulec757f63a2019-01-25 10:46:18 -08001914 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001915 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001916 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001917 }
1918
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 // Snap the latency to a value that removes scheduling jitter from the
1920 // composition and present times, which often have >1ms of jitter.
1921 // Reducing jitter is important if an app attempts to extrapolate
1922 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001923 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001925 nsecs_t bias = stats.vsyncPeriod / 2;
1926 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1927 nsecs_t snappedCompositeToPresentLatency =
1928 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001929
David Sodman99974d22017-11-28 12:04:33 -08001930 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001931 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1932 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001933 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934}
1935
Ady Abraham8164d482019-01-11 14:47:59 -08001936// debug patch for b/119477596 - add stack guards to catch stack
1937// corruptions and disable clang optimizations.
1938// The code below is temporary and planned to be removed once stack
1939// corruptions are found.
1940#pragma clang optimize off
1941class StackGuard {
1942public:
1943 StackGuard(const char* name, const char* func, int line) {
1944 guarders.reserve(MIN_CAPACITY);
1945 guarders.push_back({this, name, func, line});
1946 validate();
1947 }
1948 ~StackGuard() {
1949 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1950 if (i->guard == this) {
1951 guarders.erase(i);
1952 break;
1953 }
1954 }
1955 }
1956
1957 static void validate() {
1958 for (const auto& guard : guarders) {
1959 if (guard.guard->cookie != COOKIE_VALUE) {
1960 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1961 CallStack stack(LOG_TAG);
1962 abort();
1963 }
1964 }
1965 }
1966
1967private:
1968 uint64_t cookie = COOKIE_VALUE;
1969 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1970 static constexpr size_t MIN_CAPACITY = 16;
1971
1972 struct GuarderElement {
1973 StackGuard* guard;
1974 const char* name;
1975 const char* func;
1976 int line;
1977 };
1978
1979 static std::vector<GuarderElement> guarders;
1980};
1981std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1982
1983#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1984
1985#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001986void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001987{
Ady Abraham8164d482019-01-11 14:47:59 -08001988 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 ATRACE_CALL();
1990 ALOGV("postComposition");
1991
Brian Anderson3546a3f2016-07-14 11:51:14 -07001992 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001993 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001994 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001995 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001996 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001997 }
Ady Abraham8164d482019-01-11 14:47:59 -08001998 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001999
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002000 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002001 const auto displayDevice = getDefaultDisplayDeviceLocked();
2002 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002003
David Sodman73beded2017-11-15 11:56:06 -08002004 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002006 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2007
Lloyd Pique32cbe282018-10-19 13:09:22 -07002008 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002009 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002010 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2011 ->getRenderSurface()
2012 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002013 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002014 } else {
2015 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2016 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017
Ady Abraham8164d482019-01-11 14:47:59 -08002018 ASSERT_ON_STACK_GUARD();
2019
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002021 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2022 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002023 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002024 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002025 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
Ana Krulece588e312018-09-18 12:32:24 -07002027 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002028 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002029 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030
Ady Abraham8164d482019-01-11 14:47:59 -08002031 ASSERT_ON_STACK_GUARD();
2032
David Sodman2b406362017-12-15 13:33:47 -08002033 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002034 // when we started doing work for this frame, but that should be okay
2035 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002036 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002037 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002038 DEFINE_STACK_GUARD(compositorTiming);
2039
Brian Andersond0010582017-03-07 13:20:31 -08002040 {
David Sodman99974d22017-11-28 12:04:33 -08002041 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002042 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002043 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002044
2045 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002046 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047
Robert Carr2047fae2016-11-28 14:09:09 -08002048 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002049 bool frameLatched =
2050 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2051 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002052 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002053 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002054 recordBufferingStats(layer->getName().string(),
2055 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002056 }
Ady Abraham8164d482019-01-11 14:47:59 -08002057 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002058 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002059
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002060 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002061 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002062 mScheduler->addPresentFence(presentFenceTime);
2063 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002064 }
2065
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002066 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2068 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002069 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002070 }
2071 }
2072
Ady Abraham8164d482019-01-11 14:47:59 -08002073 ASSERT_ON_STACK_GUARD();
2074
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002075 if (mAnimCompositionPending) {
2076 mAnimCompositionPending = false;
2077
Brian Anderson4e606e32017-03-16 15:34:57 -07002078 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002080 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002081
2082 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002083 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002084 // The HWC doesn't support present fences, so use the refresh
2085 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002086 const nsecs_t presentTime =
2087 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002088 DEFINE_STACK_GUARD(presentTime);
2089
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002090 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002091 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 }
2093 mAnimFrameTracker.advanceFrame();
2094 }
Dan Stozab90cf072015-03-05 11:05:59 -08002095
Ady Abraham8164d482019-01-11 14:47:59 -08002096 ASSERT_ON_STACK_GUARD();
2097
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002098 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002099 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002100 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002101 }
2102
Ady Abraham8164d482019-01-11 14:47:59 -08002103 ASSERT_ON_STACK_GUARD();
2104
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002105 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002106
Ady Abraham8164d482019-01-11 14:47:59 -08002107 ASSERT_ON_STACK_GUARD();
2108
Lloyd Pique32cbe282018-10-19 13:09:22 -07002109 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2110 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002111 return;
2112 }
2113
2114 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002115 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002116 if (mHasPoweredOff) {
2117 mHasPoweredOff = false;
2118 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002119 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002120 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002121 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002122 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002123 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2124 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002125 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002126 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002127 }
David Sodman4a36e932017-11-07 14:29:47 -08002128 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002129
2130 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002131 }
David Sodman4a36e932017-11-07 14:29:47 -08002132 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002134
2135 {
2136 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002137 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002138 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002139 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002140 if (refillCount > 0) {
2141 const size_t offset = mTexturePool.size();
2142 mTexturePool.resize(mTexturePoolSize);
2143 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2144 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2145 }
Ady Abraham8164d482019-01-11 14:47:59 -08002146 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002147 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002148
Marissa Wallfda30bb2018-10-12 11:34:28 -07002149 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002150 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002151
2152 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153}
Ady Abraham8164d482019-01-11 14:47:59 -08002154#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002155
Vishnu Nair4351ad52019-02-11 14:13:02 -08002156void SurfaceFlinger::computeLayerBounds() {
2157 for (const auto& pair : mDisplays) {
2158 const auto& displayDevice = pair.second;
2159 const auto display = displayDevice->getCompositionDisplay();
2160 for (const auto& layer : mDrawingState.layersSortedByZ) {
2161 // only consider the layers on the given layer stack
2162 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002163 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002164 }
2165
2166 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2167 }
2168 }
2169}
2170
Mathias Agopiancd60f992012-08-16 16:28:27 -07002171void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 ATRACE_CALL();
2173 ALOGV("rebuildLayerStacks");
2174
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002175 // We need to clear these out now as these may be holding on to a
2176 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2177 // also holds a reference. When the set of visible layers is recomputed,
2178 // some layers may be destroyed if the only thing keeping them alive was
2179 // that list of visible layers associated with each display. The layer
2180 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2181 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2182 for (const auto& [token, display] : mDisplays) {
2183 getBE().mCompositionInfo[token].clear();
2184 }
2185
Mathias Agopiancd60f992012-08-16 16:28:27 -07002186 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002187 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002188 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002189 mVisibleRegionsDirty = false;
2190 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002191
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002192 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002193 const auto& displayDevice = pair.second;
2194 auto display = displayDevice->getCompositionDisplay();
2195 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002196 Region opaqueRegion;
2197 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002198 compositionengine::Output::OutputLayers layersSortedByZ;
2199 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002200 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002201 const ui::Transform& tr = displayState.transform;
2202 const Rect bounds = displayState.bounds;
2203 if (displayState.isEnabled) {
2204 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002205
Jeff Sharkey76488112017-02-27 14:15:18 -07002206 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002207 auto compositionLayer = layer->getCompositionLayer();
2208 if (compositionLayer == nullptr) {
2209 return;
2210 }
2211
Lloyd Pique32cbe282018-10-19 13:09:22 -07002212 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002213 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2214 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2215
Lloyd Pique07e33212018-12-18 16:33:37 -08002216 bool needsOutputLayer = false;
2217
Lloyd Piqueef36b002019-01-23 17:52:04 -08002218 if (display->belongsInOutput(layer->getLayerStack(),
2219 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002220 Region drawRegion(tr.transform(
2221 layer->visibleNonTransparentRegion));
2222 drawRegion.andSelf(bounds);
2223 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002224 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002225 }
Chia-I Wu83806892017-11-16 10:50:20 -08002226 }
2227
Lloyd Pique07e33212018-12-18 16:33:37 -08002228 if (needsOutputLayer) {
2229 layersSortedByZ.emplace_back(
2230 display->getOrCreateOutputLayer(displayId, compositionLayer,
2231 layerFE));
2232 deprecated_layersSortedByZ.add(layer);
2233
2234 auto& outputLayerState = layersSortedByZ.back()->editState();
2235 outputLayerState.visibleRegion =
2236 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2237 } else if (displayId) {
2238 // For layers that are being removed from a HWC display,
2239 // and that have queued frames, add them to a a list of
2240 // released layers so we can properly set a fence.
2241 bool hasExistingOutputLayer =
2242 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2243 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2244 mLayersWithQueuedFrames.cend(),
2245 layer) != mLayersWithQueuedFrames.cend();
2246
2247 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002248 layersNeedingFences.add(layer);
2249 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002250 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002251 });
2252 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002253
2254 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2255
2256 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002257 displayDevice->setLayersNeedingFences(layersNeedingFences);
2258
2259 Region undefinedRegion{bounds};
2260 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2261
2262 display->editState().undefinedRegion = undefinedRegion;
2263 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002264 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002265 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002266}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002267
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002268// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002269// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002270// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002272// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002273// The returned HDR data space is one of
2274// - Dataspace::UNKNOWN
2275// - Dataspace::BT2020_HLG
2276// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2278 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002279 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002280 *outHdrDataSpace = Dataspace::UNKNOWN;
2281
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002283 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284 case Dataspace::V0_SCRGB:
2285 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002286 case Dataspace::BT2020:
2287 case Dataspace::BT2020_ITU:
2288 case Dataspace::BT2020_LINEAR:
2289 case Dataspace::DISPLAY_BT2020:
2290 bestDataSpace = Dataspace::DISPLAY_BT2020;
2291 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002292 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002293 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002295 case Dataspace::BT2020_PQ:
2296 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002297 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002299 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002300 case Dataspace::BT2020_HLG:
2301 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002302 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002303 // When there's mixed PQ content and HLG content, we set the HDR
2304 // data space to be BT2020_PQ and convert HLG to PQ.
2305 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2306 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002307 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002308 break;
2309 default:
2310 break;
2311 }
Romain Guy54f154a2017-10-24 21:40:32 +01002312 }
2313
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002315}
2316
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002317// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2319 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2321 *outMode = ColorMode::NATIVE;
2322 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002324 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002325 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002326
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002328 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002330 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2331
Peiyong Lina3ea5592019-02-10 14:45:00 -08002332 switch (mForceColorMode) {
2333 case ColorMode::SRGB:
2334 bestDataSpace = Dataspace::V0_SRGB;
2335 break;
2336 case ColorMode::DISPLAY_P3:
2337 bestDataSpace = Dataspace::DISPLAY_P3;
2338 break;
2339 default:
2340 break;
2341 }
2342
Peiyong Lindfde5112018-06-05 10:58:41 -07002343 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002344 const bool isHdr =
2345 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002346 if (isHdr) {
2347 bestDataSpace = hdrDataSpace;
2348 }
2349
Chia-I Wu0d711262018-05-21 15:19:35 -07002350 RenderIntent intent;
2351 switch (mDisplayColorSetting) {
2352 case DisplayColorSetting::MANAGED:
2353 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002354 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002355 break;
2356 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002357 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002358 break;
2359 default: // vendor display color setting
2360 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2361 break;
2362 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002363
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002364 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002365}
2366
Lloyd Pique32cbe282018-10-19 13:09:22 -07002367void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2368 auto display = displayDevice->getCompositionDisplay();
2369 const auto& displayState = display->getState();
2370
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002371 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2373 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002374
David Sodmanfa9b2af2017-12-24 13:28:59 -08002375 // If nothing has changed (!dirty), don't recompose.
2376 // If something changed, but we don't currently have any visible layers,
2377 // and didn't when we last did a composition, then skip it this time.
2378 // The second rule does two things:
2379 // - When all layers are removed from a display, we'll emit one black
2380 // frame, then nothing more until we get new layers.
2381 // - When a display is created with a private layer stack, we won't
2382 // emit any black frames until a layer is added to the layer stack.
2383 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002384
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 const char flagPrefix[] = {'-', '+'};
2386 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2388 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2389 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2390 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002391
Lloyd Pique31cb2942018-10-19 17:23:03 -07002392 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002393
David Sodmanfa9b2af2017-12-24 13:28:59 -08002394 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002395 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002396 }
2397}
2398
Lloyd Pique32cbe282018-10-19 13:09:22 -07002399void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2400 auto display = displayDevice->getCompositionDisplay();
2401 const auto& displayState = display->getState();
2402
2403 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002404 return;
David Sodman2b406362017-12-15 13:33:47 -08002405 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002407 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002409 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002410}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002411
Lloyd Pique32cbe282018-10-19 13:09:22 -07002412void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002413 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002414 ALOGV("doComposition");
2415
Lloyd Pique32cbe282018-10-19 13:09:22 -07002416 auto display = displayDevice->getCompositionDisplay();
2417 const auto& displayState = display->getState();
2418
2419 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002420 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002421 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002422
David Sodmanfa9b2af2017-12-24 13:28:59 -08002423 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002425
Lloyd Pique32cbe282018-10-19 13:09:22 -07002426 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002427 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002428 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002430}
2431
David Sodmanfa9b2af2017-12-24 13:28:59 -08002432void SurfaceFlinger::postFrame()
2433{
2434 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002435 const auto display = getDefaultDisplayDeviceLocked();
2436 if (display && getHwComposer().isConnected(*display->getId())) {
2437 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002438 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2439 logFrameStats();
2440 }
2441 }
2442}
2443
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002445 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002446 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002447
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448 auto display = displayDevice->getCompositionDisplay();
2449 const auto& displayState = display->getState();
2450 const auto displayId = display->getId();
2451
David Sodmanfa9b2af2017-12-24 13:28:59 -08002452 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002453
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 if (displayId) {
2456 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002457 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002458 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002460 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002461
Chia-I Wu7b549592017-11-15 09:14:57 -08002462 // The layer buffer from the previous frame (if any) is released
2463 // by HWC only when the release fence from this frame (if any) is
2464 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002465 if (displayId && layer->hasHwcLayer(displayDevice)) {
2466 releaseFence =
2467 getHwComposer().getLayerReleaseFence(*displayId,
2468 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002469 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002470
2471 // If the layer was client composited in the previous frame, we
2472 // need to merge with the previous client target acquire fence.
2473 // Since we do not track that, always merge with the current
2474 // client target acquire fence when it is available, even though
2475 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002476 if (layer->getCompositionType(displayDevice) ==
2477 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002478 releaseFence =
2479 Fence::merge("LayerRelease", releaseFence,
2480 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002481 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002482
David Sodman15094112018-10-11 09:39:37 -07002483 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 }
Chia-I Wu83806892017-11-16 10:50:20 -08002485
2486 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002488 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002489 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002491 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002492 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002493 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002494 }
2495 }
2496
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 if (displayId) {
2498 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002499 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501}
2502
Mathias Agopian87baae12012-07-31 12:38:26 -07002503void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504{
Mathias Agopian841cde52012-03-01 15:44:37 -08002505 ATRACE_CALL();
2506
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002507 // here we keep a copy of the drawing state (that is the state that's
2508 // going to be overwritten by handleTransactionLocked()) outside of
2509 // mStateLock so that the side-effects of the State assignment
2510 // don't happen with mStateLock held (which can cause deadlocks).
2511 State drawingState(mDrawingState);
2512
Mathias Agopianca4d3602011-05-19 15:38:14 -07002513 Mutex::Autolock _l(mStateLock);
2514 const nsecs_t now = systemTime();
2515 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516
Mathias Agopianca4d3602011-05-19 15:38:14 -07002517 // Here we're guaranteed that some transaction flags are set
2518 // so we can call handleTransactionLocked() unconditionally.
2519 // We call getTransactionFlags(), which will also clear the flags,
2520 // with mStateLock held to guarantee that mCurrentState won't change
2521 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002522
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002523 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002524 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002525 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002526
Mathias Agopianca4d3602011-05-19 15:38:14 -07002527 mLastTransactionTime = systemTime() - now;
2528 mDebugInTransaction = 0;
2529 invalidateHwcGeometry();
2530 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002531}
2532
Lloyd Piqueba04e622017-12-14 17:11:26 -08002533void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2534 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 const std::optional<DisplayIdentificationInfo> info =
2536 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002537
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002539 continue;
2540 }
2541
Lloyd Piqueba04e622017-12-14 17:11:26 -08002542 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002544 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 mPhysicalDisplayTokens[info->id] = new BBinder();
2546 DisplayDeviceState state;
2547 state.displayId = info->id;
2548 state.isSecure = true; // All physical displays are currently considered secure.
2549 state.displayName = info->name;
2550 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2551 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002552 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002554 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002555
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2557 if (index >= 0) {
2558 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2559 mInterceptor->saveDisplayDeletion(state.sequenceId);
2560 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002561 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002563 }
2564
2565 processDisplayChangesLocked();
2566 }
2567
2568 mPendingHotplugEvents.clear();
2569}
2570
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002571void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002572 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2573 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002574}
2575
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002578 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 const sp<IGraphicBufferProducer>& producer) {
2580 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002581 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002582 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002583 creationArgs.isSecure = state.isSecure;
2584 creationArgs.displaySurface = dispSurface;
2585 creationArgs.hasWideColorGamut = false;
2586 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002587
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002588 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002589 creationArgs.isPrimary = isInternalDisplay;
2590
2591 if (useColorManagement && displayId) {
2592 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002594 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002597
Dominik Laskowski7e045462018-05-30 13:02:02 -07002598 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002600 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002601 }
tangrobin6753a022018-08-10 10:58:54 +08002602 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 if (displayId) {
2605 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002608 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609
Lloyd Pique90c115d2018-09-18 21:39:42 -07002610 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002612 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613
Lloyd Pique99d3da52018-01-22 17:48:03 -08002614 // Make sure that composition can never be stalled by a virtual display
2615 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002616 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002617 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2619 }
2620
Dominik Laskowski075d3172018-05-24 15:50:06 -07002621 creationArgs.displayInstallOrientation =
2622 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002623
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002625 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626
Lloyd Pique90c115d2018-09-18 21:39:42 -07002627 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628
2629 if (maxFrameBufferAcquiredBuffers >= 3) {
2630 nativeWindowSurface->preallocateBuffers();
2631 }
2632
2633 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002634 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002635 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002637 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002639 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2640 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002641 if (!state.isVirtual()) {
2642 LOG_ALWAYS_FATAL_IF(!displayId);
2643 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002644 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002646 display->setLayerStack(state.layerStack);
2647 display->setProjection(state.orientation, state.viewport, state.frame);
2648 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002650 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651}
2652
Lloyd Pique347200f2017-12-14 17:00:15 -08002653void SurfaceFlinger::processDisplayChangesLocked() {
2654 // here we take advantage of Vector's copy-on-write semantics to
2655 // improve performance by skipping the transaction entirely when
2656 // know that the lists are identical
2657 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2658 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2659 if (!curr.isIdenticalTo(draw)) {
2660 mVisibleRegionsDirty = true;
2661 const size_t cc = curr.size();
2662 size_t dc = draw.size();
2663
2664 // find the displays that were removed
2665 // (ie: in drawing state but not in current state)
2666 // also handle displays that changed
2667 // (ie: displays that are in both lists)
2668 for (size_t i = 0; i < dc;) {
2669 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2670 if (j < 0) {
2671 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002672 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002673 // Save display ID before disconnecting.
2674 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002675 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002676
2677 if (!display->isVirtual()) {
2678 LOG_ALWAYS_FATAL_IF(!displayId);
2679 dispatchDisplayHotplugEvent(displayId->value, false);
2680 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002682
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002683 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002684 } else {
2685 // this display is in both lists. see if something changed.
2686 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002687 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002688 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2689 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2690 if (state_binder != draw_binder) {
2691 // changing the surface is like destroying and
2692 // recreating the DisplayDevice, so we just remove it
2693 // from the drawing state, so that it get re-added
2694 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002696 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002698 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002699 mDrawingState.displays.removeItemsAt(i);
2700 dc--;
2701 // at this point we must loop to the next item
2702 continue;
2703 }
2704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 }
2709 if ((state.orientation != draw[i].orientation) ||
2710 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 }
2713 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002714 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 }
2716 }
2717 }
2718 ++i;
2719 }
2720
2721 // find displays that were added
2722 // (ie: in current state but not in drawing state)
2723 for (size_t i = 0; i < cc; i++) {
2724 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2725 const DisplayDeviceState& state(curr[i]);
2726
Lloyd Pique542307f2018-10-19 13:24:08 -07002727 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 sp<IGraphicBufferProducer> producer;
2729 sp<IGraphicBufferProducer> bqProducer;
2730 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002731 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002734 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 // Virtual displays without a surface are dormant:
2736 // they have external state (layer stack, projection,
2737 // etc.) but no internal state (i.e. a DisplayDevice).
2738 if (state.surface != nullptr) {
2739 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002740 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 int width = 0;
2742 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2743 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2744 int height = 0;
2745 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2747 int intFormat = 0;
2748 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2749 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002750 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751
Dominik Laskowski075d3172018-05-24 15:50:06 -07002752 displayId =
2753 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 }
2755
2756 // TODO: Plumb requested format back up to consumer
2757
2758 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002759 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 bqProducer, bqConsumer,
2761 state.displayName);
2762
2763 dispSurface = vds;
2764 producer = vds;
2765 }
2766 } else {
2767 ALOGE_IF(state.surface != nullptr,
2768 "adding a supported display, but rendering "
2769 "surface is provided (%p), ignoring it",
2770 state.surface.get());
2771
Dominik Laskowski075d3172018-05-24 15:50:06 -07002772 displayId = state.displayId;
2773 LOG_ALWAYS_FATAL_IF(!displayId);
2774 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 producer = bqProducer;
2776 }
2777
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002778 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002779 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002780 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002781 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002783 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002784 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002785 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 }
2787 }
2788 }
2789 }
2790 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002791
2792 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002793}
2794
Mathias Agopian87baae12012-07-31 12:38:26 -07002795void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002796{
Dan Stoza7dde5992015-05-22 09:51:44 -07002797 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002798 mCurrentState.traverseInZOrder([](Layer* layer) {
2799 layer->notifyAvailableFrames();
2800 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 /*
2803 * Traversal of the children
2804 * (perform the transaction for each of them if needed)
2805 */
2806
Mathias Agopian3559b072012-08-15 13:46:03 -07002807 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002808 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002810 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811
2812 const uint32_t flags = layer->doTransaction(0);
2813 if (flags & Layer::eVisibleRegion)
2814 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002815
2816 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002817 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002818 }
Robert Carr2047fae2016-11-28 14:09:09 -08002819 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 }
2821
2822 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002823 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 */
2825
Mathias Agopiane57f2922012-08-09 16:29:12 -07002826 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002827 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002828 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002829 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002831 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002832 // The transform hint might have changed for some layers
2833 // (either because a display has changed, or because a layer
2834 // as changed).
2835 //
2836 // Walk through all the layers in currentLayers,
2837 // and update their transform hint.
2838 //
2839 // If a layer is visible only on a single display, then that
2840 // display is used to calculate the hint, otherwise we use the
2841 // default display.
2842 //
2843 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2844 // the hint is set before we acquire a buffer from the surface texture.
2845 //
2846 // NOTE: layer transactions have taken place already, so we use their
2847 // drawing state. However, SurfaceFlinger's own transaction has not
2848 // happened yet, so we must use the current state layer list
2849 // (soon to become the drawing state list).
2850 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002852 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002853 bool first = true;
2854 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002855 // NOTE: we rely on the fact that layers are sorted by
2856 // layerStack first (so we don't have to traverse the list
2857 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002859 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002860 currentlayerStack = layerStack;
2861 // figure out if this layerstack is mirrored
2862 // (more than one display) if so, pick the default display,
2863 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 hintDisplay = nullptr;
2865 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002866 if (display->getCompositionDisplay()
2867 ->belongsInOutput(layer->getLayerStack(),
2868 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 if (hintDisplay) {
2870 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002871 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002873 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002874 }
2875 }
2876 }
2877 }
Chet Haase91d25932013-04-11 15:24:55 -07002878
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002879 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002880 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2881 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002882
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002883 // could be null when this layer is using a layerStack
2884 // that is not visible on any display. Also can occur at
2885 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002886 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002887 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002888
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002890 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002891 if (hintDisplay) {
2892 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002893 }
Robert Carr2047fae2016-11-28 14:09:09 -08002894
2895 first = false;
2896 });
Mathias Agopian84300952012-11-21 16:02:13 -08002897 }
2898
2899
Mathias Agopian3559b072012-08-15 13:46:03 -07002900 /*
2901 * Perform our own transaction if needed
2902 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903
2904 if (mLayersAdded) {
2905 mLayersAdded = false;
2906 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002907 mVisibleRegionsDirty = true;
2908 }
2909
2910 // some layers might have been removed, so
2911 // we need to update the regions they're exposing.
2912 if (mLayersRemoved) {
2913 mLayersRemoved = false;
2914 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002915 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002917 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002919 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002920 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002921 }
Robert Carr2047fae2016-11-28 14:09:09 -08002922 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923 }
2924
Vishnu Nairec0ab382019-02-13 15:32:56 -08002925 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002927}
2928
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002929void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002930 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002931 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002932 return;
2933 }
2934
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002935 if (mVisibleRegionsDirty || mInputInfoChanged) {
2936 mInputInfoChanged = false;
2937 updateInputWindowInfo();
2938 }
2939
2940 executeInputWindowCommands();
2941}
2942
2943void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002944 Vector<InputWindowInfo> inputHandles;
2945
2946 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2947 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002948 // When calculating the screen bounds we ignore the transparent region since it may
2949 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002950 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002951 }
2952 });
chaviw291d88a2019-02-14 10:33:58 -08002953
2954 mInputFlinger->setInputWindows(inputHandles,
2955 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2956 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002957}
2958
Vishnu Nairec0ab382019-02-13 15:32:56 -08002959void SurfaceFlinger::commitInputWindowCommands() {
2960 mInputWindowCommands.merge(mPendingInputWindowCommands);
2961 mPendingInputWindowCommands.clear();
2962}
2963
chaviwfbe5d9c2018-12-26 12:23:37 -08002964void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002965 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2966 if (transferTouchFocusCommand.fromToken != nullptr &&
2967 transferTouchFocusCommand.toToken != nullptr &&
2968 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2969 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2970 transferTouchFocusCommand.toToken);
2971 }
2972 }
2973
2974 mInputWindowCommands.clear();
2975}
2976
Riley Andrews03414a12014-07-01 14:22:59 -07002977void SurfaceFlinger::updateCursorAsync()
2978{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002979 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002980 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002981 continue;
2982 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002984 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2985 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002986 }
2987 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002988}
2989
chaviw61626f22018-11-15 16:26:27 -08002990void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2991 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002992 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002993 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002994 }
2995 layer->releasePendingBuffer(systemTime());
2996}
2997
Mathias Agopian4fec8732012-06-29 14:12:52 -07002998void SurfaceFlinger::commitTransaction()
2999{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003000 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003001 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003002 for (const auto& l : mLayersPendingRemoval) {
3003 recordBufferingStats(l->getName().string(),
3004 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003005
Lloyd Pique07e33212018-12-18 16:33:37 -08003006 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003007 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003008 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003009 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003010 }
3011 mLayersPendingRemoval.clear();
3012 }
3013
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003014 // If this transaction is part of a window animation then the next frame
3015 // we composite should be considered an animation as well.
3016 mAnimCompositionPending = mAnimTransactionPending;
3017
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003019 // clear the "changed" flags in current state
3020 mCurrentState.colorMatrixChanged = false;
3021
Robert Carr1f0a16a2016-10-24 16:27:39 -07003022 mDrawingState.traverseInZOrder([](Layer* layer) {
3023 layer->commitChildList();
3024 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003025 mTransactionPending = false;
3026 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003027 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028}
3029
Lloyd Pique32cbe282018-10-19 13:09:22 -07003030void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003031 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003032 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003033 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003034
Lloyd Pique32cbe282018-10-19 13:09:22 -07003035 auto display = displayDevice->getCompositionDisplay();
3036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037 Region aboveOpaqueLayers;
3038 Region aboveCoveredLayers;
3039 Region dirty;
3040
Mathias Agopian87baae12012-07-31 12:38:26 -07003041 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042
Robert Carr2047fae2016-11-28 14:09:09 -08003043 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003044 // start with the whole surface at its current location
3045 const Layer::State& s(layer->getDrawingState());
3046
Jesse Hall01e29052013-02-19 16:13:35 -08003047 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003048 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003049 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003051
Mathias Agopianab028732010-03-16 16:41:46 -07003052 /*
3053 * opaqueRegion: area of a surface that is fully opaque.
3054 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003056
3057 /*
3058 * visibleRegion: area of a surface that is visible on screen
3059 * and not fully transparent. This is essentially the layer's
3060 * footprint minus the opaque regions above it.
3061 * Areas covered by a translucent surface are considered visible.
3062 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003064
3065 /*
3066 * coveredRegion: area of a surface that is covered by all
3067 * visible regions above it (which includes the translucent areas).
3068 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003070
Jesse Halla8026d22012-09-25 13:25:04 -07003071 /*
3072 * transparentRegion: area of a surface that is hinted to be completely
3073 * transparent. This is only used to tell when the layer has no visible
3074 * non-transparent regions and can be removed from the layer list. It
3075 * does not affect the visibleRegion of this layer or any layers
3076 * beneath it. The hint may not be correct if apps don't respect the
3077 * SurfaceView restrictions (which, sadly, some don't).
3078 */
3079 Region transparentRegion;
3080
Mathias Agopianab028732010-03-16 16:41:46 -07003081
3082 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003083 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003084 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003085 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003086
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003088 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003089 if (!visibleRegion.isEmpty()) {
3090 // Remove the transparent area from the visible region
3091 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003092 if (tr.preserveRects()) {
3093 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003094 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003095 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003096 // transformation too complex, can't do the
3097 // transparent region optimization.
3098 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003099 }
Mathias Agopianab028732010-03-16 16:41:46 -07003100 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101
Mathias Agopianab028732010-03-16 16:41:46 -07003102 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003103 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003104 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003105 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003106 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003107 // the opaque region is the layer's footprint
3108 opaqueRegion = visibleRegion;
3109 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 }
3111 }
3112
Robert Carre5f4f692018-01-12 13:12:28 -08003113 if (visibleRegion.isEmpty()) {
3114 layer->clearVisibilityRegions();
3115 return;
3116 }
3117
Mathias Agopianab028732010-03-16 16:41:46 -07003118 // Clip the covered region to the visible region
3119 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3120
3121 // Update aboveCoveredLayers for next (lower) layer
3122 aboveCoveredLayers.orSelf(visibleRegion);
3123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124 // subtract the opaque region covered by the layers above us
3125 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126
3127 // compute this layer's dirty region
3128 if (layer->contentDirty) {
3129 // we need to invalidate the whole region
3130 dirty = visibleRegion;
3131 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003132 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133 layer->contentDirty = false;
3134 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003135 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003136 * the exposed region consists of two components:
3137 * 1) what's VISIBLE now and was COVERED before
3138 * 2) what's EXPOSED now less what was EXPOSED before
3139 *
3140 * note that (1) is conservative, we start with the whole
3141 * visible region but only keep what used to be covered by
3142 * something -- which mean it may have been exposed.
3143 *
3144 * (2) handles areas that were not covered by anything but got
3145 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003146 */
Mathias Agopianab028732010-03-16 16:41:46 -07003147 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003148 const Region oldVisibleRegion = layer->visibleRegion;
3149 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003150 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3151 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 }
3153 dirty.subtractSelf(aboveOpaqueLayers);
3154
3155 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003156 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157
Mathias Agopianab028732010-03-16 16:41:46 -07003158 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003160
Jesse Halla8026d22012-09-25 13:25:04 -07003161 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 layer->setVisibleRegion(visibleRegion);
3163 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003164 layer->setVisibleNonTransparentRegion(
3165 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003166 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003167
Mathias Agopian87baae12012-07-31 12:38:26 -07003168 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169}
3170
Chia-I Wuab0c3192017-08-01 11:29:00 -07003171void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003172 for (const auto& [token, displayDevice] : mDisplays) {
3173 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003174 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003175 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003176 }
3177 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003178}
3179
Daniel Solomon42d04562019-01-20 21:03:19 -08003180void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3181 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3182 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3183 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3184 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3185 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3186 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3187 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3188 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3189 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3190 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3191 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3192 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3193}
3194
Dan Stoza6b9454d2014-11-07 16:00:59 -08003195bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003197 ALOGV("handlePageFlip");
3198
Brian Andersond6927fb2016-07-23 23:37:30 -07003199 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200
Mathias Agopian4fec8732012-06-29 14:12:52 -07003201 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003202 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003203 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003204
3205 // Store the set of layers that need updates. This set must not change as
3206 // buffers are being latched, as this could result in a deadlock.
3207 // Example: Two producers share the same command stream and:
3208 // 1.) Layer 0 is latched
3209 // 2.) Layer 0 gets a new frame
3210 // 2.) Layer 1 gets a new frame
3211 // 3.) Layer 1 is latched.
3212 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3213 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003214 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003215 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003216 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003217 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003218 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003219 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003220 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003221 } else {
3222 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003223 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003224 } else {
3225 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003226 }
Robert Carr2047fae2016-11-28 14:09:09 -08003227 });
3228
Lloyd Piquef2c79392018-12-20 16:23:33 -08003229 if (!mLayersWithQueuedFrames.empty()) {
3230 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3231 // writes to Layer current state. See also b/119481871
3232 Mutex::Autolock lock(mStateLock);
3233
3234 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003235 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003236 mLayersPendingRefresh.push_back(layer);
3237 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003238 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003239 if (layer->isBufferLatched()) {
3240 newDataLatched = true;
3241 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003242 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003243 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003244
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003245 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003246
3247 // If we will need to wake up at some time in the future to deal with a
3248 // queued frame that shouldn't be displayed during this vsync period, wake
3249 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003250 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003251 signalLayerUpdate();
3252 }
3253
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003254 // enter boot animation on first buffer latch
3255 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3256 ALOGI("Enter boot animation");
3257 mBootStage = BootStage::BOOTANIMATION;
3258 }
3259
Dan Stoza6b9454d2014-11-07 16:00:59 -08003260 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003261 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262}
3263
Mathias Agopianad456f92011-01-13 17:53:01 -08003264void SurfaceFlinger::invalidateHwcGeometry()
3265{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003266 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003267}
3268
Lloyd Pique32cbe282018-10-19 13:09:22 -07003269void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003270 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003271 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003272 // We only need to actually compose the display if:
3273 // 1) It is being handled by hardware composer, which may need this to
3274 // keep its virtual display state machine in sync, or
3275 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003276 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003277 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003278 return;
3279 }
3280
Dan Stoza9e56aa02015-11-02 13:00:03 -08003281 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003282 base::unique_fd readyFence;
3283 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003284
3285 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003286 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287}
3288
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003289bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3290 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003291 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003292 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003293
Lloyd Pique32cbe282018-10-19 13:09:22 -07003294 auto display = displayDevice->getCompositionDisplay();
3295 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003296 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003297
3298 const Region bounds(displayState.bounds);
3299 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003300 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003301 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003302
Peiyong Lind3788632018-09-18 16:01:31 -07003303 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003304 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003305
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003306 renderengine::DisplaySettings clientCompositionDisplay;
3307 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3308 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003309
Dan Stoza9e56aa02015-11-02 13:00:03 -08003310 if (hasClientComposition) {
3311 ALOGV("hasClientComposition");
3312
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003313 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003314
3315 if (buf == nullptr) {
3316 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3317 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003318 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003319 return false;
3320 }
3321
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003322 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3323 clientCompositionDisplay.clip = displayState.scissor;
3324 const ui::Transform& displayTransform = displayState.transform;
3325 mat4 m;
3326 m[0][0] = displayTransform[0][0];
3327 m[0][1] = displayTransform[0][1];
3328 m[0][3] = displayTransform[0][2];
3329 m[1][0] = displayTransform[1][0];
3330 m[1][1] = displayTransform[1][1];
3331 m[1][3] = displayTransform[1][2];
3332 m[3][0] = displayTransform[2][0];
3333 m[3][1] = displayTransform[2][1];
3334 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003335
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003336 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003337
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003338 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003339 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003340 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003342 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003343 clientCompositionDisplay.outputDataspace = outputDataspace;
3344 clientCompositionDisplay.maxLuminance =
3345 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003346
Lloyd Pique441d5042018-10-18 16:49:51 -07003347 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003348 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003349 getHwComposer()
3350 .hasDisplayCapability(displayId,
3351 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003352
Peiyong Lind3788632018-09-18 16:01:31 -07003353 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003354 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3355 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003356 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003357 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003358 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003359
Mathias Agopian85d751c2012-08-29 16:59:24 -07003360 /*
3361 * and then, render the layers targeted at the framebuffer
3362 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003363
Dan Stoza9e56aa02015-11-02 13:00:03 -08003364 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003365 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003366 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003367 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003368 const Region viewportRegion(displayState.viewport);
3369 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003370 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003371 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003372 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003373 switch (layer->getCompositionType(displayDevice)) {
3374 case Hwc2::IComposerClient::Composition::CURSOR:
3375 case Hwc2::IComposerClient::Composition::DEVICE:
3376 case Hwc2::IComposerClient::Composition::SIDEBAND:
3377 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003378 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003379 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003380 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003381 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003382 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003383 // never clear the very first layer since we're
3384 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003385 renderengine::LayerSettings layerSettings;
3386 Region dummyRegion;
3387 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3388 layerSettings);
3389
3390 if (prepared) {
3391 layerSettings.source.buffer.buffer = nullptr;
3392 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3393 layerSettings.alpha = half(0.0);
3394 layerSettings.disableBlending = true;
3395 clientCompositionLayers.push_back(layerSettings);
3396 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003397 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003398 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003399 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003400 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003401 renderengine::LayerSettings layerSettings;
3402 bool prepared =
3403 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3404 if (prepared) {
3405 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003406 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003407 break;
3408 }
3409 default:
3410 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003411 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003412 } else {
3413 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003414 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003416 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003417
Alec Mouri820c7402019-01-23 13:02:39 -08003418 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003419 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003420 clientCompositionDisplay.clearRegion = clearRegion;
3421 if (!debugRegion.isEmpty()) {
3422 Region::const_iterator it = debugRegion.begin();
3423 Region::const_iterator end = debugRegion.end();
3424 while (it != end) {
3425 const Rect& rect = *it++;
3426 renderengine::LayerSettings layerSettings;
3427 layerSettings.source.buffer.buffer = nullptr;
3428 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3429 layerSettings.geometry.boundaries = rect.toFloatRect();
3430 layerSettings.alpha = half(1.0);
3431 clientCompositionLayers.push_back(layerSettings);
3432 }
3433 }
3434 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3435 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003436 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003437 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438}
3439
Chia-I Wu28e3a252018-09-07 12:05:02 -07003440void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003441 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003442 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003443}
3444
Dan Stoza7d89d062015-04-30 13:29:25 -07003445status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003446 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003447 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003448 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003449 const sp<Layer>& parent,
3450 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003451{
Dan Stoza7d89d062015-04-30 13:29:25 -07003452 // add this layer to the current state list
3453 {
3454 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003455 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003456 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3457 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003458 return NO_MEMORY;
3459 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003460 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003461 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003462 } else if (parent == nullptr) {
3463 lbc->onRemovedFromCurrentState();
3464 } else if (parent->isRemovedFromCurrentState()) {
3465 parent->addChild(lbc);
3466 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003467 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003468 parent->addChild(lbc);
3469 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003470
Yiwei Zhang243b3782018-05-15 17:40:04 -07003471 if (gbc != nullptr) {
3472 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3473 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3474 mMaxGraphicBufferProducerListSize,
3475 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3476 mGraphicBufferProducerList.size(),
3477 mMaxGraphicBufferProducerListSize, mNumLayers);
3478 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 }
3481
Mathias Agopian96f08192010-06-02 23:28:45 -07003482 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003483 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003484
Dan Stoza7d89d062015-04-30 13:29:25 -07003485 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003486}
3487
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003488uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003489 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003490}
3491
Mathias Agopian3f844832013-08-07 21:24:32 -07003492uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003493 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003494}
3495
Mathias Agopian3f844832013-08-07 21:24:32 -07003496uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003497 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003498}
3499
3500uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003501 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003502 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003503 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003505 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 }
3507 return old;
3508}
3509
Marissa Wall713b63f2018-10-17 15:42:43 -07003510bool SurfaceFlinger::flushTransactionQueues() {
3511 Mutex::Autolock _l(mStateLock);
3512 auto it = mTransactionQueues.begin();
3513 while (it != mTransactionQueues.end()) {
3514 auto& [applyToken, transactionQueue] = *it;
3515
3516 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003517 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3518 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003519 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003520 break;
3521 }
Robert Carr14167e02019-02-13 13:50:55 -08003522 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003523 transactionQueue.pop();
3524 }
3525
3526 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3527 }
3528 return mTransactionQueues.empty();
3529}
3530
chaviwca27f252018-02-06 16:46:39 -08003531bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3532 for (const ComposerState& state : states) {
3533 // Here we need to check that the interface we're given is indeed
3534 // one of our own. A malicious client could give us a nullptr
3535 // IInterface, or one of its own or even one of our own but a
3536 // different type. All these situations would cause us to crash.
3537 if (state.client == nullptr) {
3538 return true;
3539 }
3540
3541 sp<IBinder> binder = IInterface::asBinder(state.client);
3542 if (binder == nullptr) {
3543 return true;
3544 }
3545
3546 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3547 return true;
3548 }
3549 }
3550 return false;
3551}
3552
Marissa Wall17b4e452018-12-26 16:32:34 -08003553bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3554 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003555 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003556 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3557 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3558 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3559 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3560 return false;
3561 }
3562
Marissa Wall713b63f2018-10-17 15:42:43 -07003563 for (const ComposerState& state : states) {
3564 const layer_state_t& s = state.state;
3565 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3566 continue;
3567 }
3568 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003569 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003570 }
3571 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003572 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003573}
3574
3575void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3576 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003577 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003578 const InputWindowCommands& inputWindowCommands,
3579 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003580 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003581
3582 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3583
Mathias Agopian698c0872011-06-28 19:09:31 -07003584 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003585
chaviwca27f252018-02-06 16:46:39 -08003586 if (containsAnyInvalidClientState(states)) {
3587 return;
3588 }
3589
Marissa Wall713b63f2018-10-17 15:42:43 -07003590 // If its TransactionQueue already has a pending TransactionState or if it is pending
3591 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003592 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003593 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3594 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003595 setTransactionFlags(eTransactionNeeded);
3596 return;
3597 }
3598
Robert Carr14167e02019-02-13 13:50:55 -08003599 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003600}
3601
3602void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003603 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003604 const InputWindowCommands& inputWindowCommands,
3605 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003606 uint32_t transactionFlags = 0;
3607
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003608 if (flags & eAnimation) {
3609 // For window updates that are part of an animation we must wait for
3610 // previous animation "frames" to be handled.
3611 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003612 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003613 if (CC_UNLIKELY(err != NO_ERROR)) {
3614 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003615 // caller after a few seconds.
3616 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3617 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003618 mAnimTransactionPending = false;
3619 break;
3620 }
3621 }
3622 }
3623
chaviwca27f252018-02-06 16:46:39 -08003624 for (const DisplayState& display : displays) {
3625 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003626 }
3627
Marissa Walle2ffb422018-10-12 11:33:52 -07003628 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003629 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003630 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003631 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003632 // If the state doesn't require a traversal and there are callbacks, send them now
3633 if (!(clientStateFlags & eTraversalNeeded)) {
3634 mTransactionCompletedThread.sendCallbacks();
3635 }
3636 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003637
chaviw273171b2018-12-26 11:46:30 -08003638 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3639
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003640 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3641 // anyway. This can be used as a flush mechanism for previous async transactions.
3642 // Empty animation transaction can be used to simulate back-pressure, so also force a
3643 // transaction for empty animation transactions.
3644 if (transactionFlags == 0 &&
3645 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003646 transactionFlags = eTransactionNeeded;
3647 }
3648
Mathias Agopian386aa982011-11-07 21:58:03 -08003649 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003650 if (mInterceptor->isEnabled()) {
3651 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003652 }
Irvel468051e2016-06-13 16:44:44 -07003653
Mathias Agopian386aa982011-11-07 21:58:03 -08003654 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003655 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3656 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003657 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003658
3659 // if this is a synchronous transaction, wait for it to take effect
3660 // before returning.
3661 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003662 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003663 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003664 if (flags & eAnimation) {
3665 mAnimTransactionPending = true;
3666 }
3667 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003668 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3669 if (CC_UNLIKELY(err != NO_ERROR)) {
3670 // just in case something goes wrong in SF, return to the
3671 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003672 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3673 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003674 break;
3675 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003676 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003677 }
3678}
3679
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003680uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3681 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3682 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003683
Mathias Agopiane57f2922012-08-09 16:29:12 -07003684 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003685 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3686
3687 const uint32_t what = s.what;
3688 if (what & DisplayState::eSurfaceChanged) {
3689 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3690 state.surface = s.surface;
3691 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003692 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003693 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003694 if (what & DisplayState::eLayerStackChanged) {
3695 if (state.layerStack != s.layerStack) {
3696 state.layerStack = s.layerStack;
3697 flags |= eDisplayTransactionNeeded;
3698 }
3699 }
3700 if (what & DisplayState::eDisplayProjectionChanged) {
3701 if (state.orientation != s.orientation) {
3702 state.orientation = s.orientation;
3703 flags |= eDisplayTransactionNeeded;
3704 }
3705 if (state.frame != s.frame) {
3706 state.frame = s.frame;
3707 flags |= eDisplayTransactionNeeded;
3708 }
3709 if (state.viewport != s.viewport) {
3710 state.viewport = s.viewport;
3711 flags |= eDisplayTransactionNeeded;
3712 }
3713 }
3714 if (what & DisplayState::eDisplaySizeChanged) {
3715 if (state.width != s.width) {
3716 state.width = s.width;
3717 flags |= eDisplayTransactionNeeded;
3718 }
3719 if (state.height != s.height) {
3720 state.height = s.height;
3721 flags |= eDisplayTransactionNeeded;
3722 }
3723 }
3724
Mathias Agopiane57f2922012-08-09 16:29:12 -07003725 return flags;
3726}
3727
Robert Carr14167e02019-02-13 13:50:55 -08003728bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003729 IPCThreadState* ipc = IPCThreadState::self();
3730 const int pid = ipc->getCallingPid();
3731 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003732 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003733 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003734 return false;
3735 }
3736 return true;
3737}
3738
Robert Carr14167e02019-02-13 13:50:55 -08003739uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3740 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003741 const layer_state_t& s = composerState.state;
3742 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3743
Mathias Agopian13127d82013-03-05 17:47:11 -08003744 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003745 if (layer == nullptr) {
3746 return 0;
3747 }
3748
chaviw8b3871a2017-11-01 17:41:01 -07003749 uint32_t flags = 0;
3750
Garfield Tan8a3083e2018-12-03 13:21:07 -08003751 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003752 bool geometryAppliesWithResize =
3753 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003754
3755 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3756 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003757 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003758 layer->pushPendingState();
3759 }
3760
chaviw8b3871a2017-11-01 17:41:01 -07003761 if (what & layer_state_t::ePositionChanged) {
3762 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3763 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003764 }
chaviw8b3871a2017-11-01 17:41:01 -07003765 }
3766 if (what & layer_state_t::eLayerChanged) {
3767 // NOTE: index needs to be calculated before we update the state
3768 const auto& p = layer->getParent();
3769 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003770 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003771 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003772 mCurrentState.layersSortedByZ.removeAt(idx);
3773 mCurrentState.layersSortedByZ.add(layer);
3774 // we need traversal (state changed)
3775 // AND transaction (list changed)
3776 flags |= eTransactionNeeded|eTraversalNeeded;
3777 }
chaviw8b3871a2017-11-01 17:41:01 -07003778 } else {
3779 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003780 flags |= eTransactionNeeded|eTraversalNeeded;
3781 }
3782 }
chaviw8b3871a2017-11-01 17:41:01 -07003783 }
3784 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003785 // NOTE: index needs to be calculated before we update the state
3786 const auto& p = layer->getParent();
3787 if (p == nullptr) {
3788 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3789 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3790 mCurrentState.layersSortedByZ.removeAt(idx);
3791 mCurrentState.layersSortedByZ.add(layer);
3792 // we need traversal (state changed)
3793 // AND transaction (list changed)
3794 flags |= eTransactionNeeded|eTraversalNeeded;
3795 }
3796 } else {
3797 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3798 flags |= eTransactionNeeded|eTraversalNeeded;
3799 }
chaviw8b3871a2017-11-01 17:41:01 -07003800 }
3801 }
3802 if (what & layer_state_t::eSizeChanged) {
3803 if (layer->setSize(s.w, s.h)) {
3804 flags |= eTraversalNeeded;
3805 }
3806 }
3807 if (what & layer_state_t::eAlphaChanged) {
3808 if (layer->setAlpha(s.alpha))
3809 flags |= eTraversalNeeded;
3810 }
3811 if (what & layer_state_t::eColorChanged) {
3812 if (layer->setColor(s.color))
3813 flags |= eTraversalNeeded;
3814 }
Peiyong Lind3788632018-09-18 16:01:31 -07003815 if (what & layer_state_t::eColorTransformChanged) {
3816 if (layer->setColorTransform(s.colorTransform)) {
3817 flags |= eTraversalNeeded;
3818 }
3819 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003820 if (what & layer_state_t::eBackgroundColorChanged) {
3821 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3822 flags |= eTraversalNeeded;
3823 }
3824 }
chaviw8b3871a2017-11-01 17:41:01 -07003825 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003826 // TODO: b/109894387
3827 //
3828 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3829 // rotation. To see the problem observe that if we have a square parent, and a child
3830 // of the same size, then we rotate the child 45 degrees around it's center, the child
3831 // must now be cropped to a non rectangular 8 sided region.
3832 //
3833 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3834 // private API, and the WindowManager only uses rotation in one case, which is on a top
3835 // level layer in which cropping is not an issue.
3836 //
3837 // However given that abuse of rotation matrices could lead to surfaces extending outside
3838 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3839 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3840 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003841 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003842 flags |= eTraversalNeeded;
3843 }
3844 if (what & layer_state_t::eTransparentRegionChanged) {
3845 if (layer->setTransparentRegionHint(s.transparentRegion))
3846 flags |= eTraversalNeeded;
3847 }
3848 if (what & layer_state_t::eFlagsChanged) {
3849 if (layer->setFlags(s.flags, s.mask))
3850 flags |= eTraversalNeeded;
3851 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003852 if (what & layer_state_t::eCropChanged_legacy) {
3853 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003854 flags |= eTraversalNeeded;
3855 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003856 if (what & layer_state_t::eCornerRadiusChanged) {
3857 if (layer->setCornerRadius(s.cornerRadius))
3858 flags |= eTraversalNeeded;
3859 }
chaviw8b3871a2017-11-01 17:41:01 -07003860 if (what & layer_state_t::eLayerStackChanged) {
3861 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3862 // We only allow setting layer stacks for top level layers,
3863 // everything else inherits layer stack from its parent.
3864 if (layer->hasParent()) {
3865 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3866 layer->getName().string());
3867 } else if (idx < 0) {
3868 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3869 "that also does not appear in the top level layer list. Something"
3870 " has gone wrong.", layer->getName().string());
3871 } else if (layer->setLayerStack(s.layerStack)) {
3872 mCurrentState.layersSortedByZ.removeAt(idx);
3873 mCurrentState.layersSortedByZ.add(layer);
3874 // we need traversal (state changed)
3875 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003876 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003877 }
3878 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003879 if (what & layer_state_t::eDeferTransaction_legacy) {
3880 if (s.barrierHandle_legacy != nullptr) {
3881 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3882 } else if (s.barrierGbp_legacy != nullptr) {
3883 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003884 if (authenticateSurfaceTextureLocked(gbp)) {
3885 const auto& otherLayer =
3886 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003887 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003888 } else {
3889 ALOGE("Attempt to defer transaction to to an"
3890 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003891 }
3892 }
chaviw8b3871a2017-11-01 17:41:01 -07003893 // We don't trigger a traversal here because if no other state is
3894 // changed, we don't want this to cause any more work
3895 }
3896 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003897 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003898 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003899 if (!hadParent) {
3900 mCurrentState.layersSortedByZ.remove(layer);
3901 }
chaviw8b3871a2017-11-01 17:41:01 -07003902 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003903 }
chaviw8b3871a2017-11-01 17:41:01 -07003904 }
3905 if (what & layer_state_t::eReparentChildren) {
3906 if (layer->reparentChildren(s.reparentHandle)) {
3907 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003908 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (what & layer_state_t::eDetachChildren) {
3911 layer->detachChildren();
3912 }
3913 if (what & layer_state_t::eOverrideScalingModeChanged) {
3914 layer->setOverrideScalingMode(s.overrideScalingMode);
3915 // We don't trigger a traversal here because if no other state is
3916 // changed, we don't want this to cause any more work
3917 }
Marissa Wall61c58622018-07-18 10:12:20 -07003918 if (what & layer_state_t::eTransformChanged) {
3919 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3920 }
3921 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3922 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3923 flags |= eTraversalNeeded;
3924 }
3925 if (what & layer_state_t::eCropChanged) {
3926 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3927 }
Marissa Wall861616d2018-10-22 12:52:23 -07003928 if (what & layer_state_t::eFrameChanged) {
3929 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3930 }
Marissa Wall61c58622018-07-18 10:12:20 -07003931 if (what & layer_state_t::eAcquireFenceChanged) {
3932 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3933 }
3934 if (what & layer_state_t::eDataspaceChanged) {
3935 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3936 }
3937 if (what & layer_state_t::eHdrMetadataChanged) {
3938 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3939 }
3940 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3941 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3942 }
3943 if (what & layer_state_t::eApiChanged) {
3944 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3945 }
3946 if (what & layer_state_t::eSidebandStreamChanged) {
3947 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3948 }
Robert Carr720e5062018-07-30 17:45:14 -07003949 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003950 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3951 layer->setInputInfo(s.inputInfo);
3952 flags |= eTraversalNeeded;
3953 } else {
3954 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3955 }
Robert Carr720e5062018-07-30 17:45:14 -07003956 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003957 if (what & layer_state_t::eMetadataChanged) {
3958 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3959 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003960 std::vector<sp<CallbackHandle>> callbackHandles;
3961 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3962 mTransactionCompletedThread.run();
3963 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3964 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3965 }
3966 }
Marissa Wall73411622019-01-25 10:45:41 -08003967
3968 if (what & layer_state_t::eBufferChanged) {
3969 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3970 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3971 s.buffer);
3972 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003973 if (what & layer_state_t::eCachedBufferChanged) {
3974 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003975 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3976 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003977 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3978 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003979 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3980 // Do not put anything that updates layer state or modifies flags after
3981 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003982 return flags;
3983}
3984
chaviw273171b2018-12-26 11:46:30 -08003985uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3986 uint32_t flags = 0;
3987 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3988 flags |= eTraversalNeeded;
3989 }
3990
chaviwa911b102019-02-14 10:18:33 -08003991 if (inputWindowCommands.syncInputWindows) {
3992 flags |= eTraversalNeeded;
3993 }
3994
Vishnu Nairec0ab382019-02-13 15:32:56 -08003995 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003996 return flags;
3997}
3998
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003999status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4000 uint32_t h, PixelFormat format, uint32_t flags,
4001 LayerMetadata metadata, sp<IBinder>* handle,
4002 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004003 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004004 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004005 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004007 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004008
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009 status_t result = NO_ERROR;
4010
4011 sp<Layer> layer;
4012
Cody Northropbc755282017-03-31 12:00:08 -06004013 String8 uniqueName = getUniqueLayerName(name);
4014
Mathias Agopian3165cc22012-08-08 19:42:09 -07004015 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004016 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004017 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4018 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004019
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004021 case ISurfaceComposerClient::eFXSurfaceBufferState:
4022 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4023 break;
chaviw13fdc492017-06-27 12:40:18 -07004024 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004025 // check if buffer size is set for color layer.
4026 if (w > 0 || h > 0) {
4027 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4028 int(w), int(h));
4029 return BAD_VALUE;
4030 }
4031
chaviw13fdc492017-06-27 12:40:18 -07004032 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004033 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004034 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004036 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004037 // check if buffer size is set for container layer.
4038 if (w > 0 || h > 0) {
4039 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4040 int(w), int(h));
4041 return BAD_VALUE;
4042 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004043 result = createContainerLayer(client,
4044 uniqueName, w, h, flags,
4045 handle, &layer);
4046 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004047 default:
4048 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004049 break;
4050 }
4051
Dan Stoza7d89d062015-04-30 13:29:25 -07004052 if (result != NO_ERROR) {
4053 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004054 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004055
Chia-I Wuab0c3192017-08-01 11:29:00 -07004056 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4057 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004058 if (metadata.has(METADATA_WINDOW_TYPE)) {
4059 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4060 if (windowType == 441731) {
4061 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4062 layer->setPrimaryDisplayOnly();
4063 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004064 }
4065
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004066 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004067
Robert Carrb89ea9d2018-12-10 13:01:14 -08004068 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4069 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4070 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004071 if (result != NO_ERROR) {
4072 return result;
4073 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004074 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004075
4076 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004077 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004078}
4079
Cody Northropbc755282017-03-31 12:00:08 -06004080String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4081{
4082 bool matchFound = true;
4083 uint32_t dupeCounter = 0;
4084
4085 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4086 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4087
Dan Stoza436ccf32018-06-21 12:10:12 -07004088 // Grab the state lock since we're accessing mCurrentState
4089 Mutex::Autolock lock(mStateLock);
4090
Cody Northropbc755282017-03-31 12:00:08 -06004091 // Loop over layers until we're sure there is no matching name
4092 while (matchFound) {
4093 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004094 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004095 if (layer->getName() == uniqueName) {
4096 matchFound = true;
4097 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4098 }
4099 });
4100 }
4101
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004102 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4103 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004104
4105 return uniqueName;
4106}
4107
Marissa Wallfd668622018-05-10 10:21:13 -07004108status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4109 uint32_t w, uint32_t h, uint32_t flags,
4110 PixelFormat& format, sp<IBinder>* handle,
4111 sp<IGraphicBufferProducer>* gbp,
4112 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004114 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004115 case PIXEL_FORMAT_TRANSPARENT:
4116 case PIXEL_FORMAT_TRANSLUCENT:
4117 format = PIXEL_FORMAT_RGBA_8888;
4118 break;
4119 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004120 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004121 break;
4122 }
4123
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004124 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004125 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004126 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004127 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004128 *handle = layer->getHandle();
4129 *gbp = layer->getProducer();
4130 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004131 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004132
Marissa Wallfd668622018-05-10 10:21:13 -07004133 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004134 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004135}
4136
Marissa Wall61c58622018-07-18 10:12:20 -07004137status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4138 uint32_t w, uint32_t h, uint32_t flags,
4139 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004140 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004141 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004142 *handle = layer->getHandle();
4143 *outLayer = layer;
4144
4145 return NO_ERROR;
4146}
4147
chaviw13fdc492017-06-27 12:40:18 -07004148status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004149 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004150 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004151{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004152 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004153 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004154 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004155}
4156
Robert Carr6b3f6c52018-08-13 13:05:17 -07004157status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4158 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4159 sp<IBinder>* handle, sp<Layer>* outLayer)
4160{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004161 *outLayer =
4162 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004163 *handle = (*outLayer)->getHandle();
4164 return NO_ERROR;
4165}
4166
4167
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004168void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004169 mLayersPendingRemoval.add(layer);
4170 mLayersRemoved = true;
4171 setTransactionFlags(eTransactionNeeded);
4172}
4173
Robert Carr695d5282018-12-18 15:27:58 -08004174void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004175{
Robert Carr2e102c92018-10-23 12:11:15 -07004176 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004177 // If a layer has a parent, we allow it to out-live it's handle
4178 // with the idea that the parent holds a reference and will eventually
4179 // be cleaned up. However no one cleans up the top-level so we do so
4180 // here.
4181 if (layer->getParent() == nullptr) {
4182 mCurrentState.layersSortedByZ.remove(layer);
4183 }
4184 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004185 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004186}
4187
Mathias Agopianb60314a2012-04-10 22:09:54 -07004188// ---------------------------------------------------------------------------
4189
Andy McFadden13a082e2012-08-24 10:16:42 -07004190void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004191 const auto display = getDefaultDisplayDeviceLocked();
4192 if (!display) return;
4193
4194 const sp<IBinder> token = display->getDisplayToken().promote();
4195 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004196
Jesse Hall01e29052013-02-19 16:13:35 -08004197 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004198 Vector<ComposerState> state;
4199 Vector<DisplayState> displays;
4200 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004201 d.what = DisplayState::eDisplayProjectionChanged |
4202 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004203 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004204 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004205 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004206 d.frame.makeInvalid();
4207 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004208 d.width = 0;
4209 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004210 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004211 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004212
Dominik Laskowskie9774092018-12-11 10:04:24 -08004213 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004214
Dominik Laskowski83b88212018-12-11 13:34:06 -08004215 const nsecs_t vsyncPeriod = getVsyncPeriod();
4216 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004217
Brian Andersond0010582017-03-07 13:20:31 -08004218 // Use phase of 0 since phase is not known.
4219 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004221 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004222}
4223
4224void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004225 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004226 postMessageAsync(
4227 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004228}
4229
Dominik Laskowskie9774092018-12-11 10:04:24 -08004230void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004231 if (display->isVirtual()) {
4232 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004233 return;
4234 }
4235
Dominik Laskowski075d3172018-05-24 15:50:06 -07004236 const auto displayId = display->getId();
4237 LOG_ALWAYS_FATAL_IF(!displayId);
4238
Dominik Laskowski34157762018-10-31 13:07:19 -07004239 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004240
4241 int currentMode = display->getPowerMode();
4242 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004243 return;
4244 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004245
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004246 display->setPowerMode(mode);
4247
Lloyd Pique4dccc412018-01-22 17:21:36 -08004248 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004249 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004250 }
4251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004252 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004253 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004254 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004255 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004256 mScheduler->onScreenAcquired(mAppConnectionHandle);
4257 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004258 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004259
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004260 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004261 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004262 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004263
4264 struct sched_param param = {0};
4265 param.sched_priority = 1;
4266 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4267 ALOGW("Couldn't set SCHED_FIFO on display on");
4268 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004269 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004270 // Turn off the display
4271 struct sched_param param = {0};
4272 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4273 ALOGW("Couldn't set SCHED_OTHER on display off");
4274 }
4275
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004276 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004277 mScheduler->disableHardwareVsync(true);
4278 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004279 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280
Dominik Laskowski075d3172018-05-24 15:50:06 -07004281 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004282 mVisibleRegionsDirty = true;
4283 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004284 } else if (mode == HWC_POWER_MODE_DOZE ||
4285 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004286 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004287 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004289 mScheduler->onScreenAcquired(mAppConnectionHandle);
4290 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004291 }
4292 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4293 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004294 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004295 mScheduler->disableHardwareVsync(true);
4296 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004297 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004299 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004300 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004301 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004302 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004303
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004304 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004305 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004306 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004307 // Update refresh rate stats.
4308 mRefreshRateStats->setPowerMode(mode);
4309 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004310 }
4311
Dominik Laskowski34157762018-10-31 13:07:19 -07004312 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004313}
4314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004316 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004317 const auto display = getDisplayDevice(displayToken);
4318 if (!display) {
4319 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4320 displayToken.get());
4321 } else if (display->isVirtual()) {
4322 ALOGW("Attempt to set power mode %d for virtual display", mode);
4323 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004324 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004325 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004327}
4328
4329// ---------------------------------------------------------------------------
4330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4332 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004333 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004334
Mathias Agopianbd115332013-04-18 16:41:04 -07004335 IPCThreadState* ipc = IPCThreadState::self();
4336 const int pid = ipc->getCallingPid();
4337 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004338
Mathias Agopianbd115332013-04-18 16:41:04 -07004339 if ((uid != AID_SHELL) &&
4340 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004341 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4342 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004343 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004344 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004345 // (this would indicate SF is stuck, but we want to be able to
4346 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004347 status_t err = mStateLock.timedLock(s2ns(1));
4348 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004349 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350 StringAppendF(&result,
4351 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4352 "(no locks held)\n",
4353 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004354 }
4355
Dominik Laskowskic2867142019-01-21 11:33:38 -08004356 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004357
Dominik Laskowskic2867142019-01-21 11:33:38 -08004358 static const std::unordered_map<std::string, Dumper> dumpers = {
4359 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4360 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4361 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004362 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004363 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004364 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004365 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4366 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004367 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4368 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4369 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4370 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4371 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4372 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004373 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004374 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4375 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004376
Dominik Laskowskic2867142019-01-21 11:33:38 -08004377 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004378
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4380 (it->second)(args, asProto, result);
4381 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004382 if (asProto) {
4383 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4384 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4385 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004386 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004387 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004388 }
4389
Mathias Agopian9795c422009-08-26 16:36:26 -07004390 if (locked) {
4391 mStateLock.unlock();
4392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004393 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004395 return NO_ERROR;
4396}
4397
Dominik Laskowskic2867142019-01-21 11:33:38 -08004398void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004399 mCurrentState.traverseInZOrder(
4400 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004401}
4402
Dominik Laskowskic2867142019-01-21 11:33:38 -08004403void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004404 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004405
Dominik Laskowskic2867142019-01-21 11:33:38 -08004406 if (args.size() > 1) {
4407 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004408 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004409 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004410 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004411 }
Robert Carr2047fae2016-11-28 14:09:09 -08004412 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004413 } else {
4414 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004415 }
4416}
4417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004419 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004420 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004421 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004422 }
Robert Carr2047fae2016-11-28 14:09:09 -08004423 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004424
Svetoslavd85084b2014-03-20 10:28:31 -07004425 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004426}
4427
Dominik Laskowskic2867142019-01-21 11:33:38 -08004428void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4429 mTimeStats->parseArgs(asProto, args, result);
4430}
4431
Jamie Gennis6547ff42013-07-16 20:12:42 -07004432// This should only be called from the main thread. Otherwise it would need
4433// the lock and should use mCurrentState rather than mDrawingState.
4434void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004435 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004436 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004437 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004438
4439 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4440}
4441
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004443 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004444
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004445 if (isLayerTripleBufferingDisabled())
4446 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004447
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4449 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4450 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4451 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4452 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4453 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004454 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004455}
4456
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004457void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004458 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004459 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004460 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004461 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004462
Ana Krulecc2870422019-01-29 19:00:58 -08004463 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n\n", mUse90Hz ? "on" : "off");
4464 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004465}
4466
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4468 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004469 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4470 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004471 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004472 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004474 }
David Sodman4a36e932017-11-07 14:29:47 -08004475 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004476 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004477 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4479 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004480}
4481
Dan Stozae77c7662016-05-13 11:37:28 -07004482void SurfaceFlinger::recordBufferingStats(const char* layerName,
4483 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004484 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4485 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004486 for (const auto& segment : history) {
4487 if (!segment.usedThirdBuffer) {
4488 stats.twoBufferTime += segment.totalTime;
4489 }
4490 if (segment.occupancyAverage < 1.0f) {
4491 stats.doubleBufferedTime += segment.totalTime;
4492 } else if (segment.occupancyAverage < 2.0f) {
4493 stats.tripleBufferedTime += segment.totalTime;
4494 }
4495 ++stats.numSegments;
4496 stats.totalTime += segment.totalTime;
4497 }
4498}
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4501 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004502
4503 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4504 const size_t count = currentLayers.size();
4505 for (size_t i=0 ; i<count ; i++) {
4506 currentLayers[i]->dumpFrameEvents(result);
4507 }
4508}
4509
Yiwei Zhang5434a782018-12-05 18:06:32 -08004510void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004511 result.append("Buffering stats:\n");
4512 result.append(" [Layer name] <Active time> <Two buffer> "
4513 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004514 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004515 typedef std::tuple<std::string, float, float, float> BufferTuple;
4516 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004517 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004518 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004519 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004520 if (stats.numSegments == 0) {
4521 continue;
4522 }
4523 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4524 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4525 stats.totalTime;
4526 float doubleBufferRatio = static_cast<float>(
4527 stats.doubleBufferedTime) / stats.totalTime;
4528 float tripleBufferRatio = static_cast<float>(
4529 stats.tripleBufferedTime) / stats.totalTime;
4530 sorted.insert({activeTime, {name, twoBufferRatio,
4531 doubleBufferRatio, tripleBufferRatio}});
4532 }
4533 for (const auto& sortedPair : sorted) {
4534 float activeTime = sortedPair.first;
4535 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004536 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4537 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004538 }
4539 result.append("\n");
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004543 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004544 const auto displayId = display->getId();
4545 if (!displayId) {
4546 continue;
4547 }
4548 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004549 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004550 continue;
4551 }
4552
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result,
4554 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4555 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004556 uint8_t port;
4557 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004558 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004559 result.append("no identification data\n");
4560 continue;
4561 }
4562
4563 if (!isEdid(data)) {
4564 result.append("unknown identification data: ");
4565 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004567 }
4568 result.append("\n");
4569 continue;
4570 }
4571
4572 const auto edid = parseEdid(data);
4573 if (!edid) {
4574 result.append("invalid EDID: ");
4575 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004576 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004577 }
4578 result.append("\n");
4579 continue;
4580 }
4581
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004583 result.append(edid->displayName.data(), edid->displayName.length());
4584 result.append("\"\n");
4585 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004586}
4587
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4589 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4590 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4591 StringAppendF(&result, "DisplayColorSetting: %s\n",
4592 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004593
4594 // TODO: print out if wide-color mode is active or not
4595
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004596 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004597 const auto displayId = display->getId();
4598 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004599 continue;
4600 }
4601
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004603 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004604 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004605 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004606 }
4607
Lloyd Pique32cbe282018-10-19 13:09:22 -07004608 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, " Current color mode: %s (%d)\n",
4610 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004611 }
4612 result.append("\n");
4613}
4614
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004615LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004616 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004617 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4618 const State& state = useDrawing ? mDrawingState : mCurrentState;
4619 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004620 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004621 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004622 });
4623
4624 return layersProto;
4625}
4626
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004627LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4628 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004629 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004630
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004631 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004632 resolution->set_w(displayDevice->getWidth());
4633 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004634
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004635 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004636 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004637
Lloyd Pique32cbe282018-10-19 13:09:22 -07004638 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4639 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4640 layersProto.set_global_transform(displayState.orientation);
4641
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004642 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004643 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004644 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004645 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004646 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004647 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004648 }
4649 });
4650
4651 return layersProto;
4652}
4653
Dominik Laskowskic2867142019-01-21 11:33:38 -08004654void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4655 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004656 Colorizer colorizer(colorize);
4657
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004658 // figure out if we're stuck somewhere
4659 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004660 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004661 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4662
4663 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004664 * Dump library configuration.
4665 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004666
4667 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004668 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004669 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004670 appendSfConfigString(result);
4671 appendUiConfigString(result);
4672 appendGuiConfigString(result);
4673 result.append("\n");
4674
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004675 result.append("\nDisplay identification data:\n");
4676 dumpDisplayIdentificationData(result);
4677
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004678 result.append("\nWide-Color information:\n");
4679 dumpWideColorInfo(result);
4680
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004681 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004682 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004683 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004684 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004685 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004686
Andy McFadden41d67d72014-04-25 16:58:34 -07004687 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004688 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004689 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004690 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004691 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004692
Dan Stozab90cf072015-03-05 11:05:59 -08004693 dumpStaticScreenStats(result);
4694 result.append("\n");
4695
Yiwei Zhang5434a782018-12-05 18:06:32 -08004696 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004697
Dan Stozae77c7662016-05-13 11:37:28 -07004698 dumpBufferingStats(result);
4699
Andy McFadden4803b742012-09-24 19:07:20 -07004700 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701 * Dump the visible layer list
4702 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4705 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4706 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004707 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004708
Chia-I Wu2f884132018-09-13 15:17:58 -07004709 {
4710 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4711 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004713 result.append("\n");
4714 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715
4716 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004717 * Dump Display state
4718 */
4719
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004722 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004723 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004724 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004725 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004726 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004727
4728 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729 * Dump SurfaceFlinger global state
4730 */
4731
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004732 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004733 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004734 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004735
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004736 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004739 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4740 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004741 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4742 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004743 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004744 StringAppendF(&result,
4745 " transaction-flags : %08x\n"
4746 " gpu_to_cpu_unsupported : %d\n",
4747 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004748
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004749 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004750 displayId && getHwComposer().isConnected(*displayId)) {
4751 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004752 StringAppendF(&result,
4753 " refresh-rate : %f fps\n"
4754 " x-dpi : %f\n"
4755 " y-dpi : %f\n",
4756 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4757 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004758 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004759
Yiwei Zhang5434a782018-12-05 18:06:32 -08004760 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004761
Dan Stozae22aec72016-08-01 13:20:59 -07004762 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004763 * Tracing state
4764 */
4765 mTracing.dump(result);
4766 result.append("\n");
4767
4768 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004769 * HWC layer minidump
4770 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004771 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004772 const auto displayId = display->getId();
4773 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004774 continue;
4775 }
4776
Yiwei Zhang5434a782018-12-05 18:06:32 -08004777 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004778 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004779 const sp<DisplayDevice> displayDevice = display;
4780 mCurrentState.traverseInZOrder(
4781 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004782 result.append("\n");
4783 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004784
4785 /*
4786 * Dump HWComposer state
4787 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004788 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004789 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004790 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004791 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004793 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004794
4795 /*
4796 * Dump gralloc state
4797 */
4798 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4799 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004800
4801 /*
4802 * Dump VrFlinger state if in use.
4803 */
4804 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4805 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004807 result.append("\n");
4808 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004809
4810 /**
4811 * Scheduler dump state.
4812 */
Ana Krulecc2870422019-01-29 19:00:58 -08004813 result.append("\nScheduler state:\n");
4814 result.append(mScheduler->doDump() + "\n");
4815 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004816}
4817
Dominik Laskowski075d3172018-05-24 15:50:06 -07004818const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004819 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004820 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004821 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004822 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004823 }
4824 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004825
Dominik Laskowski34157762018-10-31 13:07:19 -07004826 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004827 static const Vector<sp<Layer>> empty;
4828 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004829}
4830
Chia-I Wu28f320b2018-05-03 11:02:56 -07004831void SurfaceFlinger::updateColorMatrixLocked() {
4832 mat4 colorMatrix;
4833 if (mGlobalSaturationFactor != 1.0f) {
4834 // Rec.709 luma coefficients
4835 float3 luminance{0.213f, 0.715f, 0.072f};
4836 luminance *= 1.0f - mGlobalSaturationFactor;
4837 mat4 saturationMatrix = mat4(
4838 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4839 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4840 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4841 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4842 );
4843 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4844 } else {
4845 colorMatrix = mClientColorMatrix * mDaltonizer();
4846 }
4847
4848 if (mCurrentState.colorMatrix != colorMatrix) {
4849 mCurrentState.colorMatrix = colorMatrix;
4850 mCurrentState.colorMatrixChanged = true;
4851 setTransactionFlags(eTransactionNeeded);
4852 }
4853}
4854
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004855status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856#pragma clang diagnostic push
4857#pragma clang diagnostic error "-Wswitch-enum"
4858 switch (static_cast<ISurfaceComposerTag>(code)) {
4859 // These methods should at minimum make sure that the client requested
4860 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004861 case BOOT_FINISHED:
4862 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 case CREATE_DISPLAY:
4864 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004865 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004866 case GET_ACTIVE_COLOR_MODE:
4867 case GET_ANIMATION_FRAME_STATS:
4868 case GET_HDR_CAPABILITIES:
4869 case SET_ACTIVE_CONFIG:
4870 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004871 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004872 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004873 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004874 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4875 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004876 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4877 IPCThreadState* ipc = IPCThreadState::self();
4878 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4879 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004880 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 }
Robert Carr1db73f62016-12-21 12:58:51 -08004882 return OK;
4883 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004885 IPCThreadState* ipc = IPCThreadState::self();
4886 const int pid = ipc->getCallingPid();
4887 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4889 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004890 return PERMISSION_DENIED;
4891 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004892 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 // Used by apps to hook Choreographer to SurfaceFlinger.
4895 case CREATE_DISPLAY_EVENT_CONNECTION:
4896 // The following calls are currently used by clients that do not
4897 // request necessary permissions. However, they do not expose any secret
4898 // information, so it is OK to pass them.
4899 case AUTHENTICATE_SURFACE:
4900 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004901 case GET_PHYSICAL_DISPLAY_IDS:
4902 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004904 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905 case GET_DISPLAY_CONFIGS:
4906 case GET_DISPLAY_STATS:
4907 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4908 // Calling setTransactionState is safe, because you need to have been
4909 // granted a reference to Client* and Handle* to do anything with it.
4910 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004911 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004912 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004913 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004914 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004915 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 return OK;
4917 }
4918 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004919 case CAPTURE_SCREEN:
4920 case ADD_REGION_SAMPLING_LISTENER:
4921 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004923 IPCThreadState* ipc = IPCThreadState::self();
4924 const int pid = ipc->getCallingPid();
4925 const int uid = ipc->getCallingUid();
4926 if ((uid != AID_GRAPHICS) &&
4927 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4928 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4929 return PERMISSION_DENIED;
4930 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 return OK;
4932 }
4933 // The following codes are deprecated and should never be allowed to access SF.
4934 case CONNECT_DISPLAY_UNUSED:
4935 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4936 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4937 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004938 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940
4941 // These codes are used for the IBinder protocol to either interrogate the recipient
4942 // side of the transaction for its canonical interface descriptor or to dump its state.
4943 // We let them pass by default.
4944 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4945 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4946 code == IBinder::SYSPROPS_TRANSACTION) {
4947 return OK;
4948 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004949 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004950 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004951 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4953 return OK;
4954 }
4955 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4956 return PERMISSION_DENIED;
4957#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004958}
4959
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4961 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004962 status_t credentialCheck = CheckTransactCodeCredentials(code);
4963 if (credentialCheck != OK) {
4964 return credentialCheck;
4965 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4968 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004969 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004970 IPCThreadState* ipc = IPCThreadState::self();
4971 const int uid = ipc->getCallingUid();
4972 if (CC_UNLIKELY(uid != AID_SYSTEM
4973 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004974 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004975 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004976 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 return PERMISSION_DENIED;
4978 }
4979 int n;
4980 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004981 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004982 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 return NO_ERROR;
4984 case 1002: // SHOW_UPDATES
4985 n = data.readInt32();
4986 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004987 invalidateHwcGeometry();
4988 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004990 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004991 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004992 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004994 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004995 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004996 setTransactionFlags(
4997 eTransactionNeeded|
4998 eDisplayTransactionNeeded|
4999 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005000 return NO_ERROR;
5001 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005002 case 1006:{ // send empty update
5003 signalRefresh();
5004 return NO_ERROR;
5005 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005006 case 1008: // toggle use of hw composer
5007 n = data.readInt32();
5008 mDebugDisableHWC = n ? 1 : 0;
5009 invalidateHwcGeometry();
5010 repaintEverything();
5011 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005012 case 1009: // toggle use of transform hint
5013 n = data.readInt32();
5014 mDebugDisableTransformHint = n ? 1 : 0;
5015 invalidateHwcGeometry();
5016 repaintEverything();
5017 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005019 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 reply->writeInt32(0);
5021 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005022 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005023 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 return NO_ERROR;
5025 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005026 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005027 if (!display) {
5028 return NAME_NOT_FOUND;
5029 }
5030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005031 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005032 return NO_ERROR;
5033 }
5034 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005035 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005036 // daltonize
5037 n = data.readInt32();
5038 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005039 case 1:
5040 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5041 break;
5042 case 2:
5043 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5044 break;
5045 case 3:
5046 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5047 break;
5048 default:
5049 mDaltonizer.setType(ColorBlindnessType::None);
5050 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005051 }
5052 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005053 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005054 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005055 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005056 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057
5058 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005060 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005063 // apply a color matrix
5064 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005065 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005066 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005067 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005068 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005069 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005070 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005072 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005073 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005074 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005075
5076 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5077 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005078 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005079 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5080 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5081 }
5082
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005084 return NO_ERROR;
5085 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005086 // This is an experimental interface
5087 // Needs to be shifted to proper binder interface when we productize
5088 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005089 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005090 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005091 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005092 return NO_ERROR;
5093 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005094 case 1017: {
5095 n = data.readInt32();
5096 mForceFullDamage = static_cast<bool>(n);
5097 return NO_ERROR;
5098 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005099 case 1018: { // Modify Choreographer's phase offset
5100 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005101 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005102 return NO_ERROR;
5103 }
5104 case 1019: { // Modify SurfaceFlinger's phase offset
5105 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005106 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005107 return NO_ERROR;
5108 }
Irvel468051e2016-06-13 16:44:44 -07005109 case 1020: { // Layer updates interceptor
5110 n = data.readInt32();
5111 if (n) {
5112 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005113 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005114 }
5115 else{
5116 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005117 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005118 }
5119 return NO_ERROR;
5120 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005121 case 1021: { // Disable HWC virtual displays
5122 n = data.readInt32();
5123 mUseHwcVirtualDisplays = !n;
5124 return NO_ERROR;
5125 }
Romain Guy0147a172017-06-01 13:53:56 -07005126 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005128 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005129
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005131 return NO_ERROR;
5132 }
Romain Guy54f154a2017-10-24 21:40:32 +01005133 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005134 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005135 invalidateHwcGeometry();
5136 repaintEverything();
5137 return NO_ERROR;
5138 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005139 // Deprecate, use 1030 to check whether the device is color managed.
5140 case 1024: {
5141 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005142 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005143 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005144 n = data.readInt32();
5145 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005146 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005147 mTracing.enable();
5148 doTracing("tracing.enable");
5149 reply->writeInt32(NO_ERROR);
5150 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005151 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005152 status_t err = mTracing.disable();
5153 reply->writeInt32(err);
5154 }
5155 return NO_ERROR;
5156 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005157 case 1026: { // Get layer tracing status
5158 reply->writeBool(mTracing.isEnabled());
5159 return NO_ERROR;
5160 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 // Is a DisplayColorSetting supported?
5162 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163 const auto display = getDefaultDisplayDevice();
5164 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005165 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005166 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005167
5168 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5169 switch (setting) {
5170 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005171 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 break;
5173 case DisplayColorSetting::UNMANAGED:
5174 reply->writeBool(true);
5175 break;
5176 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005177 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005178 break;
5179 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005180 reply->writeBool(
5181 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005182 break;
5183 }
5184 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005185 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005186 // Is VrFlinger active?
5187 case 1028: {
5188 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005189 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005190 return NO_ERROR;
5191 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005192 // Is device color managed?
5193 case 1030: {
5194 reply->writeBool(useColorManagement);
5195 return NO_ERROR;
5196 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005197 // Override default composition data space
5198 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5199 // && adb shell stop zygote && adb shell start zygote
5200 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5201 // adb shell stop zygote && adb shell start zygote
5202 case 1031: {
5203 Mutex::Autolock _l(mStateLock);
5204 n = data.readInt32();
5205 if (n) {
5206 n = data.readInt32();
5207 if (n) {
5208 Dataspace dataspace = static_cast<Dataspace>(n);
5209 if (!validateCompositionDataspace(dataspace)) {
5210 return BAD_VALUE;
5211 }
5212 mDefaultCompositionDataspace = dataspace;
5213 }
5214 n = data.readInt32();
5215 if (n) {
5216 Dataspace dataspace = static_cast<Dataspace>(n);
5217 if (!validateCompositionDataspace(dataspace)) {
5218 return BAD_VALUE;
5219 }
5220 mWideColorGamutCompositionDataspace = dataspace;
5221 }
5222 } else {
5223 // restore composition data space.
5224 mDefaultCompositionDataspace = defaultCompositionDataspace;
5225 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5226 }
5227 return NO_ERROR;
5228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005229 }
5230 }
5231 return err;
5232}
5233
Steven Thomas6d8110b2017-08-31 18:24:21 -07005234void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005235 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005236 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005237}
5238
Ana Krulec7d1d6832018-12-27 11:10:09 -08005239void SurfaceFlinger::repaintEverythingForHWC() {
5240 mRepaintEverything = true;
5241 mEventQueue->invalidateForHWC();
5242}
5243
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5245class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005246public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005247 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5248 ~WindowDisconnector() {
5249 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005250 }
5251
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005252private:
5253 ANativeWindow* mWindow;
5254 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005255};
5256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005257status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005258 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5259 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005260 uint32_t reqWidth, uint32_t reqHeight,
5261 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005262 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005263 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005265 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005266
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005267 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5268
Chia-I Wu20261cb2018-08-23 12:55:44 -07005269 sp<DisplayDevice> display;
5270 {
5271 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005272
Chia-I Wu20261cb2018-08-23 12:55:44 -07005273 display = getDisplayDeviceLocked(displayToken);
5274 if (!display) return BAD_VALUE;
5275
Chia-I Wucb023152018-08-28 12:57:23 -07005276 // set the requested width/height to the logical display viewport size
5277 // by default
5278 if (reqWidth == 0 || reqHeight == 0) {
5279 reqWidth = uint32_t(display->getViewport().width());
5280 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005281 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005282 }
5283
Peiyong Lin0e003c92018-09-17 11:09:51 -07005284 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5285 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005286
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005287 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5288 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005289 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5290 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005291}
5292
5293status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005294 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5295 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005296 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005297 ATRACE_CALL();
5298
5299 class LayerRenderArea : public RenderArea {
5300 public:
Robert Carr578038f2018-03-09 12:25:24 -08005301 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005302 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5303 bool childrenOnly)
5304 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005305 mLayer(layer),
5306 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005307 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005308 mFlinger(flinger),
5309 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005310 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005311 Rect getBounds() const override {
5312 const Layer::State& layerState(mLayer->getDrawingState());
5313 return mLayer->getBufferSize(layerState);
5314 }
Marissa Wall61c58622018-07-18 10:12:20 -07005315 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005316 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005317 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005318 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005319 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005320 }
chaviwa76b2712017-09-20 12:02:26 -07005321 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005322 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005323 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005324 Rect getSourceCrop() const override {
5325 if (mCrop.isEmpty()) {
5326 return getBounds();
5327 } else {
5328 return mCrop;
5329 }
5330 }
Robert Carr578038f2018-03-09 12:25:24 -08005331 class ReparentForDrawing {
5332 public:
5333 const sp<Layer>& oldParent;
5334 const sp<Layer>& newParent;
5335
Vishnu Nair4351ad52019-02-11 14:13:02 -08005336 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5337 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005338 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005339 // Compute and cache the bounds for the new parent layer.
5340 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005341 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005342 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005343 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005344 };
5345
5346 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005347 const Rect sourceCrop = getSourceCrop();
5348 // no need to check rotation because there is none
5349 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5350 sourceCrop.height() != getReqHeight();
5351
Robert Carr578038f2018-03-09 12:25:24 -08005352 if (!mChildrenOnly) {
5353 mTransform = mLayer->getTransform().inverse();
5354 drawLayers();
5355 } else {
5356 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005357 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005358 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5359 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005360
Vishnu Nair4351ad52019-02-11 14:13:02 -08005361 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005362 drawLayers();
5363 }
5364 }
chaviwa76b2712017-09-20 12:02:26 -07005365
chaviwa76b2712017-09-20 12:02:26 -07005366 private:
chaviw7206d492017-11-10 16:16:12 -08005367 const sp<Layer> mLayer;
5368 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005369
5370 // In the "childrenOnly" case we reparent the children to a screenshot
5371 // layer which has no properties set and which does not draw.
5372 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005373 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005374 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005375
5376 SurfaceFlinger* mFlinger;
5377 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005378 };
5379
5380 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5381 auto parent = layerHandle->owner.promote();
5382
Robert Carr2e102c92018-10-23 12:11:15 -07005383 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005384 ALOGE("captureLayers called with a removed parent");
5385 return NAME_NOT_FOUND;
5386 }
5387
Robert Carr578038f2018-03-09 12:25:24 -08005388 const int uid = IPCThreadState::self()->getCallingUid();
5389 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005390 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005391 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5392 return PERMISSION_DENIED;
5393 }
5394
chaviw7206d492017-11-10 16:16:12 -08005395 Rect crop(sourceCrop);
5396 if (sourceCrop.width() <= 0) {
5397 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005398 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005399 }
5400
5401 if (sourceCrop.height() <= 0) {
5402 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005403 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005404 }
5405
5406 int32_t reqWidth = crop.width() * frameScale;
5407 int32_t reqHeight = crop.height() * frameScale;
5408
Chia-I Wu20261cb2018-08-23 12:55:44 -07005409 // really small crop or frameScale
5410 if (reqWidth <= 0) {
5411 reqWidth = 1;
5412 }
5413 if (reqHeight <= 0) {
5414 reqHeight = 1;
5415 }
5416
Peiyong Lin0e003c92018-09-17 11:09:51 -07005417 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005418
Robert Carr578038f2018-03-09 12:25:24 -08005419 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005420 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5421 if (!layer->isVisible()) {
5422 return;
Robert Carr578038f2018-03-09 12:25:24 -08005423 } else if (childrenOnly && layer == parent.get()) {
5424 return;
chaviwa76b2712017-09-20 12:02:26 -07005425 }
5426 visitor(layer);
5427 });
5428 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005429 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005430}
5431
5432status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5433 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005434 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005436 bool useIdentityTransform) {
5437 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005438
Peiyong Lin0e003c92018-09-17 11:09:51 -07005439 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005440 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5441 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005442 *outBuffer =
5443 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5444 static_cast<android_pixel_format>(reqPixelFormat), 1,
5445 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005446
5447 // This mutex protects syncFd and captureResult for communication of the return values from the
5448 // main thread back to this Binder thread
5449 std::mutex captureMutex;
5450 std::condition_variable captureCondition;
5451 std::unique_lock<std::mutex> captureLock(captureMutex);
5452 int syncFd = -1;
5453 std::optional<status_t> captureResult;
5454
Robert Carr03480e22018-01-04 16:02:06 -08005455 const int uid = IPCThreadState::self()->getCallingUid();
5456 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5457
Dominik Laskowski8c001672018-05-30 16:52:06 -07005458 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005459 // If there is a refresh pending, bug out early and tell the binder thread to try again
5460 // after the refresh.
5461 if (mRefreshPending) {
5462 ATRACE_NAME("Skipping screenshot for now");
5463 std::unique_lock<std::mutex> captureLock(captureMutex);
5464 captureResult = std::make_optional<status_t>(EAGAIN);
5465 captureCondition.notify_one();
5466 return;
5467 }
5468
5469 status_t result = NO_ERROR;
5470 int fd = -1;
5471 {
5472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005473 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005474 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5475 useIdentityTransform, forSystem, &fd);
5476 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005477 }
5478
5479 {
5480 std::unique_lock<std::mutex> captureLock(captureMutex);
5481 syncFd = fd;
5482 captureResult = std::make_optional<status_t>(result);
5483 captureCondition.notify_one();
5484 }
5485 });
5486
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005487 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005488 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005489 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005490 while (*captureResult == EAGAIN) {
5491 captureResult.reset();
5492 result = postMessageAsync(message);
5493 if (result != NO_ERROR) {
5494 return result;
5495 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005496 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005497 }
5498 result = *captureResult;
5499 }
5500
5501 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005502 sync_wait(syncFd, -1);
5503 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005505
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005506 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005507}
5508
chaviwa76b2712017-09-20 12:02:26 -07005509void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005510 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005511 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5512 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005513 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005514
chaviwa76b2712017-09-20 12:02:26 -07005515 const auto reqWidth = renderArea.getReqWidth();
5516 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005517 const auto sourceCrop = renderArea.getSourceCrop();
5518 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005519
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005520 renderengine::DisplaySettings clientCompositionDisplay;
5521 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005522
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005523 // assume that bounds are never offset, and that they are the same as the
5524 // buffer bounds.
5525 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5526 ui::Transform transform = renderArea.getTransform();
5527 mat4 m;
5528 m[0][0] = transform[0][0];
5529 m[0][1] = transform[0][1];
5530 m[0][3] = transform[0][2];
5531 m[1][0] = transform[1][0];
5532 m[1][1] = transform[1][1];
5533 m[1][3] = transform[1][2];
5534 m[3][0] = transform[2][0];
5535 m[3][1] = transform[2][1];
5536 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005537
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005538 clientCompositionDisplay.globalTransform = m;
5539 mat4 rotMatrix;
5540 // Displacement for repositioning the clipping rectangle after rotating it
5541 // with the rotation hint.
5542 int displacementX = 0;
5543 int displacementY = 0;
5544 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5545 switch (rotation) {
5546 case ui::Transform::ROT_90:
5547 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5548 displacementX = reqWidth;
5549 break;
5550 case ui::Transform::ROT_180:
5551 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5552 displacementX = reqWidth;
5553 displacementY = reqHeight;
5554 break;
5555 case ui::Transform::ROT_270:
5556 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5557 displacementY = reqHeight;
5558 break;
5559 default:
5560 break;
5561 }
5562 // We need to transform the clipping window into the right spot.
5563 // First, rotate the clipping rectangle by the rotation hint to get the
5564 // right orientation
5565 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5566 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5567 const vec4 rotClipTL = rotMatrix * clipTL;
5568 const vec4 rotClipBR = rotMatrix * clipBR;
5569 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5570 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5571 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5572 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5573
5574 // Now reposition the clipping rectangle with the displacement vector
5575 // computed above.
5576 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5577
5578 clientCompositionDisplay.clip =
5579 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5580 newClipRight + displacementX, newClipBottom + displacementY);
5581
5582 // We need to perform the same transformation in layer space, so propagate
5583 // it to the global transform.
5584 mat4 clipTransform = displacementMat * rotMatrix;
5585 clientCompositionDisplay.globalTransform *= clipTransform;
5586 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5587 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005588
chaviw50da5042018-04-09 13:49:37 -07005589 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005590
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005591 renderengine::LayerSettings fillLayer;
5592 fillLayer.source.buffer.buffer = nullptr;
5593 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5594 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5595 fillLayer.alpha = half(alpha);
5596 clientCompositionLayers.push_back(fillLayer);
5597
5598 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005599 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005600 renderengine::LayerSettings layerSettings;
5601 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5602 layerSettings);
5603 if (prepared) {
5604 clientCompositionLayers.push_back(layerSettings);
5605 }
chaviwa76b2712017-09-20 12:02:26 -07005606 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005607
5608 clientCompositionDisplay.clearRegion = clearRegion;
5609 base::unique_fd drawFence;
5610 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5611 &drawFence);
5612
5613 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005614}
5615
chaviwa76b2712017-09-20 12:02:26 -07005616status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5617 TraverseLayersFunction traverseLayers,
5618 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005620 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005621 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005622 ATRACE_CALL();
5623
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005624 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005625
5626 traverseLayers([&](Layer* layer) {
5627 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5628 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005629
Robert Carr03480e22018-01-04 16:02:06 -08005630 // We allow the system server to take screenshots of secure layers for
5631 // use in situations like the Screen-rotation animation and place
5632 // the impetus on WindowManager to not persist them.
5633 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005634 ALOGW("FB is protected: PERMISSION_DENIED");
5635 return PERMISSION_DENIED;
5636 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005639}
5640
chaviw5f21a5e2019-02-14 10:00:34 -08005641void SurfaceFlinger::setInputWindowsFinished() {}
5642
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005643// ---------------------------------------------------------------------------
5644
Dan Stoza412903f2017-04-27 13:42:17 -07005645void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5646 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005647}
5648
Dan Stoza412903f2017-04-27 13:42:17 -07005649void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5650 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005651}
5652
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005653void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005654 const LayerVector::Visitor& visitor) {
5655 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005656 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005657 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005658 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005659 continue;
5660 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005661 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005662 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005663 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005664 return;
5665 }
chaviwa76b2712017-09-20 12:02:26 -07005666 if (!layer->isVisible()) {
5667 return;
5668 }
5669 visitor(layer);
5670 });
5671 }
5672}
5673
chaviw291d88a2019-02-14 10:33:58 -08005674// ----------------------------------------------------------------------------
5675
5676void SetInputWindowsListener::onSetInputWindowsFinished() {
5677 mFlinger->setInputWindowsFinished();
5678}
5679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005680}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005681
Lloyd Pique074e8122018-07-26 12:57:23 -07005682
Mathias Agopian3f844832013-08-07 21:24:32 -07005683#if defined(__gl_h_)
5684#error "don't include gl/gl.h in this file"
5685#endif
5686
5687#if defined(__gl2_h_)
5688#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005689#endif