blob: f0f57d38af82ec3b3506028afd01dfed02f2dcf0 [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()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulecc2870422019-01-29 19:00:58 -0800396 property_get("debug.sf.use_90Hz", value, "0");
397 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800398
Ana Krulecba13ab32019-02-20 14:14:12 -0800399 property_get("debug.sf.use_smart_90_for_video", value, "0");
400 mUseSmart90ForVideo = atoi(value);
401
Ana Krulec757f63a2019-01-25 10:46:18 -0800402 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
403 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700404
Romain Guy11d63f42017-07-20 12:47:14 -0700405 // We should be reading 'persist.sys.sf.color_saturation' here
406 // but since /data may be encrypted, we need to wait until after vold
407 // comes online to attempt to read the property. The property is
408 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800409
410 if (useTrebleTestingOverride()) {
411 // Without the override SurfaceFlinger cannot connect to HIDL
412 // services that are not listed in the manifests. Considered
413 // deriving the setting from the set service name, but it
414 // would be brittle if the name that's not 'default' is used
415 // for production purposes later on.
416 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420void SurfaceFlinger::onFirstRef()
421{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800422 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423}
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425SurfaceFlinger::~SurfaceFlinger()
426{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Dan Stozac7014012014-02-14 15:03:43 -0800429void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430{
431 // the window manager died on us. prepare its eulogy.
432
Andy McFadden13a082e2012-08-24 10:16:42 -0700433 // restore initial conditions (default device unblank, etc)
434 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435
436 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700437 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438}
439
Robert Carr1db73f62016-12-21 12:58:51 -0800440static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700441 status_t err = client->initCheck();
442 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800443 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return nullptr;
446}
447
448sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
449 return initClient(new Client(this));
450}
451
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700452sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
453 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454{
455 class DisplayToken : public BBinder {
456 sp<SurfaceFlinger> flinger;
457 virtual ~DisplayToken() {
458 // no more references, this display must be terminated
459 Mutex::Autolock _l(flinger->mStateLock);
460 flinger->mCurrentState.displays.removeItem(this);
461 flinger->setTransactionFlags(eDisplayTransactionNeeded);
462 }
463 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700464 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 : flinger(flinger) {
466 }
467 };
468
469 sp<BBinder> token = new DisplayToken(this);
470
471 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 // Display ID is assigned when virtual display is allocated by HWC.
473 DisplayDeviceState state;
474 state.isSecure = secure;
475 state.displayName = displayName;
476 mCurrentState.displays.add(token, state);
477 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 return token;
479}
480
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 Mutex::Autolock _l(mStateLock);
483
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
485 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
489
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
491 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 ALOGE("destroyDisplay called for non-virtual display");
493 return;
494 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 mInterceptor->saveDisplayDeletion(state.sequenceId);
496 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 setTransactionFlags(eDisplayTransactionNeeded);
498}
499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
501 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503 const auto internalDisplayId = getInternalDisplayIdLocked();
504 if (!internalDisplayId) {
505 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 }
507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 std::vector<PhysicalDisplayId> displayIds;
509 displayIds.reserve(mPhysicalDisplayTokens.size());
510 displayIds.push_back(internalDisplayId->value);
511
512 for (const auto& [id, token] : mPhysicalDisplayTokens) {
513 if (id != *internalDisplayId) {
514 displayIds.push_back(id.value);
515 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800518 return displayIds;
519}
520
521sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
522 Mutex::Autolock lock(mStateLock);
523 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700524}
525
Ady Abraham37965d42018-11-01 13:43:32 -0700526status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
527 if (!outGetColorManagement) {
528 return BAD_VALUE;
529 }
530 *outGetColorManagement = useColorManagement;
531 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700532}
533
Lloyd Pique441d5042018-10-18 16:49:51 -0700534HWComposer& SurfaceFlinger::getHwComposer() const {
535 return mCompositionEngine->getHwComposer();
536}
537
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700538renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
539 return mCompositionEngine->getRenderEngine();
540}
541
Lloyd Pique70d91362018-10-18 16:02:55 -0700542compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
543 return *mCompositionEngine.get();
544}
545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546void SurfaceFlinger::bootFinished()
547{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700548 if (mStartPropertySetThread->join() != NO_ERROR) {
549 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551 const nsecs_t now = systemTime();
552 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000553 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
555 // wait patiently for the window manager death
556 const String16 name("window");
557 sp<IBinder> window(defaultServiceManager()->getService(name));
558 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700559 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 }
Robert Carr720e5062018-07-30 17:45:14 -0700561 sp<IBinder> input(defaultServiceManager()->getService(
562 String16("inputflinger")));
563 if (input == nullptr) {
564 ALOGE("Failed to link to input service");
565 } else {
566 mInputFlinger = interface_cast<IInputFlinger>(input);
567 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 if (mVrFlinger) {
570 mVrFlinger->OnBootFinished();
571 }
572
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700574 // formerly we would just kill the process, but we now ask it to exit so it
575 // can choose where to stop the animation.
576 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700577
578 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
579 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
580 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700581
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 readPersistentProperties();
584 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800585
586 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
587 // away and it should be controlled by flipping the switch in setting. The switch in
588 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
589 // The boot must be complete before we can set the active config.
590
591 if (mUse90Hz) {
592 mPhaseOffsets->setRefreshRateType(
593 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
594 setRefreshRateTo(RefreshRateType::PERFORMANCE);
595 } else {
596 mPhaseOffsets->setRefreshRateType(
597 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
598 setRefreshRateTo(RefreshRateType::DEFAULT);
599 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800600 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800601}
602
Dan Stoza436ccf32018-06-21 12:10:12 -0700603uint32_t SurfaceFlinger::getNewTexture() {
604 {
605 std::lock_guard lock(mTexturePoolMutex);
606 if (!mTexturePool.empty()) {
607 uint32_t name = mTexturePool.back();
608 mTexturePool.pop_back();
609 ATRACE_INT("TexturePoolSize", mTexturePool.size());
610 return name;
611 }
612
613 // The pool was too small, so increase it for the future
614 ++mTexturePoolSize;
615 }
616
617 // The pool was empty, so we need to get a new texture name directly using a
618 // blocking call to the main thread
619 uint32_t name = 0;
620 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
621 return name;
622}
623
Mathias Agopian3f844832013-08-07 21:24:32 -0700624void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700625 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700626}
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
633
Ana Krulec757f63a2019-01-25 10:46:18 -0800634 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700637 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800638 mScheduler =
639 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
640 auto resyncCallback =
641 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800642
Ana Krulecc2870422019-01-29 19:00:58 -0800643 mAppConnectionHandle =
644 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
645 resyncCallback,
646 impl::EventThread::InterceptVSyncsCallback());
647 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
648 resyncCallback, [this](nsecs_t timestamp) {
649 mInterceptor->saveVSyncEvent(timestamp);
650 });
651
652 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
653 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
654 mSfConnectionHandle.get());
655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700657 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700658 renderEngineFeature |= (useColorManagement ?
659 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700660 renderEngineFeature |= (useContextPriority ?
661 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700662
663 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700664 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700665 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700666 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700670 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
671 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700681 // This callback is called from the vr flinger dispatch thread. We
682 // need to call signalTransaction(), which requires holding
683 // mStateLock when we're not on the main thread. Acquiring
684 // mStateLock from the vr flinger dispatch thread might trigger a
685 // deadlock in surface flinger (see b/66916578), so post a message
686 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700688 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
689 mVrFlingerRequestsDisplay = requestDisplay;
690 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
694 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 .value_or(0),
697 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (!mVrFlinger) {
699 ALOGE("Failed to start vrflinger");
700 }
701 }
702
Mathias Agopian92a979a2012-08-02 18:32:23 -0700703 // initialize our drawing state
704 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700705
Andy McFadden13a082e2012-08-24 10:16:42 -0700706 // set initial conditions (e.g. unblank default device)
707 initializeDisplays();
708
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700709 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700710
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700712
713 const bool presentFenceReliable =
714 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
715 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Ana Krulecc2870422019-01-29 19:00:58 -0800721 mScheduler->setExpiredIdleTimerCallback([this] {
722 Mutex::Autolock lock(mStateLock);
723 setRefreshRateTo(RefreshRateType::DEFAULT);
724 });
725 mScheduler->setResetIdleTimerCallback([this] {
726 Mutex::Autolock lock(mStateLock);
727 setRefreshRateTo(RefreshRateType::PERFORMANCE);
728 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800729
Ana Krulecc2870422019-01-29 19:00:58 -0800730 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
731 *display->getId()),
732 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800733
Dan Stoza9e56aa02015-11-02 13:00:03 -0800734 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700735}
736
Romain Guy11d63f42017-07-20 12:47:14 -0700737void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700738 Mutex::Autolock _l(mStateLock);
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740 char value[PROPERTY_VALUE_MAX];
741
742 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800743 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700744 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800745 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100746
747 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700748 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800749
750 property_get("persist.sys.sf.color_mode", value, "0");
751 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700752}
753
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Start boot animation service by setting a property mailbox
756 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700757 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 if (mStartPropertySetThread->join() != NO_ERROR) {
760 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700765 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800773
Jamie Gennis582270d2011-08-17 18:19:00 -0700774bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800775 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800776 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800777 return authenticateSurfaceTextureLocked(bufferProducer);
778}
779
780bool SurfaceFlinger::authenticateSurfaceTextureLocked(
781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800782 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800783 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800784}
785
Brian Anderson6b376712017-04-04 10:51:39 -0700786status_t SurfaceFlinger::getSupportedFrameTimestamps(
787 std::vector<FrameEvent>* outSupported) const {
788 *outSupported = {
789 FrameEvent::REQUESTED_PRESENT,
790 FrameEvent::ACQUIRE,
791 FrameEvent::LATCH,
792 FrameEvent::FIRST_REFRESH_START,
793 FrameEvent::LAST_REFRESH_START,
794 FrameEvent::GPU_COMPOSITION_DONE,
795 FrameEvent::DEQUEUE_READY,
796 FrameEvent::RELEASE,
797 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700800 if (!getHwComposer().hasCapability(
801 HWC2::Capability::PresentFenceIsNotReliable)) {
802 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
803 }
804 return NO_ERROR;
805}
806
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800807status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
808 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800813 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700822 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826 return density;
827 }
828 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dominik Laskowski075d3172018-05-24 15:50:06 -0700837 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 DisplayInfo info = DisplayInfo();
839
Dan Stoza9e56aa02015-11-02 13:00:03 -0800840 float xdpi = hwConfig->getDpiX();
841 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700842
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700843 info.w = hwConfig->getWidth();
844 info.h = hwConfig->getHeight();
845 // Default display viewport to display width and height
846 info.viewportW = info.w;
847 info.viewportH = info.h;
848
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800849 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 // The density of the device is provided by a build property
851 float density = Density::getBuildDensity() / 160.0f;
852 if (density == 0) {
853 // the build doesn't provide a density -- this is wrong!
854 // use xdpi instead
855 ALOGE("ro.sf.lcd_density must be defined as a build property");
856 density = xdpi / 160.0f;
857 }
858 if (Density::getEmuDensity()) {
859 // if "qemu.sf.lcd_density" is specified, it overrides everything
860 xdpi = ydpi = density = Density::getEmuDensity();
861 density /= 160.0f;
862 }
863 info.density = density;
864
865 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700866 const auto display = getDefaultDisplayDeviceLocked();
867 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700868
869 // This is for screenrecord
870 const Rect viewport = display->getViewport();
871 if (viewport.isValid()) {
872 info.viewportW = uint32_t(viewport.getWidth());
873 info.viewportH = uint32_t(viewport.getHeight());
874 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 } else {
876 // TODO: where should this value come from?
877 static const int TV_DENSITY = 213;
878 info.density = TV_DENSITY / 160.0f;
879 info.orientation = 0;
880 }
881
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 info.xdpi = xdpi;
883 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800885 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886
Andy McFadden91b2ca82014-06-13 14:04:23 -0700887 // This is how far in advance a buffer must be queued for
888 // presentation at a given time. If you want a buffer to appear
889 // on the screen at time N, you must submit the buffer before
890 // (N - presentationDeadline).
891 //
892 // Normally it's one full refresh period (to give SF a chance to
893 // latch the buffer), but this can be reduced by configuring a
894 // DispSync offset. Any additional delays introduced by the hardware
895 // composer or panel must be accounted for here.
896 //
897 // We add an additional 1ms to allow for processing time and
898 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800899 info.presentationDeadline =
900 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700901
902 // All non-virtual displays are currently considered secure.
903 info.secure = true;
904
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800905 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700906 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800907 std::swap(info.w, info.h);
908 }
909
Michael Wright28f24d02016-07-12 13:30:53 -0700910 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700911 }
912
Dan Stoza7f7da322014-05-02 15:26:25 -0700913 return NO_ERROR;
914}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
917 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700918 return BAD_VALUE;
919 }
920
Ana Krulecc2870422019-01-29 19:00:58 -0800921 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
926 const auto display = getDisplayDevice(displayToken);
927 if (!display) {
928 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800929 return BAD_VALUE;
930 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800935void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
936 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800937
Ana Krulec7d1d6832018-12-27 11:10:09 -0800938 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800939 // Lock is acquired by setRefreshRateTo.
940 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800941 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
942 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
943 return;
944 }
945
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 // Lock is acquired by setRefreshRateTo.
947 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948 if (!display) {
949 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
950 displayToken.get());
951 return;
952 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700953 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800954 ALOGW("Attempt to set active config %d for virtual display", mode);
955 return;
956 }
957 int currentDisplayPowerMode = display->getPowerMode();
958 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
959 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700960 return;
961 }
962
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963 // Don't check against the current mode yet. Worst case we set the desired
964 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800965 std::lock_guard<std::mutex> lock(mActiveConfigLock);
966 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
967
968 if (!mDesiredActiveConfigChanged) {
969 // This is the first time we set the desired
970 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
971
972 // This will trigger HWC refresh without resetting the idle timer.
973 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800975 mDesiredActiveConfigChanged = true;
976 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977}
978
979status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
980 ATRACE_CALL();
981 postMessageSync(new LambdaMessage(
982 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
983 return NO_ERROR;
984}
985
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986void SurfaceFlinger::setActiveConfigInternal() {
987 ATRACE_CALL();
988
989 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800990 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991
992 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
993 display->setActiveConfig(mUpcomingActiveConfig.configId);
994
Ana Krulecc2870422019-01-29 19:00:58 -0800995 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
997}
998
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
1000 // we may be in the process of changing the active state
1001 if (mWaitForNextInvalidate) {
1002 mWaitForNextInvalidate = false;
1003
1004 repaintEverythingForHWC();
1005 // We do not want to give another frame to HWC while we are transitioning.
1006 return true;
1007 }
1008
1009 if (mCheckPendingFence) {
1010 if (mPreviousPresentFence != Fence::NO_FENCE &&
1011 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1012 // fence has not signaled yet. wait for the next invalidate
1013 repaintEverythingForHWC();
1014 return true;
1015 }
1016
1017 // We received the present fence from the HWC, so we assume it successfully updated
1018 // the config, hence we update SF.
1019 mCheckPendingFence = false;
1020 setActiveConfigInternal();
1021 }
1022
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023 // Store the local variable to release the lock.
1024 ActiveConfigInfo desiredActiveConfig;
1025 {
1026 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001027 if (!mDesiredActiveConfigChanged) {
1028 return false;
1029 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001030 desiredActiveConfig = mDesiredActiveConfig;
1031 }
1032
1033 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1035 // display is not valid or we are already in the requested mode
1036 // on both cases there is nothing left to do
1037 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1038 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1039 mDesiredActiveConfigChanged = false;
1040 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1041 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001042 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043
1044 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1045 mUpcomingActiveConfig = desiredActiveConfig;
1046 const auto displayId = display->getId();
1047 LOG_ALWAYS_FATAL_IF(!displayId);
1048
1049 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1050 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1051
1052 // we need to submit an empty frame to HWC to start the process
1053 mWaitForNextInvalidate = true;
1054 mCheckPendingFence = true;
1055
1056 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1060 Vector<ColorMode>* outColorModes) {
1061 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001062 return BAD_VALUE;
1063 }
1064
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001066 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001067 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1068
1069 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1070 if (!displayId) {
1071 return NAME_NOT_FOUND;
1072 }
1073
Dominik Laskowski075d3172018-05-24 15:50:06 -07001074 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001075 }
Michael Wright28f24d02016-07-12 13:30:53 -07001076 outColorModes->clear();
1077 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1078
1079 return NO_ERROR;
1080}
1081
Daniel Solomon42d04562019-01-20 21:03:19 -08001082status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1083 ui::DisplayPrimaries &primaries) {
1084 if (!displayToken) {
1085 return BAD_VALUE;
1086 }
1087
1088 // Currently we only support this API for a single internal display.
1089 if (getInternalDisplayToken() != displayToken) {
1090 return BAD_VALUE;
1091 }
1092
1093 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1094 return NO_ERROR;
1095}
1096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1098 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001099 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001100 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001101 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001102}
1103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001105 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106 Vector<ColorMode> modes;
1107 getDisplayColorModes(displayToken, &modes);
1108 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1109 if (mode < ColorMode::NATIVE || !exists) {
1110 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1111 decodeColorMode(mode).c_str(), mode, displayToken.get());
1112 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001113 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 const auto display = getDisplayDevice(displayToken);
1115 if (!display) {
1116 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1117 decodeColorMode(mode).c_str(), mode, displayToken.get());
1118 } else if (display->isVirtual()) {
1119 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1120 decodeColorMode(mode).c_str(), mode);
1121 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001122 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1123 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124 }
1125 }));
1126
Michael Wright28f24d02016-07-12 13:30:53 -07001127 return NO_ERROR;
1128}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001129
Svetoslavd85084b2014-03-20 10:28:31 -07001130status_t SurfaceFlinger::clearAnimationFrameStats() {
1131 Mutex::Autolock _l(mStateLock);
1132 mAnimFrameTracker.clearStats();
1133 return NO_ERROR;
1134}
1135
1136status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1137 Mutex::Autolock _l(mStateLock);
1138 mAnimFrameTracker.getStats(outStats);
1139 return NO_ERROR;
1140}
1141
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001142status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1143 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001144 Mutex::Autolock _l(mStateLock);
1145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 const auto display = getDisplayDeviceLocked(displayToken);
1147 if (!display) {
1148 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001149 return BAD_VALUE;
1150 }
1151
Peiyong Linfb069302018-04-25 14:34:31 -07001152 // At this point the DisplayDeivce should already be set up,
1153 // meaning the luminance information is already queried from
1154 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001156 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1157 capabilities.getDesiredMaxLuminance(),
1158 capabilities.getDesiredMaxAverageLuminance(),
1159 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001160
1161 return NO_ERROR;
1162}
1163
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001164status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1165 ui::PixelFormat* outFormat,
1166 ui::Dataspace* outDataspace,
1167 uint8_t* outComponentMask) const {
1168 if (!outFormat || !outDataspace || !outComponentMask) {
1169 return BAD_VALUE;
1170 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001171 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001172 if (!display || !display->getId()) {
1173 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1174 return BAD_VALUE;
1175 }
1176 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1177 outDataspace, outComponentMask);
1178}
1179
Kevin DuBois74e53772018-11-19 10:52:38 -08001180status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1181 bool enable, uint8_t componentMask,
1182 uint64_t maxFrames) const {
1183 const auto display = getDisplayDevice(displayToken);
1184 if (!display || !display->getId()) {
1185 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1186 return BAD_VALUE;
1187 }
1188
1189 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1190 componentMask, maxFrames);
1191}
1192
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001193status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1194 uint64_t maxFrames, uint64_t timestamp,
1195 DisplayedFrameStats* outStats) const {
1196 const auto display = getDisplayDevice(displayToken);
1197 if (!display || !display->getId()) {
1198 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1199 return BAD_VALUE;
1200 }
1201
1202 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1203 outStats);
1204}
1205
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001206status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1207 if (!outSupported) {
1208 return BAD_VALUE;
1209 }
1210 *outSupported = getRenderEngine().supportsProtectedContent();
1211 return NO_ERROR;
1212}
1213
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001214status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1215 bool* outIsWideColorDisplay) const {
1216 if (!displayToken || !outIsWideColorDisplay) {
1217 return BAD_VALUE;
1218 }
1219 Mutex::Autolock _l(mStateLock);
1220 const auto display = getDisplayDeviceLocked(displayToken);
1221 if (!display) {
1222 return BAD_VALUE;
1223 }
1224 *outIsWideColorDisplay = display->hasWideColorGamut();
1225 return NO_ERROR;
1226}
1227
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001228status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001229 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001231
Chia-I Wu90f669f2017-10-05 14:24:41 -07001232 if (mInjectVSyncs == enable) {
1233 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001234 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001235
Ana Krulecc2870422019-01-29 19:00:58 -08001236 auto resyncCallback =
1237 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001238
Ana Krulec98b5b242018-08-10 15:03:23 -07001239 // TODO(akrulec): Part of the Injector should be refactored, so that it
1240 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001241 if (enable) {
1242 ALOGV("VSync Injections enabled");
1243 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001244 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001245 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001246 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001247 impl::EventThread::InterceptVSyncsCallback(),
1248 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001249 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001250 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001251 } else {
1252 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001253 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1254 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 }
1256
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001258 }));
1259
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001260 return NO_ERROR;
1261}
1262
1263status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001264 Mutex::Autolock _l(mStateLock);
1265
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001266 if (!mInjectVSyncs) {
1267 ALOGE("VSync Injections not enabled");
1268 return BAD_VALUE;
1269 }
1270 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1271 ALOGV("Injecting VSync inside SurfaceFlinger");
1272 mVSyncInjector->onInjectSyncEvent(when);
1273 }
1274 return NO_ERROR;
1275}
1276
Lloyd Pique755e3192018-01-31 16:46:15 -08001277status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1278 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001279 // Try to acquire a lock for 1s, fail gracefully
1280 const status_t err = mStateLock.timedLock(s2ns(1));
1281 const bool locked = (err == NO_ERROR);
1282 if (!locked) {
1283 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1284 return TIMED_OUT;
1285 }
1286
1287 outLayers->clear();
1288 mCurrentState.traverseInZOrder([&](Layer* layer) {
1289 outLayers->push_back(layer->getLayerDebugInfo());
1290 });
1291
1292 mStateLock.unlock();
1293 return NO_ERROR;
1294}
1295
Peiyong Linc6780972018-10-28 15:24:08 -07001296status_t SurfaceFlinger::getCompositionPreference(
1297 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1298 Dataspace* outWideColorGamutDataspace,
1299 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001300 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001301 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001302 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001303 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001304 return NO_ERROR;
1305}
1306
Dan Stoza84ab9372018-12-17 15:27:57 -08001307status_t SurfaceFlinger::addRegionSamplingListener(
1308 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1309 const sp<IRegionSamplingListener>& /*listener*/) {
1310 return NO_ERROR;
1311}
1312
1313status_t SurfaceFlinger::removeRegionSamplingListener(
1314 const sp<IRegionSamplingListener>& /*listener*/) {
1315 return NO_ERROR;
1316}
1317
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001318// ----------------------------------------------------------------------------
1319
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001320sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1321 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001322 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001323 Mutex::Autolock lock(mStateLock);
1324 return getVsyncPeriod();
1325 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001326
Ana Krulecc2870422019-01-29 19:00:58 -08001327 const auto& handle =
1328 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001329
Ana Krulecc2870422019-01-29 19:00:58 -08001330 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001331}
1332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001333// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334
1335void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001336 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001337}
1338
1339void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001340 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001341}
1342
1343void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001344 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345}
1346
1347void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001348 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001349 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001350}
1351
1352status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001353 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001354 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001355}
1356
1357status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001358 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001359 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001360 if (res == NO_ERROR) {
1361 msg->wait();
1362 }
1363 return res;
1364}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001365
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001366void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001367 do {
1368 waitForEvent();
1369 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001370}
1371
Dominik Laskowski83b88212018-12-11 13:34:06 -08001372nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001373 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001374 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1375 return 0;
1376 }
1377
1378 const auto config = getHwComposer().getActiveConfig(*displayId);
1379 return config ? config->getVsyncPeriod() : 0;
1380}
1381
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001382void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1383 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001384 ATRACE_NAME("SF onVsync");
1385
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001388 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 return;
1390 }
1391
Dominik Laskowski075d3172018-05-24 15:50:06 -07001392 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001393 return;
1394 }
1395
Dominik Laskowski075d3172018-05-24 15:50:06 -07001396 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001397 // For now, we don't do anything with external display vsyncs.
1398 return;
1399 }
1400
Ana Krulecc2870422019-01-29 19:00:58 -08001401 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001402}
1403
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001404void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001405 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1406 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407}
1408
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001409void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1410 mPhaseOffsets->setRefreshRateType(refreshRate);
1411
1412 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1413 mVsyncModulator.setPhaseOffsets(early, gl, late);
1414
1415 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001416 return;
1417 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001418
Ana Krulec7d1d6832018-12-27 11:10:09 -08001419 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1420 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1421 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1422 // refresh cycle.
1423
1424 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001425 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001426 if (currentVsyncPeriod == 0) {
1427 return;
1428 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001429
Ana Krulec7d1d6832018-12-27 11:10:09 -08001430 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1431 // floating numbers.
1432 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001433 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1434 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001435 if (std::abs(currentFps - newFps) <= 1) {
1436 return;
1437 }
1438
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001439 const auto displayId = getInternalDisplayIdLocked();
1440 LOG_ALWAYS_FATAL_IF(!displayId);
1441
1442 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001443 for (int i = 0; i < configs.size(); i++) {
1444 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1445 if (vsyncPeriod == 0) {
1446 continue;
1447 }
1448 const float fps = 1e9 / vsyncPeriod;
1449 // TODO(b/113612090): There should be a better way at determining which config
1450 // has the right refresh rate.
1451 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001452 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001453 }
1454 }
1455}
1456
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001457void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001458 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001459 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001460 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461
Lloyd Piqueba04e622017-12-14 17:11:26 -08001462 // Ignore events that do not have the right sequenceId.
1463 if (sequenceId != getBE().mComposerSequenceId) {
1464 return;
1465 }
1466
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 // Only lock if we're not on the main thread. This function is normally
1468 // called on a hwbinder thread, but for the primary display it's called on
1469 // the main thread with the state lock already held, so don't attempt to
1470 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001471 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001472
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001473 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001474
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001475 if (std::this_thread::get_id() == mMainThreadId) {
1476 // Process all pending hot plug events immediately if we are on the main thread.
1477 processDisplayHotplugEventsLocked();
1478 }
1479
Lloyd Piqueba04e622017-12-14 17:11:26 -08001480 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001481}
1482
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001485 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001487 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001488 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001489}
1490
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001491void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001492 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001494 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001495 getHwComposer().setVsyncEnabled(*displayId,
1496 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1497 }
Mathias Agopian86303202012-07-24 22:46:10 -07001498}
1499
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001500// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001501void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001502 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001503 // Clear the drawing state so that the logic inside of
1504 // handleTransactionLocked will fire. It will determine the delta between
1505 // mCurrentState and mDrawingState and re-apply all changes when we make the
1506 // transition.
1507 mDrawingState.displays.clear();
1508 mDisplays.clear();
1509}
1510
Steven Thomas050b2c82017-03-06 11:45:16 -08001511void SurfaceFlinger::updateVrFlinger() {
1512 if (!mVrFlinger)
1513 return;
1514 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001515 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001516 return;
1517 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518
Lloyd Pique441d5042018-10-18 16:49:51 -07001519 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 ALOGE("Vr flinger is only supported for remote hardware composer"
1521 " service connections. Ignoring request to transition to vr"
1522 " flinger.");
1523 mVrFlingerRequestsDisplay = false;
1524 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001525 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001527 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomas0123ac62018-07-12 11:32:34 -07001529 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001530 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001531
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001532 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001533
1534 // Clear out all the output layers from the composition engine for all
1535 // displays before destroying the hardware composer interface. This ensures
1536 // any HWC layers are destroyed through that interface before it becomes
1537 // invalid.
1538 for (const auto& [token, displayDevice] : mDisplays) {
1539 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1540 compositionengine::Output::OutputLayers());
1541 }
1542
Steven Thomas0123ac62018-07-12 11:32:34 -07001543 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1544 // called below. Clear the reference now so we don't accidentally use it
1545 // later.
1546 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001547
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001551
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001553 // Delete the current instance before creating the new one
1554 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1555 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1556 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1557 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001558
Lloyd Pique441d5042018-10-18 16:49:51 -07001559 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001560 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001561
1562 if (vrFlingerRequestsDisplay) {
1563 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001564 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565
1566 mVisibleRegionsDirty = true;
1567 invalidateHwcGeometry();
1568
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001569 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001570 display = getDefaultDisplayDeviceLocked();
1571 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001572 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001573
Steven Thomasb02664d2017-07-26 18:48:28 -07001574 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001575 const nsecs_t vsyncPeriod = getVsyncPeriod();
1576 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001577
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001578 // The present fences returned from vr_hwc are not an accurate
1579 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001580 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581
Steven Thomasb02664d2017-07-26 18:48:28 -07001582 // Use phase of 0 since phase is not known.
1583 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001584 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001585 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001586
Ana Krulecc2870422019-01-29 19:00:58 -08001587 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001588
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001589 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001591}
1592
Mathias Agopian4fec8732012-06-29 14:12:52 -07001593void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001594 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001595 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001596 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001597 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001598 break;
1599 }
1600
Ana Krulecba13ab32019-02-20 14:14:12 -08001601 if (mUse90Hz && mUseSmart90ForVideo) {
1602 // This call is made each time SF wakes up and creates a new frame. It is part
1603 // of video detection feature.
1604 mScheduler->incrementFrameCounter();
1605 }
Ana Krulecc2870422019-01-29 19:00:58 -08001606
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001607 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1608 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001609 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001610 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001612 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001613 if (mPropagateBackpressure) {
1614 signalLayerUpdate();
1615 break;
1616 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001617 }
Dan Stoza50182882016-07-08 12:02:20 -07001618
Steven Thomas050b2c82017-03-06 11:45:16 -08001619 // Now that we're going to make it to the handleMessageTransaction()
1620 // call below it's safe to call updateVrFlinger(), which will
1621 // potentially trigger a display handoff.
1622 updateVrFlinger();
1623
Dan Stoza6b9454d2014-11-07 16:00:59 -08001624 bool refreshNeeded = handleMessageTransaction();
1625 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001626
1627 updateCursorAsync();
1628 updateInputFlinger();
1629
Dan Stoza58784442014-12-02 16:58:17 -08001630 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001631 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001632 // Signal a refresh if a transaction modified the window state,
1633 // a new buffer was latched, or if HWC has requested a full
1634 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001635 signalRefresh();
1636 }
1637 break;
1638 }
1639 case MessageQueue::REFRESH: {
1640 handleMessageRefresh();
1641 break;
1642 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001643 }
1644}
1645
Dan Stoza6b9454d2014-11-07 16:00:59 -08001646bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001647 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001648
1649 // Apply any ready transactions in the queues if there are still transactions that have not been
1650 // applied, wake up during the next vsync period and check again
1651 bool transactionNeeded = false;
1652 if (!flushTransactionQueues()) {
1653 transactionNeeded = true;
1654 }
1655
Mathias Agopian4fec8732012-06-29 14:12:52 -07001656 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001657 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001658 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001659
1660 if (transactionNeeded) {
1661 setTransactionFlags(eTransactionNeeded);
1662 }
1663
1664 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001665}
1666
Mathias Agopian4fec8732012-06-29 14:12:52 -07001667void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001669
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001670 mRefreshPending = false;
1671
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001672 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001673 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001674 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001675 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676 for (const auto& [token, display] : mDisplays) {
1677 beginFrame(display);
1678 prepareFrame(display);
1679 doDebugFlashRegions(display, repaintEverything);
1680 doComposition(display, repaintEverything);
1681 }
1682
Adrian Roos1e1a1282017-11-01 19:05:31 +01001683 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001684 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685
1686 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001687 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001688
Dan Stozabfbffeb2016-07-21 14:49:33 -07001689 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001690 for (const auto& [token, displayDevice] : mDisplays) {
1691 auto display = displayDevice->getCompositionDisplay();
1692 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001693 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001694 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001695 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001696
Jorim Jaggi90535212018-05-23 23:44:06 +02001697 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001698
David Sodman7e4ae112018-02-09 15:02:28 -08001699 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001700
1701 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001702}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001703
David Sodmanfa9b2af2017-12-24 13:28:59 -08001704
1705bool SurfaceFlinger::handleMessageInvalidate() {
1706 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001707 bool refreshNeeded = handlePageFlip();
1708
Vishnu Nair4351ad52019-02-11 14:13:02 -08001709 if (mVisibleRegionsDirty) {
1710 computeLayerBounds();
1711 }
1712
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001713 for (auto& layer : mLayersPendingRefresh) {
1714 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001715 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001716 invalidateLayerStack(layer, visibleReg);
1717 }
1718 mLayersPendingRefresh.clear();
1719 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001720}
1721
David Sodman79bba0e2018-08-05 18:07:49 -07001722void SurfaceFlinger::calculateWorkingSet() {
1723 ATRACE_CALL();
1724 ALOGV(__FUNCTION__);
1725
David Sodman79bba0e2018-08-05 18:07:49 -07001726 // build the h/w work list
1727 if (CC_UNLIKELY(mGeometryInvalid)) {
1728 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001729 for (const auto& [token, displayDevice] : mDisplays) {
1730 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001731 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732 if (!displayId) {
1733 continue;
1734 }
David Sodman79bba0e2018-08-05 18:07:49 -07001735
Lloyd Pique32cbe282018-10-19 13:09:22 -07001736 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001737 for (size_t i = 0; i < currentLayers.size(); i++) {
1738 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001739
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001740 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001741 layer->forceClientComposition(displayDevice);
1742 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001743 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001744
Lloyd Pique32cbe282018-10-19 13:09:22 -07001745 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001746 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001747 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001748 }
David Sodman79bba0e2018-08-05 18:07:49 -07001749 }
1750 }
1751 }
1752
1753 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001754 for (const auto& [token, displayDevice] : mDisplays) {
1755 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001756 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001757 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001758 continue;
1759 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001760 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001761
1762 if (mDrawingState.colorMatrixChanged) {
1763 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001764 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001765 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001766 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001767 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001768 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1769 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001770 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001771 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001772 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1773 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001774 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001775 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001776 }
1777
Peiyong Lind3788632018-09-18 16:01:31 -07001778 // TODO(b/111562338) remove when composer 2.3 is shipped.
1779 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001780 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001781 }
1782
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001783 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001784 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001785 }
1786
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001787 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001788 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001789 layer->setCompositionType(displayDevice,
1790 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001791 continue;
1792 }
1793
Lloyd Pique32cbe282018-10-19 13:09:22 -07001794 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001795 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001796 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001797 }
1798
Peiyong Lin13effd12018-07-24 17:01:47 -07001799 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001800 ColorMode colorMode;
1801 Dataspace dataSpace;
1802 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001804 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001805 }
1806 }
1807
1808 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001809
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001810 for (const auto& [token, displayDevice] : mDisplays) {
1811 auto display = displayDevice->getCompositionDisplay();
1812 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001813 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001814 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1815 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1816 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001817 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001818 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001819 }
1820 }
David Sodman79bba0e2018-08-05 18:07:49 -07001821}
1822
Lloyd Pique32cbe282018-10-19 13:09:22 -07001823void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1824 bool repaintEverything) {
1825 auto display = displayDevice->getCompositionDisplay();
1826 const auto& displayState = display->getState();
1827
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828 // is debugging enabled
1829 if (CC_LIKELY(!mDebugRegion))
1830 return;
1831
Lloyd Pique32cbe282018-10-19 13:09:22 -07001832 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001833 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001834 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001835 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001836 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001837 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001838 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001840 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001841 }
1842 }
1843
Lloyd Pique32cbe282018-10-19 13:09:22 -07001844 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845
1846 if (mDebugRegion > 1) {
1847 usleep(mDebugRegion * 1000);
1848 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001849
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851}
1852
Adrian Roos1e1a1282017-11-01 19:05:31 +01001853void SurfaceFlinger::doTracing(const char* where) {
1854 ATRACE_CALL();
1855 ATRACE_NAME(where);
1856 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001857 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001858 }
1859}
1860
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001861void SurfaceFlinger::logLayerStats() {
1862 ATRACE_CALL();
1863 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001864 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001865 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001866 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001867 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001868 }
1869 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001870
1871 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001872 }
1873}
1874
David Sodman2b406362017-12-15 13:33:47 -08001875void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 ATRACE_CALL();
1878 ALOGV("preComposition");
1879
David Sodman2b406362017-12-15 13:33:47 -08001880 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1881
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001883 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001884 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885 needExtraInvalidate = true;
1886 }
Robert Carr2047fae2016-11-28 14:09:09 -08001887 });
1888
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889 if (needExtraInvalidate) {
1890 signalLayerUpdate();
1891 }
1892}
1893
Ana Krulece588e312018-09-18 12:32:24 -07001894void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1895 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896 // Update queue of past composite+present times and determine the
1897 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001898 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001900 while (!getBE().mCompositePresentTimes.empty()) {
1901 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902 // Cached values should have been updated before calling this method,
1903 // which helps avoid duplicate syscalls.
1904 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1905 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1906 break;
1907 }
1908 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001909 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001910 }
1911
1912 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001913 while (getBE().mCompositePresentTimes.size() > 16) {
1914 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915 }
1916
Ana Krulece588e312018-09-18 12:32:24 -07001917 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001918}
1919
Ana Krulece588e312018-09-18 12:32:24 -07001920void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1921 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001922 // Integer division and modulo round toward 0 not -inf, so we need to
1923 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001924 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1925 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1926 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927
Ana Krulec757f63a2019-01-25 10:46:18 -08001928 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001929 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001930 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001931 }
1932
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001933 // Snap the latency to a value that removes scheduling jitter from the
1934 // composition and present times, which often have >1ms of jitter.
1935 // Reducing jitter is important if an app attempts to extrapolate
1936 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001937 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001939 nsecs_t bias = stats.vsyncPeriod / 2;
1940 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1941 nsecs_t snappedCompositeToPresentLatency =
1942 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943
David Sodman99974d22017-11-28 12:04:33 -08001944 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001945 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1946 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001947 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948}
1949
Ady Abraham8164d482019-01-11 14:47:59 -08001950// debug patch for b/119477596 - add stack guards to catch stack
1951// corruptions and disable clang optimizations.
1952// The code below is temporary and planned to be removed once stack
1953// corruptions are found.
1954#pragma clang optimize off
1955class StackGuard {
1956public:
1957 StackGuard(const char* name, const char* func, int line) {
1958 guarders.reserve(MIN_CAPACITY);
1959 guarders.push_back({this, name, func, line});
1960 validate();
1961 }
1962 ~StackGuard() {
1963 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1964 if (i->guard == this) {
1965 guarders.erase(i);
1966 break;
1967 }
1968 }
1969 }
1970
1971 static void validate() {
1972 for (const auto& guard : guarders) {
1973 if (guard.guard->cookie != COOKIE_VALUE) {
1974 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1975 CallStack stack(LOG_TAG);
1976 abort();
1977 }
1978 }
1979 }
1980
1981private:
1982 uint64_t cookie = COOKIE_VALUE;
1983 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1984 static constexpr size_t MIN_CAPACITY = 16;
1985
1986 struct GuarderElement {
1987 StackGuard* guard;
1988 const char* name;
1989 const char* func;
1990 int line;
1991 };
1992
1993 static std::vector<GuarderElement> guarders;
1994};
1995std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1996
1997#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1998
1999#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002000void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001{
Ady Abraham8164d482019-01-11 14:47:59 -08002002 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 ATRACE_CALL();
2004 ALOGV("postComposition");
2005
Brian Anderson3546a3f2016-07-14 11:51:14 -07002006 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002007 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002008 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002009 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002010 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002011 }
Ady Abraham8164d482019-01-11 14:47:59 -08002012 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002013
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002014 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002015 const auto displayDevice = getDefaultDisplayDeviceLocked();
2016 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002017
David Sodman73beded2017-11-15 11:56:06 -08002018 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002020 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2021
Lloyd Pique32cbe282018-10-19 13:09:22 -07002022 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002024 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2025 ->getRenderSurface()
2026 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028 } else {
2029 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2030 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002031
Ady Abraham8164d482019-01-11 14:47:59 -08002032 ASSERT_ON_STACK_GUARD();
2033
David Sodman73beded2017-11-15 11:56:06 -08002034 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002035 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2036 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002037 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002038 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002039 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002040
Ana Krulece588e312018-09-18 12:32:24 -07002041 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002042 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002043 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044
Ady Abraham8164d482019-01-11 14:47:59 -08002045 ASSERT_ON_STACK_GUARD();
2046
David Sodman2b406362017-12-15 13:33:47 -08002047 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 // when we started doing work for this frame, but that should be okay
2049 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002050 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002051 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002052 DEFINE_STACK_GUARD(compositorTiming);
2053
Brian Andersond0010582017-03-07 13:20:31 -08002054 {
David Sodman99974d22017-11-28 12:04:33 -08002055 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002056 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002057 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002058
2059 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002060 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061
Robert Carr2047fae2016-11-28 14:09:09 -08002062 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002063 bool frameLatched =
2064 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2065 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002066 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002067 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002068 recordBufferingStats(layer->getName().string(),
2069 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002070 }
Ady Abraham8164d482019-01-11 14:47:59 -08002071 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002072 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002073
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002074 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002075 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002076 mScheduler->addPresentFence(presentFenceTime);
2077 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002078 }
2079
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002080 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002081 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2082 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002083 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002084 }
2085 }
2086
Ady Abraham8164d482019-01-11 14:47:59 -08002087 ASSERT_ON_STACK_GUARD();
2088
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002089 if (mAnimCompositionPending) {
2090 mAnimCompositionPending = false;
2091
Brian Anderson4e606e32017-03-16 15:34:57 -07002092 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002093 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002094 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002095
2096 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002098 // The HWC doesn't support present fences, so use the refresh
2099 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002100 const nsecs_t presentTime =
2101 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002102 DEFINE_STACK_GUARD(presentTime);
2103
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002104 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002105 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 }
2107 mAnimFrameTracker.advanceFrame();
2108 }
Dan Stozab90cf072015-03-05 11:05:59 -08002109
Ady Abraham8164d482019-01-11 14:47:59 -08002110 ASSERT_ON_STACK_GUARD();
2111
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002112 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002113 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002114 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002115 }
2116
Ady Abraham8164d482019-01-11 14:47:59 -08002117 ASSERT_ON_STACK_GUARD();
2118
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002119 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002120
Ady Abraham8164d482019-01-11 14:47:59 -08002121 ASSERT_ON_STACK_GUARD();
2122
Lloyd Pique32cbe282018-10-19 13:09:22 -07002123 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2124 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002125 return;
2126 }
2127
2128 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002129 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002130 if (mHasPoweredOff) {
2131 mHasPoweredOff = false;
2132 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002133 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002134 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002135 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002136 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002137 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2138 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002139 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002140 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002141 }
David Sodman4a36e932017-11-07 14:29:47 -08002142 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002143
2144 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002145 }
David Sodman4a36e932017-11-07 14:29:47 -08002146 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002147 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002148
2149 {
2150 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002151 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002152 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002153 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002154 if (refillCount > 0) {
2155 const size_t offset = mTexturePool.size();
2156 mTexturePool.resize(mTexturePoolSize);
2157 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2158 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2159 }
Ady Abraham8164d482019-01-11 14:47:59 -08002160 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002161 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002162
Marissa Wallfda30bb2018-10-12 11:34:28 -07002163 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002164 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002165
2166 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002167}
Ady Abraham8164d482019-01-11 14:47:59 -08002168#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002169
Vishnu Nair4351ad52019-02-11 14:13:02 -08002170void SurfaceFlinger::computeLayerBounds() {
2171 for (const auto& pair : mDisplays) {
2172 const auto& displayDevice = pair.second;
2173 const auto display = displayDevice->getCompositionDisplay();
2174 for (const auto& layer : mDrawingState.layersSortedByZ) {
2175 // only consider the layers on the given layer stack
2176 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002177 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002178 }
2179
2180 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2181 }
2182 }
2183}
2184
Mathias Agopiancd60f992012-08-16 16:28:27 -07002185void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 ATRACE_CALL();
2187 ALOGV("rebuildLayerStacks");
2188
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002189 // We need to clear these out now as these may be holding on to a
2190 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2191 // also holds a reference. When the set of visible layers is recomputed,
2192 // some layers may be destroyed if the only thing keeping them alive was
2193 // that list of visible layers associated with each display. The layer
2194 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2195 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2196 for (const auto& [token, display] : mDisplays) {
2197 getBE().mCompositionInfo[token].clear();
2198 }
2199
Mathias Agopiancd60f992012-08-16 16:28:27 -07002200 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002201 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002202 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002203 mVisibleRegionsDirty = false;
2204 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002205
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002206 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002207 const auto& displayDevice = pair.second;
2208 auto display = displayDevice->getCompositionDisplay();
2209 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 Region opaqueRegion;
2211 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002212 compositionengine::Output::OutputLayers layersSortedByZ;
2213 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002214 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002215 const ui::Transform& tr = displayState.transform;
2216 const Rect bounds = displayState.bounds;
2217 if (displayState.isEnabled) {
2218 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002219
Jeff Sharkey76488112017-02-27 14:15:18 -07002220 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002221 auto compositionLayer = layer->getCompositionLayer();
2222 if (compositionLayer == nullptr) {
2223 return;
2224 }
2225
Lloyd Pique32cbe282018-10-19 13:09:22 -07002226 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002227 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2228 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2229
Lloyd Pique07e33212018-12-18 16:33:37 -08002230 bool needsOutputLayer = false;
2231
Lloyd Piqueef36b002019-01-23 17:52:04 -08002232 if (display->belongsInOutput(layer->getLayerStack(),
2233 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002234 Region drawRegion(tr.transform(
2235 layer->visibleNonTransparentRegion));
2236 drawRegion.andSelf(bounds);
2237 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002238 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 }
Chia-I Wu83806892017-11-16 10:50:20 -08002240 }
2241
Lloyd Pique07e33212018-12-18 16:33:37 -08002242 if (needsOutputLayer) {
2243 layersSortedByZ.emplace_back(
2244 display->getOrCreateOutputLayer(displayId, compositionLayer,
2245 layerFE));
2246 deprecated_layersSortedByZ.add(layer);
2247
2248 auto& outputLayerState = layersSortedByZ.back()->editState();
2249 outputLayerState.visibleRegion =
2250 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2251 } else if (displayId) {
2252 // For layers that are being removed from a HWC display,
2253 // and that have queued frames, add them to a a list of
2254 // released layers so we can properly set a fence.
2255 bool hasExistingOutputLayer =
2256 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2257 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2258 mLayersWithQueuedFrames.cend(),
2259 layer) != mLayersWithQueuedFrames.cend();
2260
2261 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002262 layersNeedingFences.add(layer);
2263 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002264 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002265 });
2266 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002267
2268 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2269
2270 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002271 displayDevice->setLayersNeedingFences(layersNeedingFences);
2272
2273 Region undefinedRegion{bounds};
2274 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2275
2276 display->editState().undefinedRegion = undefinedRegion;
2277 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002278 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002279 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002280}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002281
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002284// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002285// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002286// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287// The returned HDR data space is one of
2288// - Dataspace::UNKNOWN
2289// - Dataspace::BT2020_HLG
2290// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2292 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002293 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 *outHdrDataSpace = Dataspace::UNKNOWN;
2295
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002296 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002297 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298 case Dataspace::V0_SCRGB:
2299 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002300 case Dataspace::BT2020:
2301 case Dataspace::BT2020_ITU:
2302 case Dataspace::BT2020_LINEAR:
2303 case Dataspace::DISPLAY_BT2020:
2304 bestDataSpace = Dataspace::DISPLAY_BT2020;
2305 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002306 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002307 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002308 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002309 case Dataspace::BT2020_PQ:
2310 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002311 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002312 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002313 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002314 case Dataspace::BT2020_HLG:
2315 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002316 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002317 // When there's mixed PQ content and HLG content, we set the HDR
2318 // data space to be BT2020_PQ and convert HLG to PQ.
2319 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2320 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002321 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322 break;
2323 default:
2324 break;
2325 }
Romain Guy54f154a2017-10-24 21:40:32 +01002326 }
2327
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002328 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002329}
2330
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002331// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002332void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2333 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2335 *outMode = ColorMode::NATIVE;
2336 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002339 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002340
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002341 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002344 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2345
Peiyong Lina3ea5592019-02-10 14:45:00 -08002346 switch (mForceColorMode) {
2347 case ColorMode::SRGB:
2348 bestDataSpace = Dataspace::V0_SRGB;
2349 break;
2350 case ColorMode::DISPLAY_P3:
2351 bestDataSpace = Dataspace::DISPLAY_P3;
2352 break;
2353 default:
2354 break;
2355 }
2356
Peiyong Lindfde5112018-06-05 10:58:41 -07002357 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002358 const bool isHdr =
2359 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002360 if (isHdr) {
2361 bestDataSpace = hdrDataSpace;
2362 }
2363
Chia-I Wu0d711262018-05-21 15:19:35 -07002364 RenderIntent intent;
2365 switch (mDisplayColorSetting) {
2366 case DisplayColorSetting::MANAGED:
2367 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002368 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002369 break;
2370 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002371 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002372 break;
2373 default: // vendor display color setting
2374 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2375 break;
2376 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002377
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002378 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002379}
2380
Lloyd Pique32cbe282018-10-19 13:09:22 -07002381void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2382 auto display = displayDevice->getCompositionDisplay();
2383 const auto& displayState = display->getState();
2384
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002385 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002386 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2387 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002388
David Sodmanfa9b2af2017-12-24 13:28:59 -08002389 // If nothing has changed (!dirty), don't recompose.
2390 // If something changed, but we don't currently have any visible layers,
2391 // and didn't when we last did a composition, then skip it this time.
2392 // The second rule does two things:
2393 // - When all layers are removed from a display, we'll emit one black
2394 // frame, then nothing more until we get new layers.
2395 // - When a display is created with a private layer stack, we won't
2396 // emit any black frames until a layer is added to the layer stack.
2397 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002398
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 const char flagPrefix[] = {'-', '+'};
2400 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2402 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2403 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2404 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002405
Lloyd Pique31cb2942018-10-19 17:23:03 -07002406 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002407
David Sodmanfa9b2af2017-12-24 13:28:59 -08002408 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002409 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002410 }
2411}
2412
Lloyd Pique32cbe282018-10-19 13:09:22 -07002413void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2414 auto display = displayDevice->getCompositionDisplay();
2415 const auto& displayState = display->getState();
2416
2417 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 return;
David Sodman2b406362017-12-15 13:33:47 -08002419 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002420
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002421 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002422 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002423 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002424}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002425
Lloyd Pique32cbe282018-10-19 13:09:22 -07002426void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002427 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 ALOGV("doComposition");
2429
Lloyd Pique32cbe282018-10-19 13:09:22 -07002430 auto display = displayDevice->getCompositionDisplay();
2431 const auto& displayState = display->getState();
2432
2433 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002434 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002435 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002436
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002438 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002439
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002441 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002442 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002444}
2445
David Sodmanfa9b2af2017-12-24 13:28:59 -08002446void SurfaceFlinger::postFrame()
2447{
2448 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 const auto display = getDefaultDisplayDeviceLocked();
2450 if (display && getHwComposer().isConnected(*display->getId())) {
2451 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002452 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2453 logFrameStats();
2454 }
2455 }
2456}
2457
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002459 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002461
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462 auto display = displayDevice->getCompositionDisplay();
2463 const auto& displayState = display->getState();
2464 const auto displayId = display->getId();
2465
David Sodmanfa9b2af2017-12-24 13:28:59 -08002466 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002467
Lloyd Pique32cbe282018-10-19 13:09:22 -07002468 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 if (displayId) {
2470 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002471 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002472 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002473 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002474 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002475
Chia-I Wu7b549592017-11-15 09:14:57 -08002476 // The layer buffer from the previous frame (if any) is released
2477 // by HWC only when the release fence from this frame (if any) is
2478 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002479 if (displayId && layer->hasHwcLayer(displayDevice)) {
2480 releaseFence =
2481 getHwComposer().getLayerReleaseFence(*displayId,
2482 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002483 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002484
2485 // If the layer was client composited in the previous frame, we
2486 // need to merge with the previous client target acquire fence.
2487 // Since we do not track that, always merge with the current
2488 // client target acquire fence when it is available, even though
2489 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002490 if (layer->getCompositionType(displayDevice) ==
2491 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002492 releaseFence =
2493 Fence::merge("LayerRelease", releaseFence,
2494 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002495 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002496
David Sodman15094112018-10-11 09:39:37 -07002497 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 }
Chia-I Wu83806892017-11-16 10:50:20 -08002499
2500 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002502 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002503 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002504 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002505 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002506 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002507 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002508 }
2509 }
2510
Dominik Laskowski075d3172018-05-24 15:50:06 -07002511 if (displayId) {
2512 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002513 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002514 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515}
2516
Mathias Agopian87baae12012-07-31 12:38:26 -07002517void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518{
Mathias Agopian841cde52012-03-01 15:44:37 -08002519 ATRACE_CALL();
2520
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002521 // here we keep a copy of the drawing state (that is the state that's
2522 // going to be overwritten by handleTransactionLocked()) outside of
2523 // mStateLock so that the side-effects of the State assignment
2524 // don't happen with mStateLock held (which can cause deadlocks).
2525 State drawingState(mDrawingState);
2526
Mathias Agopianca4d3602011-05-19 15:38:14 -07002527 Mutex::Autolock _l(mStateLock);
2528 const nsecs_t now = systemTime();
2529 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530
Mathias Agopianca4d3602011-05-19 15:38:14 -07002531 // Here we're guaranteed that some transaction flags are set
2532 // so we can call handleTransactionLocked() unconditionally.
2533 // We call getTransactionFlags(), which will also clear the flags,
2534 // with mStateLock held to guarantee that mCurrentState won't change
2535 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002536
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002537 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002538 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002539 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002540
Mathias Agopianca4d3602011-05-19 15:38:14 -07002541 mLastTransactionTime = systemTime() - now;
2542 mDebugInTransaction = 0;
2543 invalidateHwcGeometry();
2544 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002545}
2546
Lloyd Piqueba04e622017-12-14 17:11:26 -08002547void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2548 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 const std::optional<DisplayIdentificationInfo> info =
2550 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002551
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553 continue;
2554 }
2555
Lloyd Piqueba04e622017-12-14 17:11:26 -08002556 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002558 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 mPhysicalDisplayTokens[info->id] = new BBinder();
2560 DisplayDeviceState state;
2561 state.displayId = info->id;
2562 state.isSecure = true; // All physical displays are currently considered secure.
2563 state.displayName = info->name;
2564 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2565 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002566 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002567 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002568 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002569
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2571 if (index >= 0) {
2572 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2573 mInterceptor->saveDisplayDeletion(state.sequenceId);
2574 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002575 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002576 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002577 }
2578
2579 processDisplayChangesLocked();
2580 }
2581
2582 mPendingHotplugEvents.clear();
2583}
2584
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002585void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002586 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2587 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002588}
2589
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002592 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002593 const sp<IGraphicBufferProducer>& producer) {
2594 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002595 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002597 creationArgs.isSecure = state.isSecure;
2598 creationArgs.displaySurface = dispSurface;
2599 creationArgs.hasWideColorGamut = false;
2600 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002601
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002602 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 creationArgs.isPrimary = isInternalDisplay;
2604
2605 if (useColorManagement && displayId) {
2606 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002608 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002609 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002611
Dominik Laskowski7e045462018-05-30 13:02:02 -07002612 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615 }
tangrobin6753a022018-08-10 10:58:54 +08002616 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 if (displayId) {
2619 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002621 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002622 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623
Lloyd Pique90c115d2018-09-18 21:39:42 -07002624 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002626 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628 // Make sure that composition can never be stalled by a virtual display
2629 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002630 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002631 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2633 }
2634
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 creationArgs.displayInstallOrientation =
2636 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002637
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002639 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002640
Lloyd Pique90c115d2018-09-18 21:39:42 -07002641 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642
2643 if (maxFrameBufferAcquiredBuffers >= 3) {
2644 nativeWindowSurface->preallocateBuffers();
2645 }
2646
2647 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002648 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002649 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002651 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002653 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2654 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 if (!state.isVirtual()) {
2656 LOG_ALWAYS_FATAL_IF(!displayId);
2657 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002658 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002659
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002660 display->setLayerStack(state.layerStack);
2661 display->setProjection(state.orientation, state.viewport, state.frame);
2662 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002664 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665}
2666
Lloyd Pique347200f2017-12-14 17:00:15 -08002667void SurfaceFlinger::processDisplayChangesLocked() {
2668 // here we take advantage of Vector's copy-on-write semantics to
2669 // improve performance by skipping the transaction entirely when
2670 // know that the lists are identical
2671 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2672 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2673 if (!curr.isIdenticalTo(draw)) {
2674 mVisibleRegionsDirty = true;
2675 const size_t cc = curr.size();
2676 size_t dc = draw.size();
2677
2678 // find the displays that were removed
2679 // (ie: in drawing state but not in current state)
2680 // also handle displays that changed
2681 // (ie: displays that are in both lists)
2682 for (size_t i = 0; i < dc;) {
2683 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2684 if (j < 0) {
2685 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002687 // Save display ID before disconnecting.
2688 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002689 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002690
2691 if (!display->isVirtual()) {
2692 LOG_ALWAYS_FATAL_IF(!displayId);
2693 dispatchDisplayHotplugEvent(displayId->value, false);
2694 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002696
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002698 } else {
2699 // this display is in both lists. see if something changed.
2700 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2703 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2704 if (state_binder != draw_binder) {
2705 // changing the surface is like destroying and
2706 // recreating the DisplayDevice, so we just remove it
2707 // from the drawing state, so that it get re-added
2708 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002710 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002712 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002713 mDrawingState.displays.removeItemsAt(i);
2714 dc--;
2715 // at this point we must loop to the next item
2716 continue;
2717 }
2718
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002719 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 }
2723 if ((state.orientation != draw[i].orientation) ||
2724 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 }
2727 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 }
2730 }
2731 }
2732 ++i;
2733 }
2734
2735 // find displays that were added
2736 // (ie: in current state but not in drawing state)
2737 for (size_t i = 0; i < cc; i++) {
2738 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2739 const DisplayDeviceState& state(curr[i]);
2740
Lloyd Pique542307f2018-10-19 13:24:08 -07002741 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 sp<IGraphicBufferProducer> producer;
2743 sp<IGraphicBufferProducer> bqProducer;
2744 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002745 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002748 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 // Virtual displays without a surface are dormant:
2750 // they have external state (layer stack, projection,
2751 // etc.) but no internal state (i.e. a DisplayDevice).
2752 if (state.surface != nullptr) {
2753 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002754 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 int width = 0;
2756 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2757 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2758 int height = 0;
2759 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2760 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2761 int intFormat = 0;
2762 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2763 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002764 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765
Dominik Laskowski075d3172018-05-24 15:50:06 -07002766 displayId =
2767 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 }
2769
2770 // TODO: Plumb requested format back up to consumer
2771
2772 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002773 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 bqProducer, bqConsumer,
2775 state.displayName);
2776
2777 dispSurface = vds;
2778 producer = vds;
2779 }
2780 } else {
2781 ALOGE_IF(state.surface != nullptr,
2782 "adding a supported display, but rendering "
2783 "surface is provided (%p), ignoring it",
2784 state.surface.get());
2785
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 displayId = state.displayId;
2787 LOG_ALWAYS_FATAL_IF(!displayId);
2788 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002789 producer = bqProducer;
2790 }
2791
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002792 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002794 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002795 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002797 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002798 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002799 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002800 }
2801 }
2802 }
2803 }
2804 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002805
2806 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002807}
2808
Mathias Agopian87baae12012-07-31 12:38:26 -07002809void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002810{
Dan Stoza7dde5992015-05-22 09:51:44 -07002811 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002812 mCurrentState.traverseInZOrder([](Layer* layer) {
2813 layer->notifyAvailableFrames();
2814 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002815
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816 /*
2817 * Traversal of the children
2818 * (perform the transaction for each of them if needed)
2819 */
2820
Mathias Agopian3559b072012-08-15 13:46:03 -07002821 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002822 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002824 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825
2826 const uint32_t flags = layer->doTransaction(0);
2827 if (flags & Layer::eVisibleRegion)
2828 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002829
2830 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002831 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002832 }
Robert Carr2047fae2016-11-28 14:09:09 -08002833 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834 }
2835
2836 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002837 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 */
2839
Mathias Agopiane57f2922012-08-09 16:29:12 -07002840 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002842 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002843 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002845 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002846 // The transform hint might have changed for some layers
2847 // (either because a display has changed, or because a layer
2848 // as changed).
2849 //
2850 // Walk through all the layers in currentLayers,
2851 // and update their transform hint.
2852 //
2853 // If a layer is visible only on a single display, then that
2854 // display is used to calculate the hint, otherwise we use the
2855 // default display.
2856 //
2857 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2858 // the hint is set before we acquire a buffer from the surface texture.
2859 //
2860 // NOTE: layer transactions have taken place already, so we use their
2861 // drawing state. However, SurfaceFlinger's own transaction has not
2862 // happened yet, so we must use the current state layer list
2863 // (soon to become the drawing state list).
2864 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002865 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002866 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002867 bool first = true;
2868 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002869 // NOTE: we rely on the fact that layers are sorted by
2870 // layerStack first (so we don't have to traverse the list
2871 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002872 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002873 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002874 currentlayerStack = layerStack;
2875 // figure out if this layerstack is mirrored
2876 // (more than one display) if so, pick the default display,
2877 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002878 hintDisplay = nullptr;
2879 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002880 if (display->getCompositionDisplay()
2881 ->belongsInOutput(layer->getLayerStack(),
2882 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002883 if (hintDisplay) {
2884 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002885 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002886 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002887 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002888 }
2889 }
2890 }
2891 }
Chet Haase91d25932013-04-11 15:24:55 -07002892
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002894 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2895 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002896
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002897 // could be null when this layer is using a layerStack
2898 // that is not visible on any display. Also can occur at
2899 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002900 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002901 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002902
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002904 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 if (hintDisplay) {
2906 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002907 }
Robert Carr2047fae2016-11-28 14:09:09 -08002908
2909 first = false;
2910 });
Mathias Agopian84300952012-11-21 16:02:13 -08002911 }
2912
2913
Mathias Agopian3559b072012-08-15 13:46:03 -07002914 /*
2915 * Perform our own transaction if needed
2916 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002917
2918 if (mLayersAdded) {
2919 mLayersAdded = false;
2920 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002921 mVisibleRegionsDirty = true;
2922 }
2923
2924 // some layers might have been removed, so
2925 // we need to update the regions they're exposing.
2926 if (mLayersRemoved) {
2927 mLayersRemoved = false;
2928 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002929 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002930 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002931 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002932 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002933 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002934 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002935 }
Robert Carr2047fae2016-11-28 14:09:09 -08002936 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 }
2938
Vishnu Nairec0ab382019-02-13 15:32:56 -08002939 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002940 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002941}
2942
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002943void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002944 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002945 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002946 return;
2947 }
2948
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002949 if (mVisibleRegionsDirty || mInputInfoChanged) {
2950 mInputInfoChanged = false;
2951 updateInputWindowInfo();
2952 }
2953
2954 executeInputWindowCommands();
2955}
2956
2957void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002958 Vector<InputWindowInfo> inputHandles;
2959
2960 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2961 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002962 // When calculating the screen bounds we ignore the transparent region since it may
2963 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002964 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002965 }
2966 });
2967 mInputFlinger->setInputWindows(inputHandles);
2968}
2969
Vishnu Nairec0ab382019-02-13 15:32:56 -08002970void SurfaceFlinger::commitInputWindowCommands() {
2971 mInputWindowCommands.merge(mPendingInputWindowCommands);
2972 mPendingInputWindowCommands.clear();
2973}
2974
chaviwfbe5d9c2018-12-26 12:23:37 -08002975void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002976 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2977 if (transferTouchFocusCommand.fromToken != nullptr &&
2978 transferTouchFocusCommand.toToken != nullptr &&
2979 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2980 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2981 transferTouchFocusCommand.toToken);
2982 }
2983 }
2984
2985 mInputWindowCommands.clear();
2986}
2987
Riley Andrews03414a12014-07-01 14:22:59 -07002988void SurfaceFlinger::updateCursorAsync()
2989{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002990 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002991 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002992 continue;
2993 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2996 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002997 }
2998 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002999}
3000
chaviw61626f22018-11-15 16:26:27 -08003001void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3002 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003003 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003004 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003005 }
3006 layer->releasePendingBuffer(systemTime());
3007}
3008
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009void SurfaceFlinger::commitTransaction()
3010{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003011 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003013 for (const auto& l : mLayersPendingRemoval) {
3014 recordBufferingStats(l->getName().string(),
3015 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003016
Lloyd Pique07e33212018-12-18 16:33:37 -08003017 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003018 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003019 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003020 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003021 }
3022 mLayersPendingRemoval.clear();
3023 }
3024
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003025 // If this transaction is part of a window animation then the next frame
3026 // we composite should be considered an animation as well.
3027 mAnimCompositionPending = mAnimTransactionPending;
3028
Mathias Agopian4fec8732012-06-29 14:12:52 -07003029 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003030 // clear the "changed" flags in current state
3031 mCurrentState.colorMatrixChanged = false;
3032
Robert Carr1f0a16a2016-10-24 16:27:39 -07003033 mDrawingState.traverseInZOrder([](Layer* layer) {
3034 layer->commitChildList();
3035 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003036 mTransactionPending = false;
3037 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003038 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039}
3040
Lloyd Pique32cbe282018-10-19 13:09:22 -07003041void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003043 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003045
Lloyd Pique32cbe282018-10-19 13:09:22 -07003046 auto display = displayDevice->getCompositionDisplay();
3047
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048 Region aboveOpaqueLayers;
3049 Region aboveCoveredLayers;
3050 Region dirty;
3051
Mathias Agopian87baae12012-07-31 12:38:26 -07003052 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053
Robert Carr2047fae2016-11-28 14:09:09 -08003054 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003055 // start with the whole surface at its current location
3056 const Layer::State& s(layer->getDrawingState());
3057
Jesse Hall01e29052013-02-19 16:13:35 -08003058 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003059 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003060 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003061 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003062
Mathias Agopianab028732010-03-16 16:41:46 -07003063 /*
3064 * opaqueRegion: area of a surface that is fully opaque.
3065 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003067
3068 /*
3069 * visibleRegion: area of a surface that is visible on screen
3070 * and not fully transparent. This is essentially the layer's
3071 * footprint minus the opaque regions above it.
3072 * Areas covered by a translucent surface are considered visible.
3073 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003075
3076 /*
3077 * coveredRegion: area of a surface that is covered by all
3078 * visible regions above it (which includes the translucent areas).
3079 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003081
Jesse Halla8026d22012-09-25 13:25:04 -07003082 /*
3083 * transparentRegion: area of a surface that is hinted to be completely
3084 * transparent. This is only used to tell when the layer has no visible
3085 * non-transparent regions and can be removed from the layer list. It
3086 * does not affect the visibleRegion of this layer or any layers
3087 * beneath it. The hint may not be correct if apps don't respect the
3088 * SurfaceView restrictions (which, sadly, some don't).
3089 */
3090 Region transparentRegion;
3091
Mathias Agopianab028732010-03-16 16:41:46 -07003092
3093 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003094 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003095 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003096 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003097
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003099 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003100 if (!visibleRegion.isEmpty()) {
3101 // Remove the transparent area from the visible region
3102 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003103 if (tr.preserveRects()) {
3104 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003105 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003106 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003107 // transformation too complex, can't do the
3108 // transparent region optimization.
3109 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003110 }
Mathias Agopianab028732010-03-16 16:41:46 -07003111 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003112
Mathias Agopianab028732010-03-16 16:41:46 -07003113 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003114 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003115 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003116 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003117 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003118 // the opaque region is the layer's footprint
3119 opaqueRegion = visibleRegion;
3120 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 }
3122 }
3123
Robert Carre5f4f692018-01-12 13:12:28 -08003124 if (visibleRegion.isEmpty()) {
3125 layer->clearVisibilityRegions();
3126 return;
3127 }
3128
Mathias Agopianab028732010-03-16 16:41:46 -07003129 // Clip the covered region to the visible region
3130 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3131
3132 // Update aboveCoveredLayers for next (lower) layer
3133 aboveCoveredLayers.orSelf(visibleRegion);
3134
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003135 // subtract the opaque region covered by the layers above us
3136 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137
3138 // compute this layer's dirty region
3139 if (layer->contentDirty) {
3140 // we need to invalidate the whole region
3141 dirty = visibleRegion;
3142 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003143 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144 layer->contentDirty = false;
3145 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003146 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003147 * the exposed region consists of two components:
3148 * 1) what's VISIBLE now and was COVERED before
3149 * 2) what's EXPOSED now less what was EXPOSED before
3150 *
3151 * note that (1) is conservative, we start with the whole
3152 * visible region but only keep what used to be covered by
3153 * something -- which mean it may have been exposed.
3154 *
3155 * (2) handles areas that were not covered by anything but got
3156 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003157 */
Mathias Agopianab028732010-03-16 16:41:46 -07003158 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003159 const Region oldVisibleRegion = layer->visibleRegion;
3160 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003161 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3162 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 }
3164 dirty.subtractSelf(aboveOpaqueLayers);
3165
3166 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003167 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168
Mathias Agopianab028732010-03-16 16:41:46 -07003169 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003171
Jesse Halla8026d22012-09-25 13:25:04 -07003172 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173 layer->setVisibleRegion(visibleRegion);
3174 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003175 layer->setVisibleNonTransparentRegion(
3176 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003177 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178
Mathias Agopian87baae12012-07-31 12:38:26 -07003179 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180}
3181
Chia-I Wuab0c3192017-08-01 11:29:00 -07003182void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003183 for (const auto& [token, displayDevice] : mDisplays) {
3184 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003185 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003186 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003187 }
3188 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003189}
3190
Daniel Solomon42d04562019-01-20 21:03:19 -08003191void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3192 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3193 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3194 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3195 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3196 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3197 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3198 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3199 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3200 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3201 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3202 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3203 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3204}
3205
Dan Stoza6b9454d2014-11-07 16:00:59 -08003206bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003208 ALOGV("handlePageFlip");
3209
Brian Andersond6927fb2016-07-23 23:37:30 -07003210 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211
Mathias Agopian4fec8732012-06-29 14:12:52 -07003212 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003213 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003214 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003215
3216 // Store the set of layers that need updates. This set must not change as
3217 // buffers are being latched, as this could result in a deadlock.
3218 // Example: Two producers share the same command stream and:
3219 // 1.) Layer 0 is latched
3220 // 2.) Layer 0 gets a new frame
3221 // 2.) Layer 1 gets a new frame
3222 // 3.) Layer 1 is latched.
3223 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3224 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003225 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003226 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003227 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003228 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003229 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003230 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003231 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003232 } else {
3233 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003234 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003235 } else {
3236 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003237 }
Robert Carr2047fae2016-11-28 14:09:09 -08003238 });
3239
Lloyd Piquef2c79392018-12-20 16:23:33 -08003240 if (!mLayersWithQueuedFrames.empty()) {
3241 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3242 // writes to Layer current state. See also b/119481871
3243 Mutex::Autolock lock(mStateLock);
3244
3245 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003246 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003247 mLayersPendingRefresh.push_back(layer);
3248 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003249 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003250 if (layer->isBufferLatched()) {
3251 newDataLatched = true;
3252 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003253 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003254 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003255
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003256 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003257
3258 // If we will need to wake up at some time in the future to deal with a
3259 // queued frame that shouldn't be displayed during this vsync period, wake
3260 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003261 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003262 signalLayerUpdate();
3263 }
3264
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003265 // enter boot animation on first buffer latch
3266 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3267 ALOGI("Enter boot animation");
3268 mBootStage = BootStage::BOOTANIMATION;
3269 }
3270
Dan Stoza6b9454d2014-11-07 16:00:59 -08003271 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003272 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273}
3274
Mathias Agopianad456f92011-01-13 17:53:01 -08003275void SurfaceFlinger::invalidateHwcGeometry()
3276{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003277 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003278}
3279
Lloyd Pique32cbe282018-10-19 13:09:22 -07003280void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003281 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003282 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003283 // We only need to actually compose the display if:
3284 // 1) It is being handled by hardware composer, which may need this to
3285 // keep its virtual display state machine in sync, or
3286 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003287 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003288 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003289 return;
3290 }
3291
Dan Stoza9e56aa02015-11-02 13:00:03 -08003292 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003293 base::unique_fd readyFence;
3294 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003295
3296 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003297 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298}
3299
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003300bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3301 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003302 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003303 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003304
Lloyd Pique32cbe282018-10-19 13:09:22 -07003305 auto display = displayDevice->getCompositionDisplay();
3306 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003307 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003308
3309 const Region bounds(displayState.bounds);
3310 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003311 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003312 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003313
Peiyong Lind3788632018-09-18 16:01:31 -07003314 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003315 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003316
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003317 renderengine::DisplaySettings clientCompositionDisplay;
3318 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3319 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003320
Dan Stoza9e56aa02015-11-02 13:00:03 -08003321 if (hasClientComposition) {
3322 ALOGV("hasClientComposition");
3323
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003324 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003325
3326 if (buf == nullptr) {
3327 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3328 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003330 return false;
3331 }
3332
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003333 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3334 clientCompositionDisplay.clip = displayState.scissor;
3335 const ui::Transform& displayTransform = displayState.transform;
3336 mat4 m;
3337 m[0][0] = displayTransform[0][0];
3338 m[0][1] = displayTransform[0][1];
3339 m[0][3] = displayTransform[0][2];
3340 m[1][0] = displayTransform[1][0];
3341 m[1][1] = displayTransform[1][1];
3342 m[1][3] = displayTransform[1][2];
3343 m[3][0] = displayTransform[2][0];
3344 m[3][1] = displayTransform[2][1];
3345 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003346
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003347 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003348
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003349 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003350 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003351 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003352 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003353 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003354 clientCompositionDisplay.outputDataspace = outputDataspace;
3355 clientCompositionDisplay.maxLuminance =
3356 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003357
Lloyd Pique441d5042018-10-18 16:49:51 -07003358 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003359 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003360 getHwComposer()
3361 .hasDisplayCapability(displayId,
3362 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003363
Peiyong Lind3788632018-09-18 16:01:31 -07003364 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003365 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3366 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003367 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003368 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003369 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003370
Mathias Agopian85d751c2012-08-29 16:59:24 -07003371 /*
3372 * and then, render the layers targeted at the framebuffer
3373 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003374
Dan Stoza9e56aa02015-11-02 13:00:03 -08003375 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003376 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003377 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003378 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003379 const Region viewportRegion(displayState.viewport);
3380 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003381 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003382 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003383 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003384 switch (layer->getCompositionType(displayDevice)) {
3385 case Hwc2::IComposerClient::Composition::CURSOR:
3386 case Hwc2::IComposerClient::Composition::DEVICE:
3387 case Hwc2::IComposerClient::Composition::SIDEBAND:
3388 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003389 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003390 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003391 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003392 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003393 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003394 // never clear the very first layer since we're
3395 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003396 renderengine::LayerSettings layerSettings;
3397 Region dummyRegion;
3398 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3399 layerSettings);
3400
3401 if (prepared) {
3402 layerSettings.source.buffer.buffer = nullptr;
3403 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3404 layerSettings.alpha = half(0.0);
3405 layerSettings.disableBlending = true;
3406 clientCompositionLayers.push_back(layerSettings);
3407 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003408 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003410 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003411 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003412 renderengine::LayerSettings layerSettings;
3413 bool prepared =
3414 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3415 if (prepared) {
3416 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003417 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003418 break;
3419 }
3420 default:
3421 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003422 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003423 } else {
3424 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003425 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003426 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003427 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003428
Alec Mouri820c7402019-01-23 13:02:39 -08003429 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003430 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003431 clientCompositionDisplay.clearRegion = clearRegion;
3432 if (!debugRegion.isEmpty()) {
3433 Region::const_iterator it = debugRegion.begin();
3434 Region::const_iterator end = debugRegion.end();
3435 while (it != end) {
3436 const Rect& rect = *it++;
3437 renderengine::LayerSettings layerSettings;
3438 layerSettings.source.buffer.buffer = nullptr;
3439 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3440 layerSettings.geometry.boundaries = rect.toFloatRect();
3441 layerSettings.alpha = half(1.0);
3442 clientCompositionLayers.push_back(layerSettings);
3443 }
3444 }
3445 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3446 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003447 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003448 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003449}
3450
Chia-I Wu28e3a252018-09-07 12:05:02 -07003451void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003452 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003453 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454}
3455
Dan Stoza7d89d062015-04-30 13:29:25 -07003456status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003457 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003458 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003459 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003460 const sp<Layer>& parent,
3461 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003462{
Dan Stoza7d89d062015-04-30 13:29:25 -07003463 // add this layer to the current state list
3464 {
3465 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003466 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003467 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3468 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 return NO_MEMORY;
3470 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003471 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003472 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003473 } else if (parent == nullptr) {
3474 lbc->onRemovedFromCurrentState();
3475 } else if (parent->isRemovedFromCurrentState()) {
3476 parent->addChild(lbc);
3477 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003478 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003479 parent->addChild(lbc);
3480 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003481
Yiwei Zhang243b3782018-05-15 17:40:04 -07003482 if (gbc != nullptr) {
3483 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3484 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3485 mMaxGraphicBufferProducerListSize,
3486 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3487 mGraphicBufferProducerList.size(),
3488 mMaxGraphicBufferProducerListSize, mNumLayers);
3489 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003490 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003491 }
3492
Mathias Agopian96f08192010-06-02 23:28:45 -07003493 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003494 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003495
Dan Stoza7d89d062015-04-30 13:29:25 -07003496 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003497}
3498
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003499uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003500 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003501}
3502
Mathias Agopian3f844832013-08-07 21:24:32 -07003503uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003504 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505}
3506
Mathias Agopian3f844832013-08-07 21:24:32 -07003507uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003508 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003509}
3510
3511uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003512 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003513 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003514 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003516 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 }
3518 return old;
3519}
3520
Marissa Wall713b63f2018-10-17 15:42:43 -07003521bool SurfaceFlinger::flushTransactionQueues() {
3522 Mutex::Autolock _l(mStateLock);
3523 auto it = mTransactionQueues.begin();
3524 while (it != mTransactionQueues.end()) {
3525 auto& [applyToken, transactionQueue] = *it;
3526
3527 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003528 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3529 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003530 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003531 break;
3532 }
Robert Carr14167e02019-02-13 13:50:55 -08003533 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003534 transactionQueue.pop();
3535 }
3536
3537 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3538 }
3539 return mTransactionQueues.empty();
3540}
3541
chaviwca27f252018-02-06 16:46:39 -08003542bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3543 for (const ComposerState& state : states) {
3544 // Here we need to check that the interface we're given is indeed
3545 // one of our own. A malicious client could give us a nullptr
3546 // IInterface, or one of its own or even one of our own but a
3547 // different type. All these situations would cause us to crash.
3548 if (state.client == nullptr) {
3549 return true;
3550 }
3551
3552 sp<IBinder> binder = IInterface::asBinder(state.client);
3553 if (binder == nullptr) {
3554 return true;
3555 }
3556
3557 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3558 return true;
3559 }
3560 }
3561 return false;
3562}
3563
Marissa Wall17b4e452018-12-26 16:32:34 -08003564bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3565 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003566 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003567 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3568 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3569 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3570 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3571 return false;
3572 }
3573
Marissa Wall713b63f2018-10-17 15:42:43 -07003574 for (const ComposerState& state : states) {
3575 const layer_state_t& s = state.state;
3576 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3577 continue;
3578 }
3579 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003580 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003581 }
3582 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003583 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003584}
3585
3586void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3587 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003588 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003589 const InputWindowCommands& inputWindowCommands,
3590 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003591 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003592
3593 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3594
Mathias Agopian698c0872011-06-28 19:09:31 -07003595 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003596
chaviwca27f252018-02-06 16:46:39 -08003597 if (containsAnyInvalidClientState(states)) {
3598 return;
3599 }
3600
Marissa Wall713b63f2018-10-17 15:42:43 -07003601 // If its TransactionQueue already has a pending TransactionState or if it is pending
3602 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003603 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003604 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3605 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003606 setTransactionFlags(eTransactionNeeded);
3607 return;
3608 }
3609
Robert Carr14167e02019-02-13 13:50:55 -08003610 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003611}
3612
3613void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003614 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003615 const InputWindowCommands& inputWindowCommands,
3616 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003617 uint32_t transactionFlags = 0;
3618
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003619 if (flags & eAnimation) {
3620 // For window updates that are part of an animation we must wait for
3621 // previous animation "frames" to be handled.
3622 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003623 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003624 if (CC_UNLIKELY(err != NO_ERROR)) {
3625 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003626 // caller after a few seconds.
3627 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3628 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003629 mAnimTransactionPending = false;
3630 break;
3631 }
3632 }
3633 }
3634
chaviwca27f252018-02-06 16:46:39 -08003635 for (const DisplayState& display : displays) {
3636 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003637 }
3638
Marissa Walle2ffb422018-10-12 11:33:52 -07003639 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003640 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003641 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003642 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003643 // If the state doesn't require a traversal and there are callbacks, send them now
3644 if (!(clientStateFlags & eTraversalNeeded)) {
3645 mTransactionCompletedThread.sendCallbacks();
3646 }
3647 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003648
chaviw273171b2018-12-26 11:46:30 -08003649 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3650
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003651 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3652 // anyway. This can be used as a flush mechanism for previous async transactions.
3653 // Empty animation transaction can be used to simulate back-pressure, so also force a
3654 // transaction for empty animation transactions.
3655 if (transactionFlags == 0 &&
3656 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003657 transactionFlags = eTransactionNeeded;
3658 }
3659
Mathias Agopian386aa982011-11-07 21:58:03 -08003660 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003661 if (mInterceptor->isEnabled()) {
3662 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003663 }
Irvel468051e2016-06-13 16:44:44 -07003664
Mathias Agopian386aa982011-11-07 21:58:03 -08003665 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003666 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3667 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003668 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003669
3670 // if this is a synchronous transaction, wait for it to take effect
3671 // before returning.
3672 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003673 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003674 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003675 if (flags & eAnimation) {
3676 mAnimTransactionPending = true;
3677 }
3678 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003679 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3680 if (CC_UNLIKELY(err != NO_ERROR)) {
3681 // just in case something goes wrong in SF, return to the
3682 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003683 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3684 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003685 break;
3686 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688 }
3689}
3690
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003691uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3692 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3693 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003694
Mathias Agopiane57f2922012-08-09 16:29:12 -07003695 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003696 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3697
3698 const uint32_t what = s.what;
3699 if (what & DisplayState::eSurfaceChanged) {
3700 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3701 state.surface = s.surface;
3702 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003703 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003705 if (what & DisplayState::eLayerStackChanged) {
3706 if (state.layerStack != s.layerStack) {
3707 state.layerStack = s.layerStack;
3708 flags |= eDisplayTransactionNeeded;
3709 }
3710 }
3711 if (what & DisplayState::eDisplayProjectionChanged) {
3712 if (state.orientation != s.orientation) {
3713 state.orientation = s.orientation;
3714 flags |= eDisplayTransactionNeeded;
3715 }
3716 if (state.frame != s.frame) {
3717 state.frame = s.frame;
3718 flags |= eDisplayTransactionNeeded;
3719 }
3720 if (state.viewport != s.viewport) {
3721 state.viewport = s.viewport;
3722 flags |= eDisplayTransactionNeeded;
3723 }
3724 }
3725 if (what & DisplayState::eDisplaySizeChanged) {
3726 if (state.width != s.width) {
3727 state.width = s.width;
3728 flags |= eDisplayTransactionNeeded;
3729 }
3730 if (state.height != s.height) {
3731 state.height = s.height;
3732 flags |= eDisplayTransactionNeeded;
3733 }
3734 }
3735
Mathias Agopiane57f2922012-08-09 16:29:12 -07003736 return flags;
3737}
3738
Robert Carr14167e02019-02-13 13:50:55 -08003739bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003740 IPCThreadState* ipc = IPCThreadState::self();
3741 const int pid = ipc->getCallingPid();
3742 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003743 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003744 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003745 return false;
3746 }
3747 return true;
3748}
3749
Robert Carr14167e02019-02-13 13:50:55 -08003750uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3751 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003752 const layer_state_t& s = composerState.state;
3753 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3754
Mathias Agopian13127d82013-03-05 17:47:11 -08003755 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003756 if (layer == nullptr) {
3757 return 0;
3758 }
3759
chaviw8b3871a2017-11-01 17:41:01 -07003760 uint32_t flags = 0;
3761
Garfield Tan8a3083e2018-12-03 13:21:07 -08003762 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003763 bool geometryAppliesWithResize =
3764 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003765
3766 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3767 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003768 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003769 layer->pushPendingState();
3770 }
3771
chaviw8b3871a2017-11-01 17:41:01 -07003772 if (what & layer_state_t::ePositionChanged) {
3773 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3774 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003775 }
chaviw8b3871a2017-11-01 17:41:01 -07003776 }
3777 if (what & layer_state_t::eLayerChanged) {
3778 // NOTE: index needs to be calculated before we update the state
3779 const auto& p = layer->getParent();
3780 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003781 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003782 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003783 mCurrentState.layersSortedByZ.removeAt(idx);
3784 mCurrentState.layersSortedByZ.add(layer);
3785 // we need traversal (state changed)
3786 // AND transaction (list changed)
3787 flags |= eTransactionNeeded|eTraversalNeeded;
3788 }
chaviw8b3871a2017-11-01 17:41:01 -07003789 } else {
3790 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003791 flags |= eTransactionNeeded|eTraversalNeeded;
3792 }
3793 }
chaviw8b3871a2017-11-01 17:41:01 -07003794 }
3795 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003796 // NOTE: index needs to be calculated before we update the state
3797 const auto& p = layer->getParent();
3798 if (p == nullptr) {
3799 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3800 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3801 mCurrentState.layersSortedByZ.removeAt(idx);
3802 mCurrentState.layersSortedByZ.add(layer);
3803 // we need traversal (state changed)
3804 // AND transaction (list changed)
3805 flags |= eTransactionNeeded|eTraversalNeeded;
3806 }
3807 } else {
3808 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3809 flags |= eTransactionNeeded|eTraversalNeeded;
3810 }
chaviw8b3871a2017-11-01 17:41:01 -07003811 }
3812 }
3813 if (what & layer_state_t::eSizeChanged) {
3814 if (layer->setSize(s.w, s.h)) {
3815 flags |= eTraversalNeeded;
3816 }
3817 }
3818 if (what & layer_state_t::eAlphaChanged) {
3819 if (layer->setAlpha(s.alpha))
3820 flags |= eTraversalNeeded;
3821 }
3822 if (what & layer_state_t::eColorChanged) {
3823 if (layer->setColor(s.color))
3824 flags |= eTraversalNeeded;
3825 }
Peiyong Lind3788632018-09-18 16:01:31 -07003826 if (what & layer_state_t::eColorTransformChanged) {
3827 if (layer->setColorTransform(s.colorTransform)) {
3828 flags |= eTraversalNeeded;
3829 }
3830 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003831 if (what & layer_state_t::eBackgroundColorChanged) {
3832 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3833 flags |= eTraversalNeeded;
3834 }
3835 }
chaviw8b3871a2017-11-01 17:41:01 -07003836 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003837 // TODO: b/109894387
3838 //
3839 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3840 // rotation. To see the problem observe that if we have a square parent, and a child
3841 // of the same size, then we rotate the child 45 degrees around it's center, the child
3842 // must now be cropped to a non rectangular 8 sided region.
3843 //
3844 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3845 // private API, and the WindowManager only uses rotation in one case, which is on a top
3846 // level layer in which cropping is not an issue.
3847 //
3848 // However given that abuse of rotation matrices could lead to surfaces extending outside
3849 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3850 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3851 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003852 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003853 flags |= eTraversalNeeded;
3854 }
3855 if (what & layer_state_t::eTransparentRegionChanged) {
3856 if (layer->setTransparentRegionHint(s.transparentRegion))
3857 flags |= eTraversalNeeded;
3858 }
3859 if (what & layer_state_t::eFlagsChanged) {
3860 if (layer->setFlags(s.flags, s.mask))
3861 flags |= eTraversalNeeded;
3862 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003863 if (what & layer_state_t::eCropChanged_legacy) {
3864 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003865 flags |= eTraversalNeeded;
3866 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003867 if (what & layer_state_t::eCornerRadiusChanged) {
3868 if (layer->setCornerRadius(s.cornerRadius))
3869 flags |= eTraversalNeeded;
3870 }
chaviw8b3871a2017-11-01 17:41:01 -07003871 if (what & layer_state_t::eLayerStackChanged) {
3872 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3873 // We only allow setting layer stacks for top level layers,
3874 // everything else inherits layer stack from its parent.
3875 if (layer->hasParent()) {
3876 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3877 layer->getName().string());
3878 } else if (idx < 0) {
3879 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3880 "that also does not appear in the top level layer list. Something"
3881 " has gone wrong.", layer->getName().string());
3882 } else if (layer->setLayerStack(s.layerStack)) {
3883 mCurrentState.layersSortedByZ.removeAt(idx);
3884 mCurrentState.layersSortedByZ.add(layer);
3885 // we need traversal (state changed)
3886 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003887 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003888 }
3889 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003890 if (what & layer_state_t::eDeferTransaction_legacy) {
3891 if (s.barrierHandle_legacy != nullptr) {
3892 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3893 } else if (s.barrierGbp_legacy != nullptr) {
3894 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003895 if (authenticateSurfaceTextureLocked(gbp)) {
3896 const auto& otherLayer =
3897 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003898 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003899 } else {
3900 ALOGE("Attempt to defer transaction to to an"
3901 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003902 }
3903 }
chaviw8b3871a2017-11-01 17:41:01 -07003904 // We don't trigger a traversal here because if no other state is
3905 // changed, we don't want this to cause any more work
3906 }
3907 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003908 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003909 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003910 if (!hadParent) {
3911 mCurrentState.layersSortedByZ.remove(layer);
3912 }
chaviw8b3871a2017-11-01 17:41:01 -07003913 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003914 }
chaviw8b3871a2017-11-01 17:41:01 -07003915 }
3916 if (what & layer_state_t::eReparentChildren) {
3917 if (layer->reparentChildren(s.reparentHandle)) {
3918 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003919 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003920 }
chaviw8b3871a2017-11-01 17:41:01 -07003921 if (what & layer_state_t::eDetachChildren) {
3922 layer->detachChildren();
3923 }
3924 if (what & layer_state_t::eOverrideScalingModeChanged) {
3925 layer->setOverrideScalingMode(s.overrideScalingMode);
3926 // We don't trigger a traversal here because if no other state is
3927 // changed, we don't want this to cause any more work
3928 }
Marissa Wall61c58622018-07-18 10:12:20 -07003929 if (what & layer_state_t::eTransformChanged) {
3930 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3931 }
3932 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3933 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3934 flags |= eTraversalNeeded;
3935 }
3936 if (what & layer_state_t::eCropChanged) {
3937 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3938 }
Marissa Wall861616d2018-10-22 12:52:23 -07003939 if (what & layer_state_t::eFrameChanged) {
3940 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3941 }
Marissa Wall61c58622018-07-18 10:12:20 -07003942 if (what & layer_state_t::eAcquireFenceChanged) {
3943 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eDataspaceChanged) {
3946 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3947 }
3948 if (what & layer_state_t::eHdrMetadataChanged) {
3949 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3952 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eApiChanged) {
3955 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3956 }
3957 if (what & layer_state_t::eSidebandStreamChanged) {
3958 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3959 }
Robert Carr720e5062018-07-30 17:45:14 -07003960 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003961 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3962 layer->setInputInfo(s.inputInfo);
3963 flags |= eTraversalNeeded;
3964 } else {
3965 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3966 }
Robert Carr720e5062018-07-30 17:45:14 -07003967 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003968 if (what & layer_state_t::eMetadataChanged) {
3969 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3970 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003971 std::vector<sp<CallbackHandle>> callbackHandles;
3972 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3973 mTransactionCompletedThread.run();
3974 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3975 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3976 }
3977 }
Marissa Wall73411622019-01-25 10:45:41 -08003978
3979 if (what & layer_state_t::eBufferChanged) {
3980 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3981 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3982 s.buffer);
3983 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003984 if (what & layer_state_t::eCachedBufferChanged) {
3985 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003986 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3987 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003988 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3989 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003990 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3991 // Do not put anything that updates layer state or modifies flags after
3992 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003993 return flags;
3994}
3995
chaviw273171b2018-12-26 11:46:30 -08003996uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3997 uint32_t flags = 0;
3998 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3999 flags |= eTraversalNeeded;
4000 }
4001
chaviwa911b102019-02-14 10:18:33 -08004002 if (inputWindowCommands.syncInputWindows) {
4003 flags |= eTraversalNeeded;
4004 }
4005
Vishnu Nairec0ab382019-02-13 15:32:56 -08004006 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004007 return flags;
4008}
4009
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004010status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4011 uint32_t h, PixelFormat format, uint32_t flags,
4012 LayerMetadata metadata, sp<IBinder>* handle,
4013 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004014 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004015 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004016 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004018 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004019
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004020 status_t result = NO_ERROR;
4021
4022 sp<Layer> layer;
4023
Cody Northropbc755282017-03-31 12:00:08 -06004024 String8 uniqueName = getUniqueLayerName(name);
4025
Mathias Agopian3165cc22012-08-08 19:42:09 -07004026 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004027 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004028 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4029 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004031 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004032 case ISurfaceComposerClient::eFXSurfaceBufferState:
4033 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4034 break;
chaviw13fdc492017-06-27 12:40:18 -07004035 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004036 // check if buffer size is set for color layer.
4037 if (w > 0 || h > 0) {
4038 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4039 int(w), int(h));
4040 return BAD_VALUE;
4041 }
4042
chaviw13fdc492017-06-27 12:40:18 -07004043 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004044 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004045 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004046 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004047 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004048 // check if buffer size is set for container layer.
4049 if (w > 0 || h > 0) {
4050 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4051 int(w), int(h));
4052 return BAD_VALUE;
4053 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004054 result = createContainerLayer(client,
4055 uniqueName, w, h, flags,
4056 handle, &layer);
4057 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004058 default:
4059 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 break;
4061 }
4062
Dan Stoza7d89d062015-04-30 13:29:25 -07004063 if (result != NO_ERROR) {
4064 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004065 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004066
Chia-I Wuab0c3192017-08-01 11:29:00 -07004067 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4068 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004069 if (metadata.has(METADATA_WINDOW_TYPE)) {
4070 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4071 if (windowType == 441731) {
4072 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4073 layer->setPrimaryDisplayOnly();
4074 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004075 }
4076
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004077 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004078
Robert Carrb89ea9d2018-12-10 13:01:14 -08004079 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4080 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4081 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004082 if (result != NO_ERROR) {
4083 return result;
4084 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004085 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004086
4087 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004088 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089}
4090
Cody Northropbc755282017-03-31 12:00:08 -06004091String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4092{
4093 bool matchFound = true;
4094 uint32_t dupeCounter = 0;
4095
4096 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4097 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4098
Dan Stoza436ccf32018-06-21 12:10:12 -07004099 // Grab the state lock since we're accessing mCurrentState
4100 Mutex::Autolock lock(mStateLock);
4101
Cody Northropbc755282017-03-31 12:00:08 -06004102 // Loop over layers until we're sure there is no matching name
4103 while (matchFound) {
4104 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004105 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004106 if (layer->getName() == uniqueName) {
4107 matchFound = true;
4108 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4109 }
4110 });
4111 }
4112
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004113 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4114 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004115
4116 return uniqueName;
4117}
4118
Marissa Wallfd668622018-05-10 10:21:13 -07004119status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4120 uint32_t w, uint32_t h, uint32_t flags,
4121 PixelFormat& format, sp<IBinder>* handle,
4122 sp<IGraphicBufferProducer>* gbp,
4123 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004125 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004126 case PIXEL_FORMAT_TRANSPARENT:
4127 case PIXEL_FORMAT_TRANSLUCENT:
4128 format = PIXEL_FORMAT_RGBA_8888;
4129 break;
4130 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004131 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 break;
4133 }
4134
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004135 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004136 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004137 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004138 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004139 *handle = layer->getHandle();
4140 *gbp = layer->getProducer();
4141 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004142 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004143
Marissa Wallfd668622018-05-10 10:21:13 -07004144 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004145 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004146}
4147
Marissa Wall61c58622018-07-18 10:12:20 -07004148status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4149 uint32_t w, uint32_t h, uint32_t flags,
4150 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004151 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004152 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004153 *handle = layer->getHandle();
4154 *outLayer = layer;
4155
4156 return NO_ERROR;
4157}
4158
chaviw13fdc492017-06-27 12:40:18 -07004159status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004160 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004161 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004162{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004163 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004164 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004165 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004166}
4167
Robert Carr6b3f6c52018-08-13 13:05:17 -07004168status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4169 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4170 sp<IBinder>* handle, sp<Layer>* outLayer)
4171{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004172 *outLayer =
4173 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004174 *handle = (*outLayer)->getHandle();
4175 return NO_ERROR;
4176}
4177
4178
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004179void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004180 mLayersPendingRemoval.add(layer);
4181 mLayersRemoved = true;
4182 setTransactionFlags(eTransactionNeeded);
4183}
4184
Robert Carr695d5282018-12-18 15:27:58 -08004185void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004186{
Robert Carr2e102c92018-10-23 12:11:15 -07004187 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004188 // If a layer has a parent, we allow it to out-live it's handle
4189 // with the idea that the parent holds a reference and will eventually
4190 // be cleaned up. However no one cleans up the top-level so we do so
4191 // here.
4192 if (layer->getParent() == nullptr) {
4193 mCurrentState.layersSortedByZ.remove(layer);
4194 }
4195 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004196 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004197}
4198
Mathias Agopianb60314a2012-04-10 22:09:54 -07004199// ---------------------------------------------------------------------------
4200
Andy McFadden13a082e2012-08-24 10:16:42 -07004201void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004202 const auto display = getDefaultDisplayDeviceLocked();
4203 if (!display) return;
4204
4205 const sp<IBinder> token = display->getDisplayToken().promote();
4206 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004207
Jesse Hall01e29052013-02-19 16:13:35 -08004208 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004209 Vector<ComposerState> state;
4210 Vector<DisplayState> displays;
4211 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004212 d.what = DisplayState::eDisplayProjectionChanged |
4213 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004215 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004216 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004217 d.frame.makeInvalid();
4218 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004219 d.width = 0;
4220 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004221 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004222 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004223
Dominik Laskowskie9774092018-12-11 10:04:24 -08004224 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004225
Dominik Laskowski83b88212018-12-11 13:34:06 -08004226 const nsecs_t vsyncPeriod = getVsyncPeriod();
4227 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004228
Brian Andersond0010582017-03-07 13:20:31 -08004229 // Use phase of 0 since phase is not known.
4230 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004231 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004232 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004233}
4234
4235void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004236 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004237 postMessageAsync(
4238 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004239}
4240
Dominik Laskowskie9774092018-12-11 10:04:24 -08004241void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004242 if (display->isVirtual()) {
4243 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004244 return;
4245 }
4246
Dominik Laskowski075d3172018-05-24 15:50:06 -07004247 const auto displayId = display->getId();
4248 LOG_ALWAYS_FATAL_IF(!displayId);
4249
Dominik Laskowski34157762018-10-31 13:07:19 -07004250 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251
4252 int currentMode = display->getPowerMode();
4253 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004254 return;
4255 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004257 display->setPowerMode(mode);
4258
Lloyd Pique4dccc412018-01-22 17:21:36 -08004259 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004260 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004261 }
4262
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004263 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004264 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004266 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004267 mScheduler->onScreenAcquired(mAppConnectionHandle);
4268 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004269 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004270
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004271 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004272 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004273 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004274
4275 struct sched_param param = {0};
4276 param.sched_priority = 1;
4277 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4278 ALOGW("Couldn't set SCHED_FIFO on display on");
4279 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004280 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004281 // Turn off the display
4282 struct sched_param param = {0};
4283 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4284 ALOGW("Couldn't set SCHED_OTHER on display off");
4285 }
4286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004287 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004288 mScheduler->disableHardwareVsync(true);
4289 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004290 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004291
Dominik Laskowski075d3172018-05-24 15:50:06 -07004292 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004293 mVisibleRegionsDirty = true;
4294 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004295 } else if (mode == HWC_POWER_MODE_DOZE ||
4296 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004297 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004299 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004300 mScheduler->onScreenAcquired(mAppConnectionHandle);
4301 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004302 }
4303 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4304 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004305 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004306 mScheduler->disableHardwareVsync(true);
4307 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004308 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004309 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004310 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004311 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004312 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004313 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004314
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004315 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004316 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004317 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004318 // Update refresh rate stats.
4319 mRefreshRateStats->setPowerMode(mode);
4320 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004321 }
4322
Dominik Laskowski34157762018-10-31 13:07:19 -07004323 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004324}
4325
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004326void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004327 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328 const auto display = getDisplayDevice(displayToken);
4329 if (!display) {
4330 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4331 displayToken.get());
4332 } else if (display->isVirtual()) {
4333 ALOGW("Attempt to set power mode %d for virtual display", mode);
4334 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004335 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004336 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004337 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004338}
4339
4340// ---------------------------------------------------------------------------
4341
Dominik Laskowskic2867142019-01-21 11:33:38 -08004342status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4343 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004345
Mathias Agopianbd115332013-04-18 16:41:04 -07004346 IPCThreadState* ipc = IPCThreadState::self();
4347 const int pid = ipc->getCallingPid();
4348 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004349
Mathias Agopianbd115332013-04-18 16:41:04 -07004350 if ((uid != AID_SHELL) &&
4351 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004352 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4353 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004354 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004355 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004356 // (this would indicate SF is stuck, but we want to be able to
4357 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004358 status_t err = mStateLock.timedLock(s2ns(1));
4359 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004360 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361 StringAppendF(&result,
4362 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4363 "(no locks held)\n",
4364 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004365 }
4366
Dominik Laskowskic2867142019-01-21 11:33:38 -08004367 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004368
Dominik Laskowskic2867142019-01-21 11:33:38 -08004369 static const std::unordered_map<std::string, Dumper> dumpers = {
4370 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4371 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4372 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004373 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004374 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004375 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004376 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4377 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004378 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4379 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4380 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4381 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4382 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4383 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004384 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004385 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4386 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004387
Dominik Laskowskic2867142019-01-21 11:33:38 -08004388 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004389
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4391 (it->second)(args, asProto, result);
4392 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004393 if (asProto) {
4394 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4395 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4396 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004398 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004399 }
4400
Mathias Agopian9795c422009-08-26 16:36:26 -07004401 if (locked) {
4402 mStateLock.unlock();
4403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004404 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004405 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004406 return NO_ERROR;
4407}
4408
Dominik Laskowskic2867142019-01-21 11:33:38 -08004409void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004410 mCurrentState.traverseInZOrder(
4411 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004412}
4413
Dominik Laskowskic2867142019-01-21 11:33:38 -08004414void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004415 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004416
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417 if (args.size() > 1) {
4418 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004419 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004420 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004421 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004422 }
Robert Carr2047fae2016-11-28 14:09:09 -08004423 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004424 } else {
4425 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426 }
4427}
4428
Dominik Laskowskic2867142019-01-21 11:33:38 -08004429void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004430 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004431 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004432 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004433 }
Robert Carr2047fae2016-11-28 14:09:09 -08004434 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004435
Svetoslavd85084b2014-03-20 10:28:31 -07004436 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004437}
4438
Dominik Laskowskic2867142019-01-21 11:33:38 -08004439void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4440 mTimeStats->parseArgs(asProto, args, result);
4441}
4442
Jamie Gennis6547ff42013-07-16 20:12:42 -07004443// This should only be called from the main thread. Otherwise it would need
4444// the lock and should use mCurrentState rather than mDrawingState.
4445void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004446 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004447 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004448 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004449
4450 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4451}
4452
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004454 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004455
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004456 if (isLayerTripleBufferingDisabled())
4457 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4460 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4461 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4462 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4463 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4464 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004465 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004466}
4467
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004468void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004469 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004470 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004471 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004472 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004473
Ana Krulecba13ab32019-02-20 14:14:12 -08004474 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4475 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4476 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004477 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004478}
4479
Yiwei Zhang5434a782018-12-05 18:06:32 -08004480void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4481 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004482 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4483 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004484 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004485 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004487 }
David Sodman4a36e932017-11-07 14:29:47 -08004488 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004489 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004490 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4492 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004493}
4494
Dan Stozae77c7662016-05-13 11:37:28 -07004495void SurfaceFlinger::recordBufferingStats(const char* layerName,
4496 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004497 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4498 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004499 for (const auto& segment : history) {
4500 if (!segment.usedThirdBuffer) {
4501 stats.twoBufferTime += segment.totalTime;
4502 }
4503 if (segment.occupancyAverage < 1.0f) {
4504 stats.doubleBufferedTime += segment.totalTime;
4505 } else if (segment.occupancyAverage < 2.0f) {
4506 stats.tripleBufferedTime += segment.totalTime;
4507 }
4508 ++stats.numSegments;
4509 stats.totalTime += segment.totalTime;
4510 }
4511}
4512
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4514 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004515
4516 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4517 const size_t count = currentLayers.size();
4518 for (size_t i=0 ; i<count ; i++) {
4519 currentLayers[i]->dumpFrameEvents(result);
4520 }
4521}
4522
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004524 result.append("Buffering stats:\n");
4525 result.append(" [Layer name] <Active time> <Two buffer> "
4526 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004527 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004528 typedef std::tuple<std::string, float, float, float> BufferTuple;
4529 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004530 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004531 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004532 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004533 if (stats.numSegments == 0) {
4534 continue;
4535 }
4536 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4537 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4538 stats.totalTime;
4539 float doubleBufferRatio = static_cast<float>(
4540 stats.doubleBufferedTime) / stats.totalTime;
4541 float tripleBufferRatio = static_cast<float>(
4542 stats.tripleBufferedTime) / stats.totalTime;
4543 sorted.insert({activeTime, {name, twoBufferRatio,
4544 doubleBufferRatio, tripleBufferRatio}});
4545 }
4546 for (const auto& sortedPair : sorted) {
4547 float activeTime = sortedPair.first;
4548 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004549 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4550 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004551 }
4552 result.append("\n");
4553}
4554
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004556 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004557 const auto displayId = display->getId();
4558 if (!displayId) {
4559 continue;
4560 }
4561 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004562 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004563 continue;
4564 }
4565
Yiwei Zhang5434a782018-12-05 18:06:32 -08004566 StringAppendF(&result,
4567 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4568 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004569 uint8_t port;
4570 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004571 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004572 result.append("no identification data\n");
4573 continue;
4574 }
4575
4576 if (!isEdid(data)) {
4577 result.append("unknown identification data: ");
4578 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004579 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580 }
4581 result.append("\n");
4582 continue;
4583 }
4584
4585 const auto edid = parseEdid(data);
4586 if (!edid) {
4587 result.append("invalid EDID: ");
4588 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004589 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004590 }
4591 result.append("\n");
4592 continue;
4593 }
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004596 result.append(edid->displayName.data(), edid->displayName.length());
4597 result.append("\"\n");
4598 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004599}
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4602 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4603 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4604 StringAppendF(&result, "DisplayColorSetting: %s\n",
4605 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004606
4607 // TODO: print out if wide-color mode is active or not
4608
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004609 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004610 const auto displayId = display->getId();
4611 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004612 continue;
4613 }
4614
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004616 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004617 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004619 }
4620
Lloyd Pique32cbe282018-10-19 13:09:22 -07004621 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004622 StringAppendF(&result, " Current color mode: %s (%d)\n",
4623 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004624 }
4625 result.append("\n");
4626}
4627
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004628LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004629 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004630 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4631 const State& state = useDrawing ? mDrawingState : mCurrentState;
4632 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004633 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004634 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004635 });
4636
4637 return layersProto;
4638}
4639
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004640LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4641 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004642 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004643
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004644 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004645 resolution->set_w(displayDevice->getWidth());
4646 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004647
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004648 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004649 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004650
Lloyd Pique32cbe282018-10-19 13:09:22 -07004651 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4652 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4653 layersProto.set_global_transform(displayState.orientation);
4654
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004655 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004656 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004657 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004658 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004659 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004660 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004661 }
4662 });
4663
4664 return layersProto;
4665}
4666
Dominik Laskowskic2867142019-01-21 11:33:38 -08004667void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4668 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004669 Colorizer colorizer(colorize);
4670
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 // figure out if we're stuck somewhere
4672 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004673 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4675
4676 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004677 * Dump library configuration.
4678 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004679
4680 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004681 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004683 appendSfConfigString(result);
4684 appendUiConfigString(result);
4685 appendGuiConfigString(result);
4686 result.append("\n");
4687
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004688 result.append("\nDisplay identification data:\n");
4689 dumpDisplayIdentificationData(result);
4690
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004691 result.append("\nWide-Color information:\n");
4692 dumpWideColorInfo(result);
4693
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004694 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004695 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004697 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004698 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004699
Andy McFadden41d67d72014-04-25 16:58:34 -07004700 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004701 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004702 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004703 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004704 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004705
Dan Stozab90cf072015-03-05 11:05:59 -08004706 dumpStaticScreenStats(result);
4707 result.append("\n");
4708
Yiwei Zhang5434a782018-12-05 18:06:32 -08004709 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004710
Dan Stozae77c7662016-05-13 11:37:28 -07004711 dumpBufferingStats(result);
4712
Andy McFadden4803b742012-09-24 19:07:20 -07004713 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714 * Dump the visible layer list
4715 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4718 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4719 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004720 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004721
Chia-I Wu2f884132018-09-13 15:17:58 -07004722 {
4723 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4724 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004726 result.append("\n");
4727 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728
4729 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004730 * Dump Display state
4731 */
4732
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004734 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004735 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004736 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004737 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004738 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004739 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004740
4741 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004742 * Dump SurfaceFlinger global state
4743 */
4744
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004746 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004747 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004748
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004749 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004750
Dominik Laskowski075d3172018-05-24 15:50:06 -07004751 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004752 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4753 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004754 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4755 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004756 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result,
4758 " transaction-flags : %08x\n"
4759 " gpu_to_cpu_unsupported : %d\n",
4760 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004761
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004762 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004763 displayId && getHwComposer().isConnected(*displayId)) {
4764 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004765 StringAppendF(&result,
4766 " refresh-rate : %f fps\n"
4767 " x-dpi : %f\n"
4768 " y-dpi : %f\n",
4769 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4770 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004771 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004772
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004774
Dan Stozae22aec72016-08-01 13:20:59 -07004775 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004776 * Tracing state
4777 */
4778 mTracing.dump(result);
4779 result.append("\n");
4780
4781 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004782 * HWC layer minidump
4783 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004784 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004785 const auto displayId = display->getId();
4786 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004787 continue;
4788 }
4789
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004791 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004792 const sp<DisplayDevice> displayDevice = display;
4793 mCurrentState.traverseInZOrder(
4794 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004795 result.append("\n");
4796 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004797
4798 /*
4799 * Dump HWComposer state
4800 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004801 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004802 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004803 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004804 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004806 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004807
4808 /*
4809 * Dump gralloc state
4810 */
4811 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4812 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004813
4814 /*
4815 * Dump VrFlinger state if in use.
4816 */
4817 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4818 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004820 result.append("\n");
4821 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004822
4823 /**
4824 * Scheduler dump state.
4825 */
Ana Krulecc2870422019-01-29 19:00:58 -08004826 result.append("\nScheduler state:\n");
4827 result.append(mScheduler->doDump() + "\n");
4828 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004829}
4830
Dominik Laskowski075d3172018-05-24 15:50:06 -07004831const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004832 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004833 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004834 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004835 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004836 }
4837 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004838
Dominik Laskowski34157762018-10-31 13:07:19 -07004839 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004840 static const Vector<sp<Layer>> empty;
4841 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004842}
4843
Chia-I Wu28f320b2018-05-03 11:02:56 -07004844void SurfaceFlinger::updateColorMatrixLocked() {
4845 mat4 colorMatrix;
4846 if (mGlobalSaturationFactor != 1.0f) {
4847 // Rec.709 luma coefficients
4848 float3 luminance{0.213f, 0.715f, 0.072f};
4849 luminance *= 1.0f - mGlobalSaturationFactor;
4850 mat4 saturationMatrix = mat4(
4851 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4852 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4853 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4854 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4855 );
4856 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4857 } else {
4858 colorMatrix = mClientColorMatrix * mDaltonizer();
4859 }
4860
4861 if (mCurrentState.colorMatrix != colorMatrix) {
4862 mCurrentState.colorMatrix = colorMatrix;
4863 mCurrentState.colorMatrixChanged = true;
4864 setTransactionFlags(eTransactionNeeded);
4865 }
4866}
4867
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004868status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869#pragma clang diagnostic push
4870#pragma clang diagnostic error "-Wswitch-enum"
4871 switch (static_cast<ISurfaceComposerTag>(code)) {
4872 // These methods should at minimum make sure that the client requested
4873 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004874 case BOOT_FINISHED:
4875 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004876 case CREATE_DISPLAY:
4877 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004878 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004879 case GET_ACTIVE_COLOR_MODE:
4880 case GET_ANIMATION_FRAME_STATS:
4881 case GET_HDR_CAPABILITIES:
4882 case SET_ACTIVE_CONFIG:
4883 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004884 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004885 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004886 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004887 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4888 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004889 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4890 IPCThreadState* ipc = IPCThreadState::self();
4891 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4892 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004893 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004894 }
Robert Carr1db73f62016-12-21 12:58:51 -08004895 return OK;
4896 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004897 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004898 IPCThreadState* ipc = IPCThreadState::self();
4899 const int pid = ipc->getCallingPid();
4900 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4902 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004903 return PERMISSION_DENIED;
4904 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004906 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 // Used by apps to hook Choreographer to SurfaceFlinger.
4908 case CREATE_DISPLAY_EVENT_CONNECTION:
4909 // The following calls are currently used by clients that do not
4910 // request necessary permissions. However, they do not expose any secret
4911 // information, so it is OK to pass them.
4912 case AUTHENTICATE_SURFACE:
4913 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004914 case GET_PHYSICAL_DISPLAY_IDS:
4915 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004917 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004918 case GET_DISPLAY_CONFIGS:
4919 case GET_DISPLAY_STATS:
4920 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4921 // Calling setTransactionState is safe, because you need to have been
4922 // granted a reference to Client* and Handle* to do anything with it.
4923 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004924 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004925 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004926 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004927 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004928 case IS_WIDE_COLOR_DISPLAY:
4929 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004930 return OK;
4931 }
4932 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004933 case CAPTURE_SCREEN:
4934 case ADD_REGION_SAMPLING_LISTENER:
4935 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004937 IPCThreadState* ipc = IPCThreadState::self();
4938 const int pid = ipc->getCallingPid();
4939 const int uid = ipc->getCallingUid();
4940 if ((uid != AID_GRAPHICS) &&
4941 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4942 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4943 return PERMISSION_DENIED;
4944 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004945 return OK;
4946 }
4947 // The following codes are deprecated and should never be allowed to access SF.
4948 case CONNECT_DISPLAY_UNUSED:
4949 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4950 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4951 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004952 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004954
4955 // These codes are used for the IBinder protocol to either interrogate the recipient
4956 // side of the transaction for its canonical interface descriptor or to dump its state.
4957 // We let them pass by default.
4958 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4959 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4960 code == IBinder::SYSPROPS_TRANSACTION) {
4961 return OK;
4962 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004963 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004964 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004965 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4967 return OK;
4968 }
4969 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4970 return PERMISSION_DENIED;
4971#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004972}
4973
Ana Krulec13be8ad2018-08-21 02:43:56 +00004974status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4975 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004976 status_t credentialCheck = CheckTransactCodeCredentials(code);
4977 if (credentialCheck != OK) {
4978 return credentialCheck;
4979 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004980
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004981 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4982 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004983 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004984 IPCThreadState* ipc = IPCThreadState::self();
4985 const int uid = ipc->getCallingUid();
4986 if (CC_UNLIKELY(uid != AID_SYSTEM
4987 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004988 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004989 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004990 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004991 return PERMISSION_DENIED;
4992 }
4993 int n;
4994 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004995 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004996 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 return NO_ERROR;
4998 case 1002: // SHOW_UPDATES
4999 n = data.readInt32();
5000 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005001 invalidateHwcGeometry();
5002 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005005 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005006 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005008 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005009 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005010 setTransactionFlags(
5011 eTransactionNeeded|
5012 eDisplayTransactionNeeded|
5013 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005014 return NO_ERROR;
5015 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005016 case 1006:{ // send empty update
5017 signalRefresh();
5018 return NO_ERROR;
5019 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005020 case 1008: // toggle use of hw composer
5021 n = data.readInt32();
5022 mDebugDisableHWC = n ? 1 : 0;
5023 invalidateHwcGeometry();
5024 repaintEverything();
5025 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005026 case 1009: // toggle use of transform hint
5027 n = data.readInt32();
5028 mDebugDisableTransformHint = n ? 1 : 0;
5029 invalidateHwcGeometry();
5030 repaintEverything();
5031 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005032 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005033 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005034 reply->writeInt32(0);
5035 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005036 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005037 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 return NO_ERROR;
5039 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005040 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005041 if (!display) {
5042 return NAME_NOT_FOUND;
5043 }
5044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005045 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005046 return NO_ERROR;
5047 }
5048 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005049 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005050 // daltonize
5051 n = data.readInt32();
5052 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005053 case 1:
5054 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5055 break;
5056 case 2:
5057 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5058 break;
5059 case 3:
5060 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5061 break;
5062 default:
5063 mDaltonizer.setType(ColorBlindnessType::None);
5064 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005065 }
5066 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005067 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005068 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005069 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005070 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005071
5072 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005073 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005074 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005075 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005076 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005077 // apply a color matrix
5078 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005079 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005080 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005081 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005082 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005084 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005085 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005086 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005087 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005088 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005089
5090 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5091 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005092 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005093 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5094 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5095 }
5096
Chia-I Wu28f320b2018-05-03 11:02:56 -07005097 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 return NO_ERROR;
5099 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005100 // This is an experimental interface
5101 // Needs to be shifted to proper binder interface when we productize
5102 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005103 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005104 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005105 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005106 return NO_ERROR;
5107 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005108 case 1017: {
5109 n = data.readInt32();
5110 mForceFullDamage = static_cast<bool>(n);
5111 return NO_ERROR;
5112 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005113 case 1018: { // Modify Choreographer's phase offset
5114 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005115 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005116 return NO_ERROR;
5117 }
5118 case 1019: { // Modify SurfaceFlinger's phase offset
5119 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005120 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005121 return NO_ERROR;
5122 }
Irvel468051e2016-06-13 16:44:44 -07005123 case 1020: { // Layer updates interceptor
5124 n = data.readInt32();
5125 if (n) {
5126 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005127 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005128 }
5129 else{
5130 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005131 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005132 }
5133 return NO_ERROR;
5134 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005135 case 1021: { // Disable HWC virtual displays
5136 n = data.readInt32();
5137 mUseHwcVirtualDisplays = !n;
5138 return NO_ERROR;
5139 }
Romain Guy0147a172017-06-01 13:53:56 -07005140 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005141 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005142 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005143
Chia-I Wu28f320b2018-05-03 11:02:56 -07005144 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005145 return NO_ERROR;
5146 }
Romain Guy54f154a2017-10-24 21:40:32 +01005147 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005148 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005149 invalidateHwcGeometry();
5150 repaintEverything();
5151 return NO_ERROR;
5152 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005153 // Deprecate, use 1030 to check whether the device is color managed.
5154 case 1024: {
5155 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005156 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005157 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005158 n = data.readInt32();
5159 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005160 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005161 mTracing.enable();
5162 doTracing("tracing.enable");
5163 reply->writeInt32(NO_ERROR);
5164 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005165 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005166 status_t err = mTracing.disable();
5167 reply->writeInt32(err);
5168 }
5169 return NO_ERROR;
5170 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005171 case 1026: { // Get layer tracing status
5172 reply->writeBool(mTracing.isEnabled());
5173 return NO_ERROR;
5174 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005175 // Is a DisplayColorSetting supported?
5176 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005177 const auto display = getDefaultDisplayDevice();
5178 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005179 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005180 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005181
5182 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5183 switch (setting) {
5184 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005185 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005186 break;
5187 case DisplayColorSetting::UNMANAGED:
5188 reply->writeBool(true);
5189 break;
5190 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005191 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005192 break;
5193 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005194 reply->writeBool(
5195 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005196 break;
5197 }
5198 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005199 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005200 // Is VrFlinger active?
5201 case 1028: {
5202 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005203 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005204 return NO_ERROR;
5205 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005206 // Is device color managed?
5207 case 1030: {
5208 reply->writeBool(useColorManagement);
5209 return NO_ERROR;
5210 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005211 // Override default composition data space
5212 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5213 // && adb shell stop zygote && adb shell start zygote
5214 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5215 // adb shell stop zygote && adb shell start zygote
5216 case 1031: {
5217 Mutex::Autolock _l(mStateLock);
5218 n = data.readInt32();
5219 if (n) {
5220 n = data.readInt32();
5221 if (n) {
5222 Dataspace dataspace = static_cast<Dataspace>(n);
5223 if (!validateCompositionDataspace(dataspace)) {
5224 return BAD_VALUE;
5225 }
5226 mDefaultCompositionDataspace = dataspace;
5227 }
5228 n = data.readInt32();
5229 if (n) {
5230 Dataspace dataspace = static_cast<Dataspace>(n);
5231 if (!validateCompositionDataspace(dataspace)) {
5232 return BAD_VALUE;
5233 }
5234 mWideColorGamutCompositionDataspace = dataspace;
5235 }
5236 } else {
5237 // restore composition data space.
5238 mDefaultCompositionDataspace = defaultCompositionDataspace;
5239 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5240 }
5241 return NO_ERROR;
5242 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005243 }
5244 }
5245 return err;
5246}
5247
Steven Thomas6d8110b2017-08-31 18:24:21 -07005248void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005249 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005250 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005251}
5252
Ana Krulec7d1d6832018-12-27 11:10:09 -08005253void SurfaceFlinger::repaintEverythingForHWC() {
5254 mRepaintEverything = true;
5255 mEventQueue->invalidateForHWC();
5256}
5257
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005258// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5259class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005260public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005261 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5262 ~WindowDisconnector() {
5263 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005264 }
5265
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005266private:
5267 ANativeWindow* mWindow;
5268 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005269};
5270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005271status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005272 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5273 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005274 uint32_t reqWidth, uint32_t reqHeight,
5275 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005276 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005277 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005278
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005279 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005280
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005281 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5282
Chia-I Wu20261cb2018-08-23 12:55:44 -07005283 sp<DisplayDevice> display;
5284 {
5285 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005286
Chia-I Wu20261cb2018-08-23 12:55:44 -07005287 display = getDisplayDeviceLocked(displayToken);
5288 if (!display) return BAD_VALUE;
5289
Chia-I Wucb023152018-08-28 12:57:23 -07005290 // set the requested width/height to the logical display viewport size
5291 // by default
5292 if (reqWidth == 0 || reqHeight == 0) {
5293 reqWidth = uint32_t(display->getViewport().width());
5294 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005295 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005296 }
5297
Peiyong Lin0e003c92018-09-17 11:09:51 -07005298 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5299 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005300
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005301 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5302 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005303 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5304 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005305}
5306
5307status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005308 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5309 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005310 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005311 ATRACE_CALL();
5312
5313 class LayerRenderArea : public RenderArea {
5314 public:
Robert Carr578038f2018-03-09 12:25:24 -08005315 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005316 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5317 bool childrenOnly)
5318 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005319 mLayer(layer),
5320 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005321 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005322 mFlinger(flinger),
5323 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005324 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005325 Rect getBounds() const override {
5326 const Layer::State& layerState(mLayer->getDrawingState());
5327 return mLayer->getBufferSize(layerState);
5328 }
Marissa Wall61c58622018-07-18 10:12:20 -07005329 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005330 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005331 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005332 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005333 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005334 }
chaviwa76b2712017-09-20 12:02:26 -07005335 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005336 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005337 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005338 Rect getSourceCrop() const override {
5339 if (mCrop.isEmpty()) {
5340 return getBounds();
5341 } else {
5342 return mCrop;
5343 }
5344 }
Robert Carr578038f2018-03-09 12:25:24 -08005345 class ReparentForDrawing {
5346 public:
5347 const sp<Layer>& oldParent;
5348 const sp<Layer>& newParent;
5349
Vishnu Nair4351ad52019-02-11 14:13:02 -08005350 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5351 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005352 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005353 // Compute and cache the bounds for the new parent layer.
5354 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005355 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005356 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005357 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005358 };
5359
5360 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005361 const Rect sourceCrop = getSourceCrop();
5362 // no need to check rotation because there is none
5363 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5364 sourceCrop.height() != getReqHeight();
5365
Robert Carr578038f2018-03-09 12:25:24 -08005366 if (!mChildrenOnly) {
5367 mTransform = mLayer->getTransform().inverse();
5368 drawLayers();
5369 } else {
5370 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005371 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005372 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5373 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005374
Vishnu Nair4351ad52019-02-11 14:13:02 -08005375 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005376 drawLayers();
5377 }
5378 }
chaviwa76b2712017-09-20 12:02:26 -07005379
chaviwa76b2712017-09-20 12:02:26 -07005380 private:
chaviw7206d492017-11-10 16:16:12 -08005381 const sp<Layer> mLayer;
5382 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005383
5384 // In the "childrenOnly" case we reparent the children to a screenshot
5385 // layer which has no properties set and which does not draw.
5386 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005387 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005388 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005389
5390 SurfaceFlinger* mFlinger;
5391 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005392 };
5393
5394 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5395 auto parent = layerHandle->owner.promote();
5396
Robert Carr2e102c92018-10-23 12:11:15 -07005397 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005398 ALOGE("captureLayers called with a removed parent");
5399 return NAME_NOT_FOUND;
5400 }
5401
Robert Carr578038f2018-03-09 12:25:24 -08005402 const int uid = IPCThreadState::self()->getCallingUid();
5403 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005404 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005405 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5406 return PERMISSION_DENIED;
5407 }
5408
chaviw7206d492017-11-10 16:16:12 -08005409 Rect crop(sourceCrop);
5410 if (sourceCrop.width() <= 0) {
5411 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005412 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005413 }
5414
5415 if (sourceCrop.height() <= 0) {
5416 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005417 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005418 }
5419
5420 int32_t reqWidth = crop.width() * frameScale;
5421 int32_t reqHeight = crop.height() * frameScale;
5422
Chia-I Wu20261cb2018-08-23 12:55:44 -07005423 // really small crop or frameScale
5424 if (reqWidth <= 0) {
5425 reqWidth = 1;
5426 }
5427 if (reqHeight <= 0) {
5428 reqHeight = 1;
5429 }
5430
Peiyong Lin0e003c92018-09-17 11:09:51 -07005431 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005432
Robert Carr578038f2018-03-09 12:25:24 -08005433 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005434 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5435 if (!layer->isVisible()) {
5436 return;
Robert Carr578038f2018-03-09 12:25:24 -08005437 } else if (childrenOnly && layer == parent.get()) {
5438 return;
chaviwa76b2712017-09-20 12:02:26 -07005439 }
5440 visitor(layer);
5441 });
5442 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005443 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005444}
5445
5446status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5447 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005448 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005449 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005450 bool useIdentityTransform) {
5451 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005452
Peiyong Lin0e003c92018-09-17 11:09:51 -07005453 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005454 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5455 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005456 *outBuffer =
5457 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5458 static_cast<android_pixel_format>(reqPixelFormat), 1,
5459 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005460
5461 // This mutex protects syncFd and captureResult for communication of the return values from the
5462 // main thread back to this Binder thread
5463 std::mutex captureMutex;
5464 std::condition_variable captureCondition;
5465 std::unique_lock<std::mutex> captureLock(captureMutex);
5466 int syncFd = -1;
5467 std::optional<status_t> captureResult;
5468
Robert Carr03480e22018-01-04 16:02:06 -08005469 const int uid = IPCThreadState::self()->getCallingUid();
5470 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5471
Dominik Laskowski8c001672018-05-30 16:52:06 -07005472 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473 // If there is a refresh pending, bug out early and tell the binder thread to try again
5474 // after the refresh.
5475 if (mRefreshPending) {
5476 ATRACE_NAME("Skipping screenshot for now");
5477 std::unique_lock<std::mutex> captureLock(captureMutex);
5478 captureResult = std::make_optional<status_t>(EAGAIN);
5479 captureCondition.notify_one();
5480 return;
5481 }
5482
5483 status_t result = NO_ERROR;
5484 int fd = -1;
5485 {
5486 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005487 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005488 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5489 useIdentityTransform, forSystem, &fd);
5490 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005491 }
5492
5493 {
5494 std::unique_lock<std::mutex> captureLock(captureMutex);
5495 syncFd = fd;
5496 captureResult = std::make_optional<status_t>(result);
5497 captureCondition.notify_one();
5498 }
5499 });
5500
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005501 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005502 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005503 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504 while (*captureResult == EAGAIN) {
5505 captureResult.reset();
5506 result = postMessageAsync(message);
5507 if (result != NO_ERROR) {
5508 return result;
5509 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005510 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005511 }
5512 result = *captureResult;
5513 }
5514
5515 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005516 sync_wait(syncFd, -1);
5517 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005518 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005519
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005520 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005521}
5522
chaviwa76b2712017-09-20 12:02:26 -07005523void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005524 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005525 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5526 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005527 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005528
chaviwa76b2712017-09-20 12:02:26 -07005529 const auto reqWidth = renderArea.getReqWidth();
5530 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005531 const auto sourceCrop = renderArea.getSourceCrop();
5532 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005533
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005534 renderengine::DisplaySettings clientCompositionDisplay;
5535 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005536
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005537 // assume that bounds are never offset, and that they are the same as the
5538 // buffer bounds.
5539 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5540 ui::Transform transform = renderArea.getTransform();
5541 mat4 m;
5542 m[0][0] = transform[0][0];
5543 m[0][1] = transform[0][1];
5544 m[0][3] = transform[0][2];
5545 m[1][0] = transform[1][0];
5546 m[1][1] = transform[1][1];
5547 m[1][3] = transform[1][2];
5548 m[3][0] = transform[2][0];
5549 m[3][1] = transform[2][1];
5550 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005551
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005552 clientCompositionDisplay.globalTransform = m;
5553 mat4 rotMatrix;
5554 // Displacement for repositioning the clipping rectangle after rotating it
5555 // with the rotation hint.
5556 int displacementX = 0;
5557 int displacementY = 0;
5558 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5559 switch (rotation) {
5560 case ui::Transform::ROT_90:
5561 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5562 displacementX = reqWidth;
5563 break;
5564 case ui::Transform::ROT_180:
5565 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5566 displacementX = reqWidth;
5567 displacementY = reqHeight;
5568 break;
5569 case ui::Transform::ROT_270:
5570 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5571 displacementY = reqHeight;
5572 break;
5573 default:
5574 break;
5575 }
5576 // We need to transform the clipping window into the right spot.
5577 // First, rotate the clipping rectangle by the rotation hint to get the
5578 // right orientation
5579 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5580 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5581 const vec4 rotClipTL = rotMatrix * clipTL;
5582 const vec4 rotClipBR = rotMatrix * clipBR;
5583 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5584 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5585 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5586 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5587
5588 // Now reposition the clipping rectangle with the displacement vector
5589 // computed above.
5590 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5591
5592 clientCompositionDisplay.clip =
5593 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5594 newClipRight + displacementX, newClipBottom + displacementY);
5595
5596 // We need to perform the same transformation in layer space, so propagate
5597 // it to the global transform.
5598 mat4 clipTransform = displacementMat * rotMatrix;
5599 clientCompositionDisplay.globalTransform *= clipTransform;
5600 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5601 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005602
chaviw50da5042018-04-09 13:49:37 -07005603 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005604
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005605 renderengine::LayerSettings fillLayer;
5606 fillLayer.source.buffer.buffer = nullptr;
5607 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5608 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5609 fillLayer.alpha = half(alpha);
5610 clientCompositionLayers.push_back(fillLayer);
5611
5612 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005613 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005614 renderengine::LayerSettings layerSettings;
5615 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5616 layerSettings);
5617 if (prepared) {
5618 clientCompositionLayers.push_back(layerSettings);
5619 }
chaviwa76b2712017-09-20 12:02:26 -07005620 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005621
5622 clientCompositionDisplay.clearRegion = clearRegion;
5623 base::unique_fd drawFence;
5624 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5625 &drawFence);
5626
5627 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005628}
5629
chaviwa76b2712017-09-20 12:02:26 -07005630status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5631 TraverseLayersFunction traverseLayers,
5632 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005633 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005634 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005635 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005636 ATRACE_CALL();
5637
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005638 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005639
5640 traverseLayers([&](Layer* layer) {
5641 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5642 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005643
Robert Carr03480e22018-01-04 16:02:06 -08005644 // We allow the system server to take screenshots of secure layers for
5645 // use in situations like the Screen-rotation animation and place
5646 // the impetus on WindowManager to not persist them.
5647 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005648 ALOGW("FB is protected: PERMISSION_DENIED");
5649 return PERMISSION_DENIED;
5650 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005651 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005652 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005653}
5654
chaviw5f21a5e2019-02-14 10:00:34 -08005655void SurfaceFlinger::setInputWindowsFinished() {}
5656
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005657// ---------------------------------------------------------------------------
5658
Dan Stoza412903f2017-04-27 13:42:17 -07005659void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5660 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005661}
5662
Dan Stoza412903f2017-04-27 13:42:17 -07005663void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5664 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005665}
5666
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005667void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005668 const LayerVector::Visitor& visitor) {
5669 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005670 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005671 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005672 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005673 continue;
5674 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005675 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005676 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005677 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005678 return;
5679 }
chaviwa76b2712017-09-20 12:02:26 -07005680 if (!layer->isVisible()) {
5681 return;
5682 }
5683 visitor(layer);
5684 });
5685 }
5686}
5687
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005688}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005689
Lloyd Pique074e8122018-07-26 12:57:23 -07005690
Mathias Agopian3f844832013-08-07 21:24:32 -07005691#if defined(__gl_h_)
5692#error "don't include gl/gl.h in this file"
5693#endif
5694
5695#if defined(__gl2_h_)
5696#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005697#endif