blob: adc4a6164e137543af19e1b0edb6f6e7275ecdaf [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 {
Alec Mourife3dc942019-02-12 14:19:18 -08001000 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001001 // we may be in the process of changing the active state
1002 if (mWaitForNextInvalidate) {
1003 mWaitForNextInvalidate = false;
1004
1005 repaintEverythingForHWC();
1006 // We do not want to give another frame to HWC while we are transitioning.
1007 return true;
1008 }
1009
1010 if (mCheckPendingFence) {
1011 if (mPreviousPresentFence != Fence::NO_FENCE &&
1012 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1013 // fence has not signaled yet. wait for the next invalidate
1014 repaintEverythingForHWC();
1015 return true;
1016 }
1017
1018 // We received the present fence from the HWC, so we assume it successfully updated
1019 // the config, hence we update SF.
1020 mCheckPendingFence = false;
1021 setActiveConfigInternal();
1022 }
1023
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024 // Store the local variable to release the lock.
1025 ActiveConfigInfo desiredActiveConfig;
1026 {
1027 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (!mDesiredActiveConfigChanged) {
1029 return false;
1030 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 desiredActiveConfig = mDesiredActiveConfig;
1032 }
1033
1034 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1036 // display is not valid or we are already in the requested mode
1037 // on both cases there is nothing left to do
1038 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1039 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1040 mDesiredActiveConfigChanged = false;
1041 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1042 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044
1045 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1046 mUpcomingActiveConfig = desiredActiveConfig;
1047 const auto displayId = display->getId();
1048 LOG_ALWAYS_FATAL_IF(!displayId);
1049
1050 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1051 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1052
1053 // we need to submit an empty frame to HWC to start the process
1054 mWaitForNextInvalidate = true;
1055 mCheckPendingFence = true;
1056
1057 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001058}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1061 Vector<ColorMode>* outColorModes) {
1062 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001063 return BAD_VALUE;
1064 }
1065
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001068 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1069
1070 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1071 if (!displayId) {
1072 return NAME_NOT_FOUND;
1073 }
1074
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001076 }
Michael Wright28f24d02016-07-12 13:30:53 -07001077 outColorModes->clear();
1078 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1079
1080 return NO_ERROR;
1081}
1082
Daniel Solomon42d04562019-01-20 21:03:19 -08001083status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1084 ui::DisplayPrimaries &primaries) {
1085 if (!displayToken) {
1086 return BAD_VALUE;
1087 }
1088
1089 // Currently we only support this API for a single internal display.
1090 if (getInternalDisplayToken() != displayToken) {
1091 return BAD_VALUE;
1092 }
1093
1094 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1099 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001100 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001102 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001103}
1104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 Vector<ColorMode> modes;
1108 getDisplayColorModes(displayToken, &modes);
1109 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1110 if (mode < ColorMode::NATIVE || !exists) {
1111 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1112 decodeColorMode(mode).c_str(), mode, displayToken.get());
1113 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 const auto display = getDisplayDevice(displayToken);
1116 if (!display) {
1117 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1118 decodeColorMode(mode).c_str(), mode, displayToken.get());
1119 } else if (display->isVirtual()) {
1120 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1121 decodeColorMode(mode).c_str(), mode);
1122 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001123 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1124 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125 }
1126 }));
1127
Michael Wright28f24d02016-07-12 13:30:53 -07001128 return NO_ERROR;
1129}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001130
Svetoslavd85084b2014-03-20 10:28:31 -07001131status_t SurfaceFlinger::clearAnimationFrameStats() {
1132 Mutex::Autolock _l(mStateLock);
1133 mAnimFrameTracker.clearStats();
1134 return NO_ERROR;
1135}
1136
1137status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1138 Mutex::Autolock _l(mStateLock);
1139 mAnimFrameTracker.getStats(outStats);
1140 return NO_ERROR;
1141}
1142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1144 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001145 Mutex::Autolock _l(mStateLock);
1146
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 const auto display = getDisplayDeviceLocked(displayToken);
1148 if (!display) {
1149 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001150 return BAD_VALUE;
1151 }
1152
Peiyong Linfb069302018-04-25 14:34:31 -07001153 // At this point the DisplayDeivce should already be set up,
1154 // meaning the luminance information is already queried from
1155 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001157 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1158 capabilities.getDesiredMaxLuminance(),
1159 capabilities.getDesiredMaxAverageLuminance(),
1160 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001161
1162 return NO_ERROR;
1163}
1164
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001165status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1166 ui::PixelFormat* outFormat,
1167 ui::Dataspace* outDataspace,
1168 uint8_t* outComponentMask) const {
1169 if (!outFormat || !outDataspace || !outComponentMask) {
1170 return BAD_VALUE;
1171 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001172 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001173 if (!display || !display->getId()) {
1174 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1175 return BAD_VALUE;
1176 }
1177 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1178 outDataspace, outComponentMask);
1179}
1180
Kevin DuBois74e53772018-11-19 10:52:38 -08001181status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1182 bool enable, uint8_t componentMask,
1183 uint64_t maxFrames) const {
1184 const auto display = getDisplayDevice(displayToken);
1185 if (!display || !display->getId()) {
1186 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1187 return BAD_VALUE;
1188 }
1189
1190 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1191 componentMask, maxFrames);
1192}
1193
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001194status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1195 uint64_t maxFrames, uint64_t timestamp,
1196 DisplayedFrameStats* outStats) const {
1197 const auto display = getDisplayDevice(displayToken);
1198 if (!display || !display->getId()) {
1199 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1200 return BAD_VALUE;
1201 }
1202
1203 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1204 outStats);
1205}
1206
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001207status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1208 if (!outSupported) {
1209 return BAD_VALUE;
1210 }
1211 *outSupported = getRenderEngine().supportsProtectedContent();
1212 return NO_ERROR;
1213}
1214
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001215status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1216 bool* outIsWideColorDisplay) const {
1217 if (!displayToken || !outIsWideColorDisplay) {
1218 return BAD_VALUE;
1219 }
1220 Mutex::Autolock _l(mStateLock);
1221 const auto display = getDisplayDeviceLocked(displayToken);
1222 if (!display) {
1223 return BAD_VALUE;
1224 }
1225 *outIsWideColorDisplay = display->hasWideColorGamut();
1226 return NO_ERROR;
1227}
1228
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001230 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 if (mInjectVSyncs == enable) {
1234 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236
Ana Krulecc2870422019-01-29 19:00:58 -08001237 auto resyncCallback =
1238 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001239
Ana Krulec98b5b242018-08-10 15:03:23 -07001240 // TODO(akrulec): Part of the Injector should be refactored, so that it
1241 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 if (enable) {
1243 ALOGV("VSync Injections enabled");
1244 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001245 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001246 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001247 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001248 impl::EventThread::InterceptVSyncsCallback(),
1249 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001251 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 } else {
1253 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001254 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1255 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 }
1257
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001259 }));
1260
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001261 return NO_ERROR;
1262}
1263
1264status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 Mutex::Autolock _l(mStateLock);
1266
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001267 if (!mInjectVSyncs) {
1268 ALOGE("VSync Injections not enabled");
1269 return BAD_VALUE;
1270 }
1271 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1272 ALOGV("Injecting VSync inside SurfaceFlinger");
1273 mVSyncInjector->onInjectSyncEvent(when);
1274 }
1275 return NO_ERROR;
1276}
1277
Lloyd Pique755e3192018-01-31 16:46:15 -08001278status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1279 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001280 // Try to acquire a lock for 1s, fail gracefully
1281 const status_t err = mStateLock.timedLock(s2ns(1));
1282 const bool locked = (err == NO_ERROR);
1283 if (!locked) {
1284 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1285 return TIMED_OUT;
1286 }
1287
1288 outLayers->clear();
1289 mCurrentState.traverseInZOrder([&](Layer* layer) {
1290 outLayers->push_back(layer->getLayerDebugInfo());
1291 });
1292
1293 mStateLock.unlock();
1294 return NO_ERROR;
1295}
1296
Peiyong Linc6780972018-10-28 15:24:08 -07001297status_t SurfaceFlinger::getCompositionPreference(
1298 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1299 Dataspace* outWideColorGamutDataspace,
1300 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001301 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001302 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001303 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001304 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001305 return NO_ERROR;
1306}
1307
Dan Stoza84ab9372018-12-17 15:27:57 -08001308status_t SurfaceFlinger::addRegionSamplingListener(
1309 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1310 const sp<IRegionSamplingListener>& /*listener*/) {
1311 return NO_ERROR;
1312}
1313
1314status_t SurfaceFlinger::removeRegionSamplingListener(
1315 const sp<IRegionSamplingListener>& /*listener*/) {
1316 return NO_ERROR;
1317}
1318
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001319// ----------------------------------------------------------------------------
1320
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001321sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1322 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001323 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001324 Mutex::Autolock lock(mStateLock);
1325 return getVsyncPeriod();
1326 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001327
Ana Krulecc2870422019-01-29 19:00:58 -08001328 const auto& handle =
1329 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001330
Ana Krulecc2870422019-01-29 19:00:58 -08001331 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001332}
1333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001335
1336void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001337 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338}
1339
1340void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001341 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001342}
1343
1344void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001345 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001346}
1347
1348void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001349 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001350 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351}
1352
1353status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001354 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001355 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001356}
1357
1358status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001359 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001360 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001361 if (res == NO_ERROR) {
1362 msg->wait();
1363 }
1364 return res;
1365}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001366
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001367void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001368 do {
1369 waitForEvent();
1370 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001371}
1372
Dominik Laskowski83b88212018-12-11 13:34:06 -08001373nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001374 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001375 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1376 return 0;
1377 }
1378
1379 const auto config = getHwComposer().getActiveConfig(*displayId);
1380 return config ? config->getVsyncPeriod() : 0;
1381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1384 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001385 ATRACE_NAME("SF onVsync");
1386
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
1391 }
1392
Dominik Laskowski075d3172018-05-24 15:50:06 -07001393 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001394 return;
1395 }
1396
Dominik Laskowski075d3172018-05-24 15:50:06 -07001397 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 // For now, we don't do anything with external display vsyncs.
1399 return;
1400 }
1401
Ana Krulecc2870422019-01-29 19:00:58 -08001402 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001403}
1404
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001406 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1407 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408}
1409
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001410void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1411 mPhaseOffsets->setRefreshRateType(refreshRate);
1412
1413 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1414 mVsyncModulator.setPhaseOffsets(early, gl, late);
1415
1416 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001417 return;
1418 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001419
Ana Krulec7d1d6832018-12-27 11:10:09 -08001420 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1421 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1422 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1423 // refresh cycle.
1424
1425 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001426 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001427 if (currentVsyncPeriod == 0) {
1428 return;
1429 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001430
Ana Krulec7d1d6832018-12-27 11:10:09 -08001431 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1432 // floating numbers.
1433 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001434 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1435 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001436 if (std::abs(currentFps - newFps) <= 1) {
1437 return;
1438 }
1439
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001440 const auto displayId = getInternalDisplayIdLocked();
1441 LOG_ALWAYS_FATAL_IF(!displayId);
1442
1443 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001444 for (int i = 0; i < configs.size(); i++) {
1445 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1446 if (vsyncPeriod == 0) {
1447 continue;
1448 }
1449 const float fps = 1e9 / vsyncPeriod;
1450 // TODO(b/113612090): There should be a better way at determining which config
1451 // has the right refresh rate.
1452 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001453 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454 }
1455 }
1456}
1457
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001458void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001459 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001461 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462
Lloyd Piqueba04e622017-12-14 17:11:26 -08001463 // Ignore events that do not have the right sequenceId.
1464 if (sequenceId != getBE().mComposerSequenceId) {
1465 return;
1466 }
1467
Steven Thomasb02664d2017-07-26 18:48:28 -07001468 // Only lock if we're not on the main thread. This function is normally
1469 // called on a hwbinder thread, but for the primary display it's called on
1470 // the main thread with the state lock already held, so don't attempt to
1471 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001472 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001473
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001474 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001475
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001476 if (std::this_thread::get_id() == mMainThreadId) {
1477 // Process all pending hot plug events immediately if we are on the main thread.
1478 processDisplayHotplugEventsLocked();
1479 }
1480
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001482}
1483
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001484void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001485 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001486 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001489 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001490}
1491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001492void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001493 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001494 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001495 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 getHwComposer().setVsyncEnabled(*displayId,
1497 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1498 }
Mathias Agopian86303202012-07-24 22:46:10 -07001499}
1500
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001502void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001503 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504 // Clear the drawing state so that the logic inside of
1505 // handleTransactionLocked will fire. It will determine the delta between
1506 // mCurrentState and mDrawingState and re-apply all changes when we make the
1507 // transition.
1508 mDrawingState.displays.clear();
1509 mDisplays.clear();
1510}
1511
Steven Thomas050b2c82017-03-06 11:45:16 -08001512void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001513 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001514 if (!mVrFlinger)
1515 return;
1516 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001518 return;
1519 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520
Lloyd Pique441d5042018-10-18 16:49:51 -07001521 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 ALOGE("Vr flinger is only supported for remote hardware composer"
1523 " service connections. Ignoring request to transition to vr"
1524 " flinger.");
1525 mVrFlingerRequestsDisplay = false;
1526 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001527 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001530
Steven Thomas0123ac62018-07-12 11:32:34 -07001531 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001532 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001533
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001534 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001535
1536 // Clear out all the output layers from the composition engine for all
1537 // displays before destroying the hardware composer interface. This ensures
1538 // any HWC layers are destroyed through that interface before it becomes
1539 // invalid.
1540 for (const auto& [token, displayDevice] : mDisplays) {
1541 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1542 compositionengine::Output::OutputLayers());
1543 }
1544
Steven Thomas0123ac62018-07-12 11:32:34 -07001545 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1546 // called below. Clear the reference now so we don't accidentally use it
1547 // later.
1548 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001555 // Delete the current instance before creating the new one
1556 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1557 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1558 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1559 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560
Lloyd Pique441d5042018-10-18 16:49:51 -07001561 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001562 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001563
1564 if (vrFlingerRequestsDisplay) {
1565 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567
1568 mVisibleRegionsDirty = true;
1569 invalidateHwcGeometry();
1570
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001571 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001572 display = getDefaultDisplayDeviceLocked();
1573 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001574 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001575
Steven Thomasb02664d2017-07-26 18:48:28 -07001576 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577 const nsecs_t vsyncPeriod = getVsyncPeriod();
1578 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001579
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001580 // The present fences returned from vr_hwc are not an accurate
1581 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001582 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 // Use phase of 0 since phase is not known.
1585 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001586 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001587 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001588
Ana Krulecc2870422019-01-29 19:00:58 -08001589 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001591 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593}
1594
Mathias Agopian4fec8732012-06-29 14:12:52 -07001595void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001596 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001597 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001598 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001599 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001600 break;
1601 }
1602
Ana Krulecba13ab32019-02-20 14:14:12 -08001603 if (mUse90Hz && mUseSmart90ForVideo) {
1604 // This call is made each time SF wakes up and creates a new frame. It is part
1605 // of video detection feature.
1606 mScheduler->incrementFrameCounter();
1607 }
Alec Mourife3dc942019-02-12 14:19:18 -08001608 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001609 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001610 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001611 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001612 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1613 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001614 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001615 }
1616 // For now, only propagate backpressure when missing a hwc frame.
1617 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001618 if (mPropagateBackpressure) {
1619 signalLayerUpdate();
1620 break;
1621 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001622 }
Dan Stoza50182882016-07-08 12:02:20 -07001623
Steven Thomas050b2c82017-03-06 11:45:16 -08001624 // Now that we're going to make it to the handleMessageTransaction()
1625 // call below it's safe to call updateVrFlinger(), which will
1626 // potentially trigger a display handoff.
1627 updateVrFlinger();
1628
Dan Stoza6b9454d2014-11-07 16:00:59 -08001629 bool refreshNeeded = handleMessageTransaction();
1630 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001631
1632 updateCursorAsync();
1633 updateInputFlinger();
1634
Dan Stoza58784442014-12-02 16:58:17 -08001635 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001636 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001637 // Signal a refresh if a transaction modified the window state,
1638 // a new buffer was latched, or if HWC has requested a full
1639 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001640 signalRefresh();
1641 }
1642 break;
1643 }
1644 case MessageQueue::REFRESH: {
1645 handleMessageRefresh();
1646 break;
1647 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001648 }
1649}
1650
Dan Stoza6b9454d2014-11-07 16:00:59 -08001651bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001652 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001653 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001654
1655 // Apply any ready transactions in the queues if there are still transactions that have not been
1656 // applied, wake up during the next vsync period and check again
1657 bool transactionNeeded = false;
1658 if (!flushTransactionQueues()) {
1659 transactionNeeded = true;
1660 }
1661
Mathias Agopian4fec8732012-06-29 14:12:52 -07001662 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001663 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001664 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001665
1666 if (transactionNeeded) {
1667 setTransactionFlags(eTransactionNeeded);
1668 }
1669
1670 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001671}
1672
Mathias Agopian4fec8732012-06-29 14:12:52 -07001673void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001674 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001675
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001676 mRefreshPending = false;
1677
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001678 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001679 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001680 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001681 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682 for (const auto& [token, display] : mDisplays) {
1683 beginFrame(display);
1684 prepareFrame(display);
1685 doDebugFlashRegions(display, repaintEverything);
1686 doComposition(display, repaintEverything);
1687 }
1688
Adrian Roos1e1a1282017-11-01 19:05:31 +01001689 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001690 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001691
1692 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001693 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001694
Dan Stozabfbffeb2016-07-21 14:49:33 -07001695 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001696 for (const auto& [token, displayDevice] : mDisplays) {
1697 auto display = displayDevice->getCompositionDisplay();
1698 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001699 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001700 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001701 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001702
Jorim Jaggi90535212018-05-23 23:44:06 +02001703 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001704
David Sodman7e4ae112018-02-09 15:02:28 -08001705 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001706
1707 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001708}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709
David Sodmanfa9b2af2017-12-24 13:28:59 -08001710
1711bool SurfaceFlinger::handleMessageInvalidate() {
1712 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001713 bool refreshNeeded = handlePageFlip();
1714
Vishnu Nair4351ad52019-02-11 14:13:02 -08001715 if (mVisibleRegionsDirty) {
1716 computeLayerBounds();
1717 }
1718
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001719 for (auto& layer : mLayersPendingRefresh) {
1720 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001721 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001722 invalidateLayerStack(layer, visibleReg);
1723 }
1724 mLayersPendingRefresh.clear();
1725 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001726}
1727
David Sodman79bba0e2018-08-05 18:07:49 -07001728void SurfaceFlinger::calculateWorkingSet() {
1729 ATRACE_CALL();
1730 ALOGV(__FUNCTION__);
1731
David Sodman79bba0e2018-08-05 18:07:49 -07001732 // build the h/w work list
1733 if (CC_UNLIKELY(mGeometryInvalid)) {
1734 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001735 for (const auto& [token, displayDevice] : mDisplays) {
1736 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001737 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738 if (!displayId) {
1739 continue;
1740 }
David Sodman79bba0e2018-08-05 18:07:49 -07001741
Lloyd Pique32cbe282018-10-19 13:09:22 -07001742 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001743 for (size_t i = 0; i < currentLayers.size(); i++) {
1744 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001745
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001746 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001747 layer->forceClientComposition(displayDevice);
1748 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001749 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001750
Lloyd Pique32cbe282018-10-19 13:09:22 -07001751 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001753 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001754 }
David Sodman79bba0e2018-08-05 18:07:49 -07001755 }
1756 }
1757 }
1758
1759 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001760 for (const auto& [token, displayDevice] : mDisplays) {
1761 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001762 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001763 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001764 continue;
1765 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001766 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001767
1768 if (mDrawingState.colorMatrixChanged) {
1769 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001770 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001771 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001772 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001773 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001774 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1775 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001776 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001777 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001778 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1779 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001780 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001781 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001782 }
1783
Peiyong Lind3788632018-09-18 16:01:31 -07001784 // TODO(b/111562338) remove when composer 2.3 is shipped.
1785 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001786 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001787 }
1788
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001789 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001790 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001791 }
1792
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001793 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001794 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001795 layer->setCompositionType(displayDevice,
1796 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001797 continue;
1798 }
1799
Lloyd Pique32cbe282018-10-19 13:09:22 -07001800 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001801 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001802 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001803 }
1804
Peiyong Lin13effd12018-07-24 17:01:47 -07001805 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001806 ColorMode colorMode;
1807 Dataspace dataSpace;
1808 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001810 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001811 }
1812 }
1813
1814 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001815
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001816 for (const auto& [token, displayDevice] : mDisplays) {
1817 auto display = displayDevice->getCompositionDisplay();
1818 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001819 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001820 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1821 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1822 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001823 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001824 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001825 }
1826 }
David Sodman79bba0e2018-08-05 18:07:49 -07001827}
1828
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1830 bool repaintEverything) {
1831 auto display = displayDevice->getCompositionDisplay();
1832 const auto& displayState = display->getState();
1833
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834 // is debugging enabled
1835 if (CC_LIKELY(!mDebugRegion))
1836 return;
1837
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001839 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001840 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001841 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001842 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001843 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001844 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001846 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001847 }
1848 }
1849
Lloyd Pique32cbe282018-10-19 13:09:22 -07001850 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001851
1852 if (mDebugRegion > 1) {
1853 usleep(mDebugRegion * 1000);
1854 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001855
Lloyd Pique32cbe282018-10-19 13:09:22 -07001856 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857}
1858
Adrian Roos1e1a1282017-11-01 19:05:31 +01001859void SurfaceFlinger::doTracing(const char* where) {
1860 ATRACE_CALL();
1861 ATRACE_NAME(where);
1862 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001863 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001864 }
1865}
1866
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001867void SurfaceFlinger::logLayerStats() {
1868 ATRACE_CALL();
1869 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001870 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001871 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001872 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001873 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001874 }
1875 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001876
1877 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001878 }
1879}
1880
David Sodman2b406362017-12-15 13:33:47 -08001881void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 ATRACE_CALL();
1884 ALOGV("preComposition");
1885
David Sodman2b406362017-12-15 13:33:47 -08001886 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1887
Mathias Agopiancd60f992012-08-16 16:28:27 -07001888 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001889 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001890 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 needExtraInvalidate = true;
1892 }
Robert Carr2047fae2016-11-28 14:09:09 -08001893 });
1894
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895 if (needExtraInvalidate) {
1896 signalLayerUpdate();
1897 }
1898}
1899
Ana Krulece588e312018-09-18 12:32:24 -07001900void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1901 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902 // Update queue of past composite+present times and determine the
1903 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001904 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001905 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001906 while (!getBE().mCompositePresentTimes.empty()) {
1907 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908 // Cached values should have been updated before calling this method,
1909 // which helps avoid duplicate syscalls.
1910 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1911 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1912 break;
1913 }
1914 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001915 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916 }
1917
1918 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001919 while (getBE().mCompositePresentTimes.size() > 16) {
1920 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 }
1922
Ana Krulece588e312018-09-18 12:32:24 -07001923 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001924}
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1927 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 // Integer division and modulo round toward 0 not -inf, so we need to
1929 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001930 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1931 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1932 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001933
Ana Krulec757f63a2019-01-25 10:46:18 -08001934 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001935 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001936 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001937 }
1938
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 // Snap the latency to a value that removes scheduling jitter from the
1940 // composition and present times, which often have >1ms of jitter.
1941 // Reducing jitter is important if an app attempts to extrapolate
1942 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001943 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001945 nsecs_t bias = stats.vsyncPeriod / 2;
1946 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1947 nsecs_t snappedCompositeToPresentLatency =
1948 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949
David Sodman99974d22017-11-28 12:04:33 -08001950 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001951 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1952 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001953 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954}
1955
Ady Abraham8164d482019-01-11 14:47:59 -08001956// debug patch for b/119477596 - add stack guards to catch stack
1957// corruptions and disable clang optimizations.
1958// The code below is temporary and planned to be removed once stack
1959// corruptions are found.
1960#pragma clang optimize off
1961class StackGuard {
1962public:
1963 StackGuard(const char* name, const char* func, int line) {
1964 guarders.reserve(MIN_CAPACITY);
1965 guarders.push_back({this, name, func, line});
1966 validate();
1967 }
1968 ~StackGuard() {
1969 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1970 if (i->guard == this) {
1971 guarders.erase(i);
1972 break;
1973 }
1974 }
1975 }
1976
1977 static void validate() {
1978 for (const auto& guard : guarders) {
1979 if (guard.guard->cookie != COOKIE_VALUE) {
1980 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1981 CallStack stack(LOG_TAG);
1982 abort();
1983 }
1984 }
1985 }
1986
1987private:
1988 uint64_t cookie = COOKIE_VALUE;
1989 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1990 static constexpr size_t MIN_CAPACITY = 16;
1991
1992 struct GuarderElement {
1993 StackGuard* guard;
1994 const char* name;
1995 const char* func;
1996 int line;
1997 };
1998
1999 static std::vector<GuarderElement> guarders;
2000};
2001std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2002
2003#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2004
2005#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002006void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002007{
Ady Abraham8164d482019-01-11 14:47:59 -08002008 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 ATRACE_CALL();
2010 ALOGV("postComposition");
2011
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002013 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002014 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002016 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002017 }
Ady Abraham8164d482019-01-11 14:47:59 -08002018 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002019
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002020 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002021 const auto displayDevice = getDefaultDisplayDeviceLocked();
2022 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023
David Sodman73beded2017-11-15 11:56:06 -08002024 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2027
Lloyd Pique32cbe282018-10-19 13:09:22 -07002028 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002030 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2031 ->getRenderSurface()
2032 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002033 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002034 } else {
2035 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2036 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002037
Ady Abraham8164d482019-01-11 14:47:59 -08002038 ASSERT_ON_STACK_GUARD();
2039
David Sodman73beded2017-11-15 11:56:06 -08002040 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002041 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2042 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002043 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002045 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002046
Ana Krulece588e312018-09-18 12:32:24 -07002047 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002048 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002049 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050
Ady Abraham8164d482019-01-11 14:47:59 -08002051 ASSERT_ON_STACK_GUARD();
2052
David Sodman2b406362017-12-15 13:33:47 -08002053 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 // when we started doing work for this frame, but that should be okay
2055 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002056 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002057 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002058 DEFINE_STACK_GUARD(compositorTiming);
2059
Brian Andersond0010582017-03-07 13:20:31 -08002060 {
David Sodman99974d22017-11-28 12:04:33 -08002061 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002062 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002063 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002064
2065 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002066 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002067
Robert Carr2047fae2016-11-28 14:09:09 -08002068 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 bool frameLatched =
2070 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2071 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002072 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002073 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002074 recordBufferingStats(layer->getName().string(),
2075 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002076 }
Ady Abraham8164d482019-01-11 14:47:59 -08002077 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002078 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002079
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002080 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002081 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002082 mScheduler->addPresentFence(presentFenceTime);
2083 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002084 }
2085
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002086 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2088 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002089 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002090 }
2091 }
2092
Ady Abraham8164d482019-01-11 14:47:59 -08002093 ASSERT_ON_STACK_GUARD();
2094
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002095 if (mAnimCompositionPending) {
2096 mAnimCompositionPending = false;
2097
Brian Anderson4e606e32017-03-16 15:34:57 -07002098 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002099 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002100 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002101
2102 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002103 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002104 // The HWC doesn't support present fences, so use the refresh
2105 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002106 const nsecs_t presentTime =
2107 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002108 DEFINE_STACK_GUARD(presentTime);
2109
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002110 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002111 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002112 }
2113 mAnimFrameTracker.advanceFrame();
2114 }
Dan Stozab90cf072015-03-05 11:05:59 -08002115
Ady Abraham8164d482019-01-11 14:47:59 -08002116 ASSERT_ON_STACK_GUARD();
2117
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002118 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002119 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002120 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002121 }
2122
Ady Abraham8164d482019-01-11 14:47:59 -08002123 ASSERT_ON_STACK_GUARD();
2124
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002125 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002126
Ady Abraham8164d482019-01-11 14:47:59 -08002127 ASSERT_ON_STACK_GUARD();
2128
Lloyd Pique32cbe282018-10-19 13:09:22 -07002129 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2130 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002131 return;
2132 }
2133
2134 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002135 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002136 if (mHasPoweredOff) {
2137 mHasPoweredOff = false;
2138 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002139 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002140 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002141 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002142 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002143 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2144 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002145 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002146 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002147 }
David Sodman4a36e932017-11-07 14:29:47 -08002148 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002149
2150 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002151 }
David Sodman4a36e932017-11-07 14:29:47 -08002152 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002153 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002154
2155 {
2156 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002157 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002158 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002159 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002160 if (refillCount > 0) {
2161 const size_t offset = mTexturePool.size();
2162 mTexturePool.resize(mTexturePoolSize);
2163 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2164 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2165 }
Ady Abraham8164d482019-01-11 14:47:59 -08002166 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002167 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002168
Marissa Wallfda30bb2018-10-12 11:34:28 -07002169 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002170 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002171
2172 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002173}
Ady Abraham8164d482019-01-11 14:47:59 -08002174#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002175
Vishnu Nair4351ad52019-02-11 14:13:02 -08002176void SurfaceFlinger::computeLayerBounds() {
2177 for (const auto& pair : mDisplays) {
2178 const auto& displayDevice = pair.second;
2179 const auto display = displayDevice->getCompositionDisplay();
2180 for (const auto& layer : mDrawingState.layersSortedByZ) {
2181 // only consider the layers on the given layer stack
2182 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002183 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002184 }
2185
2186 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2187 }
2188 }
2189}
2190
Mathias Agopiancd60f992012-08-16 16:28:27 -07002191void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192 ATRACE_CALL();
2193 ALOGV("rebuildLayerStacks");
2194
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002195 // We need to clear these out now as these may be holding on to a
2196 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2197 // also holds a reference. When the set of visible layers is recomputed,
2198 // some layers may be destroyed if the only thing keeping them alive was
2199 // that list of visible layers associated with each display. The layer
2200 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2201 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2202 for (const auto& [token, display] : mDisplays) {
2203 getBE().mCompositionInfo[token].clear();
2204 }
2205
Mathias Agopiancd60f992012-08-16 16:28:27 -07002206 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002207 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002208 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002209 mVisibleRegionsDirty = false;
2210 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002211
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002212 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002213 const auto& displayDevice = pair.second;
2214 auto display = displayDevice->getCompositionDisplay();
2215 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002216 Region opaqueRegion;
2217 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002218 compositionengine::Output::OutputLayers layersSortedByZ;
2219 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002220 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002221 const ui::Transform& tr = displayState.transform;
2222 const Rect bounds = displayState.bounds;
2223 if (displayState.isEnabled) {
2224 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002225
Jeff Sharkey76488112017-02-27 14:15:18 -07002226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002227 auto compositionLayer = layer->getCompositionLayer();
2228 if (compositionLayer == nullptr) {
2229 return;
2230 }
2231
Lloyd Pique32cbe282018-10-19 13:09:22 -07002232 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002233 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2234 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2235
Lloyd Pique07e33212018-12-18 16:33:37 -08002236 bool needsOutputLayer = false;
2237
Lloyd Piqueef36b002019-01-23 17:52:04 -08002238 if (display->belongsInOutput(layer->getLayerStack(),
2239 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 Region drawRegion(tr.transform(
2241 layer->visibleNonTransparentRegion));
2242 drawRegion.andSelf(bounds);
2243 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002244 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 }
Chia-I Wu83806892017-11-16 10:50:20 -08002246 }
2247
Lloyd Pique07e33212018-12-18 16:33:37 -08002248 if (needsOutputLayer) {
2249 layersSortedByZ.emplace_back(
2250 display->getOrCreateOutputLayer(displayId, compositionLayer,
2251 layerFE));
2252 deprecated_layersSortedByZ.add(layer);
2253
2254 auto& outputLayerState = layersSortedByZ.back()->editState();
2255 outputLayerState.visibleRegion =
2256 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2257 } else if (displayId) {
2258 // For layers that are being removed from a HWC display,
2259 // and that have queued frames, add them to a a list of
2260 // released layers so we can properly set a fence.
2261 bool hasExistingOutputLayer =
2262 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2263 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2264 mLayersWithQueuedFrames.cend(),
2265 layer) != mLayersWithQueuedFrames.cend();
2266
2267 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002268 layersNeedingFences.add(layer);
2269 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002271 });
2272 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002273
2274 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2275
2276 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 displayDevice->setLayersNeedingFences(layersNeedingFences);
2278
2279 Region undefinedRegion{bounds};
2280 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2281
2282 display->editState().undefinedRegion = undefinedRegion;
2283 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002284 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002285 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002286}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002287
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002290// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002291// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002292// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293// The returned HDR data space is one of
2294// - Dataspace::UNKNOWN
2295// - Dataspace::BT2020_HLG
2296// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2298 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002299 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 *outHdrDataSpace = Dataspace::UNKNOWN;
2301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002303 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 case Dataspace::V0_SCRGB:
2305 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002306 case Dataspace::BT2020:
2307 case Dataspace::BT2020_ITU:
2308 case Dataspace::BT2020_LINEAR:
2309 case Dataspace::DISPLAY_BT2020:
2310 bestDataSpace = Dataspace::DISPLAY_BT2020;
2311 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002312 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002313 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 case Dataspace::BT2020_PQ:
2316 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002317 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002320 case Dataspace::BT2020_HLG:
2321 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002322 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323 // When there's mixed PQ content and HLG content, we set the HDR
2324 // data space to be BT2020_PQ and convert HLG to PQ.
2325 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2326 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002327 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 break;
2329 default:
2330 break;
2331 }
Romain Guy54f154a2017-10-24 21:40:32 +01002332 }
2333
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002335}
2336
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2339 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002340 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2341 *outMode = ColorMode::NATIVE;
2342 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002345 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002346
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002347 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002348 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002349
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002350 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2351
Peiyong Lina3ea5592019-02-10 14:45:00 -08002352 switch (mForceColorMode) {
2353 case ColorMode::SRGB:
2354 bestDataSpace = Dataspace::V0_SRGB;
2355 break;
2356 case ColorMode::DISPLAY_P3:
2357 bestDataSpace = Dataspace::DISPLAY_P3;
2358 break;
2359 default:
2360 break;
2361 }
2362
Peiyong Lindfde5112018-06-05 10:58:41 -07002363 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002364 const bool isHdr =
2365 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002366 if (isHdr) {
2367 bestDataSpace = hdrDataSpace;
2368 }
2369
Chia-I Wu0d711262018-05-21 15:19:35 -07002370 RenderIntent intent;
2371 switch (mDisplayColorSetting) {
2372 case DisplayColorSetting::MANAGED:
2373 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002374 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002375 break;
2376 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002377 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002378 break;
2379 default: // vendor display color setting
2380 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2381 break;
2382 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002383
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002384 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002385}
2386
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2388 auto display = displayDevice->getCompositionDisplay();
2389 const auto& displayState = display->getState();
2390
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002391 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002392 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2393 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002394
David Sodmanfa9b2af2017-12-24 13:28:59 -08002395 // If nothing has changed (!dirty), don't recompose.
2396 // If something changed, but we don't currently have any visible layers,
2397 // and didn't when we last did a composition, then skip it this time.
2398 // The second rule does two things:
2399 // - When all layers are removed from a display, we'll emit one black
2400 // frame, then nothing more until we get new layers.
2401 // - When a display is created with a private layer stack, we won't
2402 // emit any black frames until a layer is added to the layer stack.
2403 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002404
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 const char flagPrefix[] = {'-', '+'};
2406 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2408 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2409 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2410 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002411
Lloyd Pique31cb2942018-10-19 17:23:03 -07002412 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002413
David Sodmanfa9b2af2017-12-24 13:28:59 -08002414 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002415 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002416 }
2417}
2418
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2420 auto display = displayDevice->getCompositionDisplay();
2421 const auto& displayState = display->getState();
2422
2423 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002424 return;
David Sodman2b406362017-12-15 13:33:47 -08002425 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002426
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002427 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002430}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002431
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002433 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002434 ALOGV("doComposition");
2435
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436 auto display = displayDevice->getCompositionDisplay();
2437 const auto& displayState = display->getState();
2438
2439 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002441 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002442
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002447 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002448 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002450}
2451
David Sodmanfa9b2af2017-12-24 13:28:59 -08002452void SurfaceFlinger::postFrame()
2453{
2454 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 const auto display = getDefaultDisplayDeviceLocked();
2456 if (display && getHwComposer().isConnected(*display->getId())) {
2457 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002458 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2459 logFrameStats();
2460 }
2461 }
2462}
2463
Lloyd Pique32cbe282018-10-19 13:09:22 -07002464void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002465 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002466 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002467
Lloyd Pique32cbe282018-10-19 13:09:22 -07002468 auto display = displayDevice->getCompositionDisplay();
2469 const auto& displayState = display->getState();
2470 const auto displayId = display->getId();
2471
David Sodmanfa9b2af2017-12-24 13:28:59 -08002472 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002473
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002475 if (displayId) {
2476 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002477 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002478 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002480 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002481
Chia-I Wu7b549592017-11-15 09:14:57 -08002482 // The layer buffer from the previous frame (if any) is released
2483 // by HWC only when the release fence from this frame (if any) is
2484 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002485 if (displayId && layer->hasHwcLayer(displayDevice)) {
2486 releaseFence =
2487 getHwComposer().getLayerReleaseFence(*displayId,
2488 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002489 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002490
2491 // If the layer was client composited in the previous frame, we
2492 // need to merge with the previous client target acquire fence.
2493 // Since we do not track that, always merge with the current
2494 // client target acquire fence when it is available, even though
2495 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002496 if (layer->getCompositionType(displayDevice) ==
2497 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002498 releaseFence =
2499 Fence::merge("LayerRelease", releaseFence,
2500 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002501 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002502
David Sodman15094112018-10-11 09:39:37 -07002503 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 }
Chia-I Wu83806892017-11-16 10:50:20 -08002505
2506 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002507 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002508 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002509 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002510 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002511 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002512 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002513 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002514 }
2515 }
2516
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 if (displayId) {
2518 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002519 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521}
2522
Mathias Agopian87baae12012-07-31 12:38:26 -07002523void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524{
Mathias Agopian841cde52012-03-01 15:44:37 -08002525 ATRACE_CALL();
2526
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002527 // here we keep a copy of the drawing state (that is the state that's
2528 // going to be overwritten by handleTransactionLocked()) outside of
2529 // mStateLock so that the side-effects of the State assignment
2530 // don't happen with mStateLock held (which can cause deadlocks).
2531 State drawingState(mDrawingState);
2532
Mathias Agopianca4d3602011-05-19 15:38:14 -07002533 Mutex::Autolock _l(mStateLock);
2534 const nsecs_t now = systemTime();
2535 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536
Mathias Agopianca4d3602011-05-19 15:38:14 -07002537 // Here we're guaranteed that some transaction flags are set
2538 // so we can call handleTransactionLocked() unconditionally.
2539 // We call getTransactionFlags(), which will also clear the flags,
2540 // with mStateLock held to guarantee that mCurrentState won't change
2541 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002542
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002543 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002544 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002545 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002546
Mathias Agopianca4d3602011-05-19 15:38:14 -07002547 mLastTransactionTime = systemTime() - now;
2548 mDebugInTransaction = 0;
2549 invalidateHwcGeometry();
2550 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002551}
2552
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2554 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 const std::optional<DisplayIdentificationInfo> info =
2556 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002557
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002559 continue;
2560 }
2561
Lloyd Piqueba04e622017-12-14 17:11:26 -08002562 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002564 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 mPhysicalDisplayTokens[info->id] = new BBinder();
2566 DisplayDeviceState state;
2567 state.displayId = info->id;
2568 state.isSecure = true; // All physical displays are currently considered secure.
2569 state.displayName = info->name;
2570 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2571 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002572 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002573 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002574 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002575
Dominik Laskowski075d3172018-05-24 15:50:06 -07002576 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2577 if (index >= 0) {
2578 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2579 mInterceptor->saveDisplayDeletion(state.sequenceId);
2580 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002581 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002582 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002583 }
2584
2585 processDisplayChangesLocked();
2586 }
2587
2588 mPendingHotplugEvents.clear();
2589}
2590
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002591void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002592 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2593 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002594}
2595
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002598 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 const sp<IGraphicBufferProducer>& producer) {
2600 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002601 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002603 creationArgs.isSecure = state.isSecure;
2604 creationArgs.displaySurface = dispSurface;
2605 creationArgs.hasWideColorGamut = false;
2606 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002607
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002608 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 creationArgs.isPrimary = isInternalDisplay;
2610
2611 if (useColorManagement && displayId) {
2612 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002614 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002615 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002617
Dominik Laskowski7e045462018-05-30 13:02:02 -07002618 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621 }
tangrobin6753a022018-08-10 10:58:54 +08002622 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 if (displayId) {
2625 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002626 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002628 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002629
Lloyd Pique90c115d2018-09-18 21:39:42 -07002630 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002631 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002632 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 // Make sure that composition can never be stalled by a virtual display
2635 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002636 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002637 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2639 }
2640
Dominik Laskowski075d3172018-05-24 15:50:06 -07002641 creationArgs.displayInstallOrientation =
2642 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002643
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002645 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646
Lloyd Pique90c115d2018-09-18 21:39:42 -07002647 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002648
2649 if (maxFrameBufferAcquiredBuffers >= 3) {
2650 nativeWindowSurface->preallocateBuffers();
2651 }
2652
2653 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002654 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002655 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002657 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002659 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2660 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 if (!state.isVirtual()) {
2662 LOG_ALWAYS_FATAL_IF(!displayId);
2663 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002664 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002666 display->setLayerStack(state.layerStack);
2667 display->setProjection(state.orientation, state.viewport, state.frame);
2668 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671}
2672
Lloyd Pique347200f2017-12-14 17:00:15 -08002673void SurfaceFlinger::processDisplayChangesLocked() {
2674 // here we take advantage of Vector's copy-on-write semantics to
2675 // improve performance by skipping the transaction entirely when
2676 // know that the lists are identical
2677 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2678 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2679 if (!curr.isIdenticalTo(draw)) {
2680 mVisibleRegionsDirty = true;
2681 const size_t cc = curr.size();
2682 size_t dc = draw.size();
2683
2684 // find the displays that were removed
2685 // (ie: in drawing state but not in current state)
2686 // also handle displays that changed
2687 // (ie: displays that are in both lists)
2688 for (size_t i = 0; i < dc;) {
2689 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2690 if (j < 0) {
2691 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002693 // Save display ID before disconnecting.
2694 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002695 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002696
2697 if (!display->isVirtual()) {
2698 LOG_ALWAYS_FATAL_IF(!displayId);
2699 dispatchDisplayHotplugEvent(displayId->value, false);
2700 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002702
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002703 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 } else {
2705 // this display is in both lists. see if something changed.
2706 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2709 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2710 if (state_binder != draw_binder) {
2711 // changing the surface is like destroying and
2712 // recreating the DisplayDevice, so we just remove it
2713 // from the drawing state, so that it get re-added
2714 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002716 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002717 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002718 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002719 mDrawingState.displays.removeItemsAt(i);
2720 dc--;
2721 // at this point we must loop to the next item
2722 continue;
2723 }
2724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002728 }
2729 if ((state.orientation != draw[i].orientation) ||
2730 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 }
2733 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736 }
2737 }
2738 ++i;
2739 }
2740
2741 // find displays that were added
2742 // (ie: in current state but not in drawing state)
2743 for (size_t i = 0; i < cc; i++) {
2744 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2745 const DisplayDeviceState& state(curr[i]);
2746
Lloyd Pique542307f2018-10-19 13:24:08 -07002747 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 sp<IGraphicBufferProducer> producer;
2749 sp<IGraphicBufferProducer> bqProducer;
2750 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002751 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002754 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 // Virtual displays without a surface are dormant:
2756 // they have external state (layer stack, projection,
2757 // etc.) but no internal state (i.e. a DisplayDevice).
2758 if (state.surface != nullptr) {
2759 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002760 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 int width = 0;
2762 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2763 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2764 int height = 0;
2765 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2766 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2767 int intFormat = 0;
2768 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2769 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002770 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002771
Dominik Laskowski075d3172018-05-24 15:50:06 -07002772 displayId =
2773 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 }
2775
2776 // TODO: Plumb requested format back up to consumer
2777
2778 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002779 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002780 bqProducer, bqConsumer,
2781 state.displayName);
2782
2783 dispSurface = vds;
2784 producer = vds;
2785 }
2786 } else {
2787 ALOGE_IF(state.surface != nullptr,
2788 "adding a supported display, but rendering "
2789 "surface is provided (%p), ignoring it",
2790 state.surface.get());
2791
Dominik Laskowski075d3172018-05-24 15:50:06 -07002792 displayId = state.displayId;
2793 LOG_ALWAYS_FATAL_IF(!displayId);
2794 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002795 producer = bqProducer;
2796 }
2797
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002798 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002799 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002800 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002801 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002802 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002803 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002804 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002805 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002806 }
2807 }
2808 }
2809 }
2810 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002811
2812 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002813}
2814
Mathias Agopian87baae12012-07-31 12:38:26 -07002815void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002816{
Dan Stoza7dde5992015-05-22 09:51:44 -07002817 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002818 mCurrentState.traverseInZOrder([](Layer* layer) {
2819 layer->notifyAvailableFrames();
2820 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002821
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 /*
2823 * Traversal of the children
2824 * (perform the transaction for each of them if needed)
2825 */
2826
Mathias Agopian3559b072012-08-15 13:46:03 -07002827 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002828 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002829 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002830 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831
2832 const uint32_t flags = layer->doTransaction(0);
2833 if (flags & Layer::eVisibleRegion)
2834 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002835
2836 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002837 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 }
2841
2842 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002843 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844 */
2845
Mathias Agopiane57f2922012-08-09 16:29:12 -07002846 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002847 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002848 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002849 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002851 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002852 // The transform hint might have changed for some layers
2853 // (either because a display has changed, or because a layer
2854 // as changed).
2855 //
2856 // Walk through all the layers in currentLayers,
2857 // and update their transform hint.
2858 //
2859 // If a layer is visible only on a single display, then that
2860 // display is used to calculate the hint, otherwise we use the
2861 // default display.
2862 //
2863 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2864 // the hint is set before we acquire a buffer from the surface texture.
2865 //
2866 // NOTE: layer transactions have taken place already, so we use their
2867 // drawing state. However, SurfaceFlinger's own transaction has not
2868 // happened yet, so we must use the current state layer list
2869 // (soon to become the drawing state list).
2870 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002872 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002873 bool first = true;
2874 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002875 // NOTE: we rely on the fact that layers are sorted by
2876 // layerStack first (so we don't have to traverse the list
2877 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002878 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002879 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002880 currentlayerStack = layerStack;
2881 // figure out if this layerstack is mirrored
2882 // (more than one display) if so, pick the default display,
2883 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 hintDisplay = nullptr;
2885 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002886 if (display->getCompositionDisplay()
2887 ->belongsInOutput(layer->getLayerStack(),
2888 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 if (hintDisplay) {
2890 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002891 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002892 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002894 }
2895 }
2896 }
2897 }
Chet Haase91d25932013-04-11 15:24:55 -07002898
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002899 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002900 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2901 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002902
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002903 // could be null when this layer is using a layerStack
2904 // that is not visible on any display. Also can occur at
2905 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002907 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002908
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002909 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002910 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002911 if (hintDisplay) {
2912 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002913 }
Robert Carr2047fae2016-11-28 14:09:09 -08002914
2915 first = false;
2916 });
Mathias Agopian84300952012-11-21 16:02:13 -08002917 }
2918
2919
Mathias Agopian3559b072012-08-15 13:46:03 -07002920 /*
2921 * Perform our own transaction if needed
2922 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923
2924 if (mLayersAdded) {
2925 mLayersAdded = false;
2926 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002927 mVisibleRegionsDirty = true;
2928 }
2929
2930 // some layers might have been removed, so
2931 // we need to update the regions they're exposing.
2932 if (mLayersRemoved) {
2933 mLayersRemoved = false;
2934 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002935 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002937 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002938 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002939 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002940 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002941 }
Robert Carr2047fae2016-11-28 14:09:09 -08002942 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 }
2944
Vishnu Nairec0ab382019-02-13 15:32:56 -08002945 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002947}
2948
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002949void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002950 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002951 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002952 return;
2953 }
2954
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002955 if (mVisibleRegionsDirty || mInputInfoChanged) {
2956 mInputInfoChanged = false;
2957 updateInputWindowInfo();
2958 }
2959
2960 executeInputWindowCommands();
2961}
2962
2963void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002964 Vector<InputWindowInfo> inputHandles;
2965
2966 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2967 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002968 // When calculating the screen bounds we ignore the transparent region since it may
2969 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002970 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002971 }
2972 });
2973 mInputFlinger->setInputWindows(inputHandles);
2974}
2975
Vishnu Nairec0ab382019-02-13 15:32:56 -08002976void SurfaceFlinger::commitInputWindowCommands() {
2977 mInputWindowCommands.merge(mPendingInputWindowCommands);
2978 mPendingInputWindowCommands.clear();
2979}
2980
chaviwfbe5d9c2018-12-26 12:23:37 -08002981void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002982 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2983 if (transferTouchFocusCommand.fromToken != nullptr &&
2984 transferTouchFocusCommand.toToken != nullptr &&
2985 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2986 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2987 transferTouchFocusCommand.toToken);
2988 }
2989 }
2990
2991 mInputWindowCommands.clear();
2992}
2993
Riley Andrews03414a12014-07-01 14:22:59 -07002994void SurfaceFlinger::updateCursorAsync()
2995{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002996 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002997 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002998 continue;
2999 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003001 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3002 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003003 }
3004 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003005}
3006
chaviw61626f22018-11-15 16:26:27 -08003007void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3008 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003009 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003010 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003011 }
3012 layer->releasePendingBuffer(systemTime());
3013}
3014
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015void SurfaceFlinger::commitTransaction()
3016{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003017 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003019 for (const auto& l : mLayersPendingRemoval) {
3020 recordBufferingStats(l->getName().string(),
3021 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003022
Lloyd Pique07e33212018-12-18 16:33:37 -08003023 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003024 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003025 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003026 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003027 }
3028 mLayersPendingRemoval.clear();
3029 }
3030
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003031 // If this transaction is part of a window animation then the next frame
3032 // we composite should be considered an animation as well.
3033 mAnimCompositionPending = mAnimTransactionPending;
3034
Mathias Agopian4fec8732012-06-29 14:12:52 -07003035 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003036 // clear the "changed" flags in current state
3037 mCurrentState.colorMatrixChanged = false;
3038
Robert Carr1f0a16a2016-10-24 16:27:39 -07003039 mDrawingState.traverseInZOrder([](Layer* layer) {
3040 layer->commitChildList();
3041 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003042 mTransactionPending = false;
3043 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003044 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045}
3046
Lloyd Pique32cbe282018-10-19 13:09:22 -07003047void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003048 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003049 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003051
Lloyd Pique32cbe282018-10-19 13:09:22 -07003052 auto display = displayDevice->getCompositionDisplay();
3053
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054 Region aboveOpaqueLayers;
3055 Region aboveCoveredLayers;
3056 Region dirty;
3057
Mathias Agopian87baae12012-07-31 12:38:26 -07003058 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059
Robert Carr2047fae2016-11-28 14:09:09 -08003060 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003061 // start with the whole surface at its current location
3062 const Layer::State& s(layer->getDrawingState());
3063
Jesse Hall01e29052013-02-19 16:13:35 -08003064 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003065 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003066 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003067 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003068
Mathias Agopianab028732010-03-16 16:41:46 -07003069 /*
3070 * opaqueRegion: area of a surface that is fully opaque.
3071 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003073
3074 /*
3075 * visibleRegion: area of a surface that is visible on screen
3076 * and not fully transparent. This is essentially the layer's
3077 * footprint minus the opaque regions above it.
3078 * Areas covered by a translucent surface are considered visible.
3079 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003081
3082 /*
3083 * coveredRegion: area of a surface that is covered by all
3084 * visible regions above it (which includes the translucent areas).
3085 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003087
Jesse Halla8026d22012-09-25 13:25:04 -07003088 /*
3089 * transparentRegion: area of a surface that is hinted to be completely
3090 * transparent. This is only used to tell when the layer has no visible
3091 * non-transparent regions and can be removed from the layer list. It
3092 * does not affect the visibleRegion of this layer or any layers
3093 * beneath it. The hint may not be correct if apps don't respect the
3094 * SurfaceView restrictions (which, sadly, some don't).
3095 */
3096 Region transparentRegion;
3097
Mathias Agopianab028732010-03-16 16:41:46 -07003098
3099 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003100 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003101 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003102 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003103
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003105 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003106 if (!visibleRegion.isEmpty()) {
3107 // Remove the transparent area from the visible region
3108 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003109 if (tr.preserveRects()) {
3110 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003111 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003112 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003113 // transformation too complex, can't do the
3114 // transparent region optimization.
3115 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 }
Mathias Agopianab028732010-03-16 16:41:46 -07003117 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003118
Mathias Agopianab028732010-03-16 16:41:46 -07003119 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003120 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003121 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003122 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003123 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003124 // the opaque region is the layer's footprint
3125 opaqueRegion = visibleRegion;
3126 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127 }
3128 }
3129
Robert Carre5f4f692018-01-12 13:12:28 -08003130 if (visibleRegion.isEmpty()) {
3131 layer->clearVisibilityRegions();
3132 return;
3133 }
3134
Mathias Agopianab028732010-03-16 16:41:46 -07003135 // Clip the covered region to the visible region
3136 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3137
3138 // Update aboveCoveredLayers for next (lower) layer
3139 aboveCoveredLayers.orSelf(visibleRegion);
3140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 // subtract the opaque region covered by the layers above us
3142 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143
3144 // compute this layer's dirty region
3145 if (layer->contentDirty) {
3146 // we need to invalidate the whole region
3147 dirty = visibleRegion;
3148 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003149 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 layer->contentDirty = false;
3151 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003152 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003153 * the exposed region consists of two components:
3154 * 1) what's VISIBLE now and was COVERED before
3155 * 2) what's EXPOSED now less what was EXPOSED before
3156 *
3157 * note that (1) is conservative, we start with the whole
3158 * visible region but only keep what used to be covered by
3159 * something -- which mean it may have been exposed.
3160 *
3161 * (2) handles areas that were not covered by anything but got
3162 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003163 */
Mathias Agopianab028732010-03-16 16:41:46 -07003164 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003165 const Region oldVisibleRegion = layer->visibleRegion;
3166 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003167 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3168 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 }
3170 dirty.subtractSelf(aboveOpaqueLayers);
3171
3172 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003173 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174
Mathias Agopianab028732010-03-16 16:41:46 -07003175 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003177
Jesse Halla8026d22012-09-25 13:25:04 -07003178 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 layer->setVisibleRegion(visibleRegion);
3180 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003181 layer->setVisibleNonTransparentRegion(
3182 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003183 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184
Mathias Agopian87baae12012-07-31 12:38:26 -07003185 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186}
3187
Chia-I Wuab0c3192017-08-01 11:29:00 -07003188void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003189 for (const auto& [token, displayDevice] : mDisplays) {
3190 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003191 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003192 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003193 }
3194 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003195}
3196
Daniel Solomon42d04562019-01-20 21:03:19 -08003197void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3198 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3199 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3200 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3201 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3202 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3203 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3204 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3205 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3206 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3207 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3208 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3209 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3210}
3211
Dan Stoza6b9454d2014-11-07 16:00:59 -08003212bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003214 ALOGV("handlePageFlip");
3215
Brian Andersond6927fb2016-07-23 23:37:30 -07003216 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003217
Mathias Agopian4fec8732012-06-29 14:12:52 -07003218 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003219 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003220 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003221
3222 // Store the set of layers that need updates. This set must not change as
3223 // buffers are being latched, as this could result in a deadlock.
3224 // Example: Two producers share the same command stream and:
3225 // 1.) Layer 0 is latched
3226 // 2.) Layer 0 gets a new frame
3227 // 2.) Layer 1 gets a new frame
3228 // 3.) Layer 1 is latched.
3229 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3230 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003231 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003232 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003233 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003234 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003235 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003236 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003237 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003238 } else {
3239 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003241 } else {
3242 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003243 }
Robert Carr2047fae2016-11-28 14:09:09 -08003244 });
3245
Lloyd Piquef2c79392018-12-20 16:23:33 -08003246 if (!mLayersWithQueuedFrames.empty()) {
3247 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3248 // writes to Layer current state. See also b/119481871
3249 Mutex::Autolock lock(mStateLock);
3250
3251 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003252 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003253 mLayersPendingRefresh.push_back(layer);
3254 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003255 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003256 if (layer->isBufferLatched()) {
3257 newDataLatched = true;
3258 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003259 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003260 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003261
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003262 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263
3264 // If we will need to wake up at some time in the future to deal with a
3265 // queued frame that shouldn't be displayed during this vsync period, wake
3266 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003267 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003268 signalLayerUpdate();
3269 }
3270
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003271 // enter boot animation on first buffer latch
3272 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3273 ALOGI("Enter boot animation");
3274 mBootStage = BootStage::BOOTANIMATION;
3275 }
3276
Dan Stoza6b9454d2014-11-07 16:00:59 -08003277 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003278 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279}
3280
Mathias Agopianad456f92011-01-13 17:53:01 -08003281void SurfaceFlinger::invalidateHwcGeometry()
3282{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003283 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003284}
3285
Lloyd Pique32cbe282018-10-19 13:09:22 -07003286void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003287 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003288 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003289 // We only need to actually compose the display if:
3290 // 1) It is being handled by hardware composer, which may need this to
3291 // keep its virtual display state machine in sync, or
3292 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003293 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003294 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003295 return;
3296 }
3297
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003299 base::unique_fd readyFence;
3300 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003301
3302 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003303 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304}
3305
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003306bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3307 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003308 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003309 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003310
Lloyd Pique32cbe282018-10-19 13:09:22 -07003311 auto display = displayDevice->getCompositionDisplay();
3312 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003313 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003314
3315 const Region bounds(displayState.bounds);
3316 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003317 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003318 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003319
Peiyong Lind3788632018-09-18 16:01:31 -07003320 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003321 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003322
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003323 renderengine::DisplaySettings clientCompositionDisplay;
3324 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3325 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003326
Dan Stoza9e56aa02015-11-02 13:00:03 -08003327 if (hasClientComposition) {
3328 ALOGV("hasClientComposition");
3329
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003330 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003331
3332 if (buf == nullptr) {
3333 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3334 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003335 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003336 return false;
3337 }
3338
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003339 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3340 clientCompositionDisplay.clip = displayState.scissor;
3341 const ui::Transform& displayTransform = displayState.transform;
3342 mat4 m;
3343 m[0][0] = displayTransform[0][0];
3344 m[0][1] = displayTransform[0][1];
3345 m[0][3] = displayTransform[0][2];
3346 m[1][0] = displayTransform[1][0];
3347 m[1][1] = displayTransform[1][1];
3348 m[1][3] = displayTransform[1][2];
3349 m[3][0] = displayTransform[2][0];
3350 m[3][1] = displayTransform[2][1];
3351 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003352
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003353 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003354
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003355 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003356 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003357 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003358 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003359 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003360 clientCompositionDisplay.outputDataspace = outputDataspace;
3361 clientCompositionDisplay.maxLuminance =
3362 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003363
Lloyd Pique441d5042018-10-18 16:49:51 -07003364 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003365 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003366 getHwComposer()
3367 .hasDisplayCapability(displayId,
3368 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003369
Peiyong Lind3788632018-09-18 16:01:31 -07003370 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003371 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3372 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003374 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003375 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003376
Mathias Agopian85d751c2012-08-29 16:59:24 -07003377 /*
3378 * and then, render the layers targeted at the framebuffer
3379 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003380
Dan Stoza9e56aa02015-11-02 13:00:03 -08003381 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003382 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003384 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003385 const Region viewportRegion(displayState.viewport);
3386 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003387 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003388 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003389 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003390 switch (layer->getCompositionType(displayDevice)) {
3391 case Hwc2::IComposerClient::Composition::CURSOR:
3392 case Hwc2::IComposerClient::Composition::DEVICE:
3393 case Hwc2::IComposerClient::Composition::SIDEBAND:
3394 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003395 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003396 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003397 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003398 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003399 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003400 // never clear the very first layer since we're
3401 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003402 renderengine::LayerSettings layerSettings;
3403 Region dummyRegion;
3404 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3405 layerSettings);
3406
3407 if (prepared) {
3408 layerSettings.source.buffer.buffer = nullptr;
3409 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3410 layerSettings.alpha = half(0.0);
3411 layerSettings.disableBlending = true;
3412 clientCompositionLayers.push_back(layerSettings);
3413 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003414 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003416 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003417 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003418 renderengine::LayerSettings layerSettings;
3419 bool prepared =
3420 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3421 if (prepared) {
3422 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003423 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003424 break;
3425 }
3426 default:
3427 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003428 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003429 } else {
3430 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003431 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003432 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003433 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003434
Alec Mouri820c7402019-01-23 13:02:39 -08003435 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003436 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003437 clientCompositionDisplay.clearRegion = clearRegion;
3438 if (!debugRegion.isEmpty()) {
3439 Region::const_iterator it = debugRegion.begin();
3440 Region::const_iterator end = debugRegion.end();
3441 while (it != end) {
3442 const Rect& rect = *it++;
3443 renderengine::LayerSettings layerSettings;
3444 layerSettings.source.buffer.buffer = nullptr;
3445 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3446 layerSettings.geometry.boundaries = rect.toFloatRect();
3447 layerSettings.alpha = half(1.0);
3448 clientCompositionLayers.push_back(layerSettings);
3449 }
3450 }
3451 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3452 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003453 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003454 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455}
3456
Chia-I Wu28e3a252018-09-07 12:05:02 -07003457void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003458 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003459 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460}
3461
Dan Stoza7d89d062015-04-30 13:29:25 -07003462status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003463 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003464 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003465 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003466 const sp<Layer>& parent,
3467 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003468{
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 // add this layer to the current state list
3470 {
3471 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003472 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003473 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3474 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003475 return NO_MEMORY;
3476 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003477 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003479 } else if (parent == nullptr) {
3480 lbc->onRemovedFromCurrentState();
3481 } else if (parent->isRemovedFromCurrentState()) {
3482 parent->addChild(lbc);
3483 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003484 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003485 parent->addChild(lbc);
3486 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003487
Yiwei Zhang243b3782018-05-15 17:40:04 -07003488 if (gbc != nullptr) {
3489 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3490 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3491 mMaxGraphicBufferProducerListSize,
3492 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3493 mGraphicBufferProducerList.size(),
3494 mMaxGraphicBufferProducerListSize, mNumLayers);
3495 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003496 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003497 }
3498
Mathias Agopian96f08192010-06-02 23:28:45 -07003499 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003500 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003501
Dan Stoza7d89d062015-04-30 13:29:25 -07003502 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003503}
3504
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003505uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003506 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003507}
3508
Mathias Agopian3f844832013-08-07 21:24:32 -07003509uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003510 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511}
3512
Mathias Agopian3f844832013-08-07 21:24:32 -07003513uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003514 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003515}
3516
3517uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003518 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003519 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003520 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003522 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 }
3524 return old;
3525}
3526
Marissa Wall713b63f2018-10-17 15:42:43 -07003527bool SurfaceFlinger::flushTransactionQueues() {
3528 Mutex::Autolock _l(mStateLock);
3529 auto it = mTransactionQueues.begin();
3530 while (it != mTransactionQueues.end()) {
3531 auto& [applyToken, transactionQueue] = *it;
3532
3533 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003534 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3535 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003536 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003537 break;
3538 }
Robert Carr14167e02019-02-13 13:50:55 -08003539 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003540 transactionQueue.pop();
3541 }
3542
3543 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3544 }
3545 return mTransactionQueues.empty();
3546}
3547
chaviwca27f252018-02-06 16:46:39 -08003548bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3549 for (const ComposerState& state : states) {
3550 // Here we need to check that the interface we're given is indeed
3551 // one of our own. A malicious client could give us a nullptr
3552 // IInterface, or one of its own or even one of our own but a
3553 // different type. All these situations would cause us to crash.
3554 if (state.client == nullptr) {
3555 return true;
3556 }
3557
3558 sp<IBinder> binder = IInterface::asBinder(state.client);
3559 if (binder == nullptr) {
3560 return true;
3561 }
3562
3563 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3564 return true;
3565 }
3566 }
3567 return false;
3568}
3569
Marissa Wall17b4e452018-12-26 16:32:34 -08003570bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3571 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003572 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3574 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3575 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3576 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3577 return false;
3578 }
3579
Marissa Wall713b63f2018-10-17 15:42:43 -07003580 for (const ComposerState& state : states) {
3581 const layer_state_t& s = state.state;
3582 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3583 continue;
3584 }
3585 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003586 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003587 }
3588 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003589 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003590}
3591
3592void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3593 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003594 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003595 const InputWindowCommands& inputWindowCommands,
3596 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003597 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003598
3599 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3600
Mathias Agopian698c0872011-06-28 19:09:31 -07003601 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003602
chaviwca27f252018-02-06 16:46:39 -08003603 if (containsAnyInvalidClientState(states)) {
3604 return;
3605 }
3606
Marissa Wall713b63f2018-10-17 15:42:43 -07003607 // If its TransactionQueue already has a pending TransactionState or if it is pending
3608 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003609 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003610 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3611 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003612 setTransactionFlags(eTransactionNeeded);
3613 return;
3614 }
3615
Robert Carr14167e02019-02-13 13:50:55 -08003616 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003617}
3618
3619void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003620 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003621 const InputWindowCommands& inputWindowCommands,
3622 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003623 uint32_t transactionFlags = 0;
3624
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003625 if (flags & eAnimation) {
3626 // For window updates that are part of an animation we must wait for
3627 // previous animation "frames" to be handled.
3628 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003629 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 if (CC_UNLIKELY(err != NO_ERROR)) {
3631 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003632 // caller after a few seconds.
3633 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3634 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003635 mAnimTransactionPending = false;
3636 break;
3637 }
3638 }
3639 }
3640
chaviwca27f252018-02-06 16:46:39 -08003641 for (const DisplayState& display : displays) {
3642 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003643 }
3644
Marissa Walle2ffb422018-10-12 11:33:52 -07003645 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003646 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003647 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003648 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003649 // If the state doesn't require a traversal and there are callbacks, send them now
3650 if (!(clientStateFlags & eTraversalNeeded)) {
3651 mTransactionCompletedThread.sendCallbacks();
3652 }
3653 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003654
chaviw273171b2018-12-26 11:46:30 -08003655 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3656
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003657 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3658 // anyway. This can be used as a flush mechanism for previous async transactions.
3659 // Empty animation transaction can be used to simulate back-pressure, so also force a
3660 // transaction for empty animation transactions.
3661 if (transactionFlags == 0 &&
3662 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003663 transactionFlags = eTransactionNeeded;
3664 }
3665
Mathias Agopian386aa982011-11-07 21:58:03 -08003666 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003667 if (mInterceptor->isEnabled()) {
3668 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003669 }
Irvel468051e2016-06-13 16:44:44 -07003670
Mathias Agopian386aa982011-11-07 21:58:03 -08003671 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003672 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3673 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003674 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003675
3676 // if this is a synchronous transaction, wait for it to take effect
3677 // before returning.
3678 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003679 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003681 if (flags & eAnimation) {
3682 mAnimTransactionPending = true;
3683 }
3684 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003685 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3686 if (CC_UNLIKELY(err != NO_ERROR)) {
3687 // just in case something goes wrong in SF, return to the
3688 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003689 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3690 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003691 break;
3692 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003693 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 }
3695}
3696
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003697uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3698 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3699 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003700
Mathias Agopiane57f2922012-08-09 16:29:12 -07003701 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003702 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3703
3704 const uint32_t what = s.what;
3705 if (what & DisplayState::eSurfaceChanged) {
3706 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3707 state.surface = s.surface;
3708 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003709 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003710 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003711 if (what & DisplayState::eLayerStackChanged) {
3712 if (state.layerStack != s.layerStack) {
3713 state.layerStack = s.layerStack;
3714 flags |= eDisplayTransactionNeeded;
3715 }
3716 }
3717 if (what & DisplayState::eDisplayProjectionChanged) {
3718 if (state.orientation != s.orientation) {
3719 state.orientation = s.orientation;
3720 flags |= eDisplayTransactionNeeded;
3721 }
3722 if (state.frame != s.frame) {
3723 state.frame = s.frame;
3724 flags |= eDisplayTransactionNeeded;
3725 }
3726 if (state.viewport != s.viewport) {
3727 state.viewport = s.viewport;
3728 flags |= eDisplayTransactionNeeded;
3729 }
3730 }
3731 if (what & DisplayState::eDisplaySizeChanged) {
3732 if (state.width != s.width) {
3733 state.width = s.width;
3734 flags |= eDisplayTransactionNeeded;
3735 }
3736 if (state.height != s.height) {
3737 state.height = s.height;
3738 flags |= eDisplayTransactionNeeded;
3739 }
3740 }
3741
Mathias Agopiane57f2922012-08-09 16:29:12 -07003742 return flags;
3743}
3744
Robert Carr14167e02019-02-13 13:50:55 -08003745bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003746 IPCThreadState* ipc = IPCThreadState::self();
3747 const int pid = ipc->getCallingPid();
3748 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003749 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003750 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003751 return false;
3752 }
3753 return true;
3754}
3755
Robert Carr14167e02019-02-13 13:50:55 -08003756uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3757 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003758 const layer_state_t& s = composerState.state;
3759 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3760
Mathias Agopian13127d82013-03-05 17:47:11 -08003761 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003762 if (layer == nullptr) {
3763 return 0;
3764 }
3765
chaviw8b3871a2017-11-01 17:41:01 -07003766 uint32_t flags = 0;
3767
Garfield Tan8a3083e2018-12-03 13:21:07 -08003768 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003769 bool geometryAppliesWithResize =
3770 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003771
3772 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3773 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003774 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003775 layer->pushPendingState();
3776 }
3777
chaviw8b3871a2017-11-01 17:41:01 -07003778 if (what & layer_state_t::ePositionChanged) {
3779 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3780 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003781 }
chaviw8b3871a2017-11-01 17:41:01 -07003782 }
3783 if (what & layer_state_t::eLayerChanged) {
3784 // NOTE: index needs to be calculated before we update the state
3785 const auto& p = layer->getParent();
3786 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003787 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003788 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003789 mCurrentState.layersSortedByZ.removeAt(idx);
3790 mCurrentState.layersSortedByZ.add(layer);
3791 // we need traversal (state changed)
3792 // AND transaction (list changed)
3793 flags |= eTransactionNeeded|eTraversalNeeded;
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 } else {
3796 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003797 flags |= eTransactionNeeded|eTraversalNeeded;
3798 }
3799 }
chaviw8b3871a2017-11-01 17:41:01 -07003800 }
3801 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003802 // NOTE: index needs to be calculated before we update the state
3803 const auto& p = layer->getParent();
3804 if (p == nullptr) {
3805 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3806 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3807 mCurrentState.layersSortedByZ.removeAt(idx);
3808 mCurrentState.layersSortedByZ.add(layer);
3809 // we need traversal (state changed)
3810 // AND transaction (list changed)
3811 flags |= eTransactionNeeded|eTraversalNeeded;
3812 }
3813 } else {
3814 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3815 flags |= eTransactionNeeded|eTraversalNeeded;
3816 }
chaviw8b3871a2017-11-01 17:41:01 -07003817 }
3818 }
3819 if (what & layer_state_t::eSizeChanged) {
3820 if (layer->setSize(s.w, s.h)) {
3821 flags |= eTraversalNeeded;
3822 }
3823 }
3824 if (what & layer_state_t::eAlphaChanged) {
3825 if (layer->setAlpha(s.alpha))
3826 flags |= eTraversalNeeded;
3827 }
3828 if (what & layer_state_t::eColorChanged) {
3829 if (layer->setColor(s.color))
3830 flags |= eTraversalNeeded;
3831 }
Peiyong Lind3788632018-09-18 16:01:31 -07003832 if (what & layer_state_t::eColorTransformChanged) {
3833 if (layer->setColorTransform(s.colorTransform)) {
3834 flags |= eTraversalNeeded;
3835 }
3836 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003837 if (what & layer_state_t::eBackgroundColorChanged) {
3838 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3839 flags |= eTraversalNeeded;
3840 }
3841 }
chaviw8b3871a2017-11-01 17:41:01 -07003842 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003843 // TODO: b/109894387
3844 //
3845 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3846 // rotation. To see the problem observe that if we have a square parent, and a child
3847 // of the same size, then we rotate the child 45 degrees around it's center, the child
3848 // must now be cropped to a non rectangular 8 sided region.
3849 //
3850 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3851 // private API, and the WindowManager only uses rotation in one case, which is on a top
3852 // level layer in which cropping is not an issue.
3853 //
3854 // However given that abuse of rotation matrices could lead to surfaces extending outside
3855 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3856 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3857 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003858 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003859 flags |= eTraversalNeeded;
3860 }
3861 if (what & layer_state_t::eTransparentRegionChanged) {
3862 if (layer->setTransparentRegionHint(s.transparentRegion))
3863 flags |= eTraversalNeeded;
3864 }
3865 if (what & layer_state_t::eFlagsChanged) {
3866 if (layer->setFlags(s.flags, s.mask))
3867 flags |= eTraversalNeeded;
3868 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003869 if (what & layer_state_t::eCropChanged_legacy) {
3870 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003871 flags |= eTraversalNeeded;
3872 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003873 if (what & layer_state_t::eCornerRadiusChanged) {
3874 if (layer->setCornerRadius(s.cornerRadius))
3875 flags |= eTraversalNeeded;
3876 }
chaviw8b3871a2017-11-01 17:41:01 -07003877 if (what & layer_state_t::eLayerStackChanged) {
3878 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3879 // We only allow setting layer stacks for top level layers,
3880 // everything else inherits layer stack from its parent.
3881 if (layer->hasParent()) {
3882 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3883 layer->getName().string());
3884 } else if (idx < 0) {
3885 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3886 "that also does not appear in the top level layer list. Something"
3887 " has gone wrong.", layer->getName().string());
3888 } else if (layer->setLayerStack(s.layerStack)) {
3889 mCurrentState.layersSortedByZ.removeAt(idx);
3890 mCurrentState.layersSortedByZ.add(layer);
3891 // we need traversal (state changed)
3892 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003893 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003894 }
3895 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003896 if (what & layer_state_t::eDeferTransaction_legacy) {
3897 if (s.barrierHandle_legacy != nullptr) {
3898 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3899 } else if (s.barrierGbp_legacy != nullptr) {
3900 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003901 if (authenticateSurfaceTextureLocked(gbp)) {
3902 const auto& otherLayer =
3903 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003904 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003905 } else {
3906 ALOGE("Attempt to defer transaction to to an"
3907 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003908 }
3909 }
chaviw8b3871a2017-11-01 17:41:01 -07003910 // We don't trigger a traversal here because if no other state is
3911 // changed, we don't want this to cause any more work
3912 }
3913 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003914 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003915 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003916 if (!hadParent) {
3917 mCurrentState.layersSortedByZ.remove(layer);
3918 }
chaviw8b3871a2017-11-01 17:41:01 -07003919 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003920 }
chaviw8b3871a2017-11-01 17:41:01 -07003921 }
3922 if (what & layer_state_t::eReparentChildren) {
3923 if (layer->reparentChildren(s.reparentHandle)) {
3924 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003925 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003926 }
chaviw8b3871a2017-11-01 17:41:01 -07003927 if (what & layer_state_t::eDetachChildren) {
3928 layer->detachChildren();
3929 }
3930 if (what & layer_state_t::eOverrideScalingModeChanged) {
3931 layer->setOverrideScalingMode(s.overrideScalingMode);
3932 // We don't trigger a traversal here because if no other state is
3933 // changed, we don't want this to cause any more work
3934 }
Marissa Wall61c58622018-07-18 10:12:20 -07003935 if (what & layer_state_t::eTransformChanged) {
3936 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3937 }
3938 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3939 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3940 flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eCropChanged) {
3943 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3944 }
Marissa Wall861616d2018-10-22 12:52:23 -07003945 if (what & layer_state_t::eFrameChanged) {
3946 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3947 }
Marissa Wall61c58622018-07-18 10:12:20 -07003948 if (what & layer_state_t::eAcquireFenceChanged) {
3949 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3950 }
3951 if (what & layer_state_t::eDataspaceChanged) {
3952 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eHdrMetadataChanged) {
3955 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3956 }
3957 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3958 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3959 }
3960 if (what & layer_state_t::eApiChanged) {
3961 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3962 }
3963 if (what & layer_state_t::eSidebandStreamChanged) {
3964 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3965 }
Robert Carr720e5062018-07-30 17:45:14 -07003966 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003967 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3968 layer->setInputInfo(s.inputInfo);
3969 flags |= eTraversalNeeded;
3970 } else {
3971 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3972 }
Robert Carr720e5062018-07-30 17:45:14 -07003973 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003974 if (what & layer_state_t::eMetadataChanged) {
3975 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3976 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003977 std::vector<sp<CallbackHandle>> callbackHandles;
3978 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3979 mTransactionCompletedThread.run();
3980 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3981 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3982 }
3983 }
Marissa Wall73411622019-01-25 10:45:41 -08003984
3985 if (what & layer_state_t::eBufferChanged) {
3986 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3987 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3988 s.buffer);
3989 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003990 if (what & layer_state_t::eCachedBufferChanged) {
3991 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003992 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3993 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003994 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3995 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003996 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3997 // Do not put anything that updates layer state or modifies flags after
3998 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003999 return flags;
4000}
4001
chaviw273171b2018-12-26 11:46:30 -08004002uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4003 uint32_t flags = 0;
4004 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4005 flags |= eTraversalNeeded;
4006 }
4007
chaviwa911b102019-02-14 10:18:33 -08004008 if (inputWindowCommands.syncInputWindows) {
4009 flags |= eTraversalNeeded;
4010 }
4011
Vishnu Nairec0ab382019-02-13 15:32:56 -08004012 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004013 return flags;
4014}
4015
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004016status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4017 uint32_t h, PixelFormat format, uint32_t flags,
4018 LayerMetadata metadata, sp<IBinder>* handle,
4019 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004020 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004021 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004022 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004023 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004024 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004025
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004026 status_t result = NO_ERROR;
4027
4028 sp<Layer> layer;
4029
Cody Northropbc755282017-03-31 12:00:08 -06004030 String8 uniqueName = getUniqueLayerName(name);
4031
Mathias Agopian3165cc22012-08-08 19:42:09 -07004032 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004033 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004034 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4035 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004038 case ISurfaceComposerClient::eFXSurfaceBufferState:
4039 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4040 break;
chaviw13fdc492017-06-27 12:40:18 -07004041 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004042 // check if buffer size is set for color layer.
4043 if (w > 0 || h > 0) {
4044 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4045 int(w), int(h));
4046 return BAD_VALUE;
4047 }
4048
chaviw13fdc492017-06-27 12:40:18 -07004049 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004050 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004051 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004052 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004053 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004054 // check if buffer size is set for container layer.
4055 if (w > 0 || h > 0) {
4056 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4057 int(w), int(h));
4058 return BAD_VALUE;
4059 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004060 result = createContainerLayer(client,
4061 uniqueName, w, h, flags,
4062 handle, &layer);
4063 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004064 default:
4065 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 break;
4067 }
4068
Dan Stoza7d89d062015-04-30 13:29:25 -07004069 if (result != NO_ERROR) {
4070 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004071 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004072
Chia-I Wuab0c3192017-08-01 11:29:00 -07004073 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4074 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004075 if (metadata.has(METADATA_WINDOW_TYPE)) {
4076 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4077 if (windowType == 441731) {
4078 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4079 layer->setPrimaryDisplayOnly();
4080 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004081 }
4082
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004083 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004084
Robert Carrb89ea9d2018-12-10 13:01:14 -08004085 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4086 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4087 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004088 if (result != NO_ERROR) {
4089 return result;
4090 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004091 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004092
4093 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004094 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004095}
4096
Cody Northropbc755282017-03-31 12:00:08 -06004097String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4098{
4099 bool matchFound = true;
4100 uint32_t dupeCounter = 0;
4101
4102 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4103 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4104
Dan Stoza436ccf32018-06-21 12:10:12 -07004105 // Grab the state lock since we're accessing mCurrentState
4106 Mutex::Autolock lock(mStateLock);
4107
Cody Northropbc755282017-03-31 12:00:08 -06004108 // Loop over layers until we're sure there is no matching name
4109 while (matchFound) {
4110 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004111 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004112 if (layer->getName() == uniqueName) {
4113 matchFound = true;
4114 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4115 }
4116 });
4117 }
4118
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004119 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4120 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004121
4122 return uniqueName;
4123}
4124
Marissa Wallfd668622018-05-10 10:21:13 -07004125status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4126 uint32_t w, uint32_t h, uint32_t flags,
4127 PixelFormat& format, sp<IBinder>* handle,
4128 sp<IGraphicBufferProducer>* gbp,
4129 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004131 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132 case PIXEL_FORMAT_TRANSPARENT:
4133 case PIXEL_FORMAT_TRANSLUCENT:
4134 format = PIXEL_FORMAT_RGBA_8888;
4135 break;
4136 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004137 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004138 break;
4139 }
4140
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004141 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004142 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004143 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004144 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004145 *handle = layer->getHandle();
4146 *gbp = layer->getProducer();
4147 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004149
Marissa Wallfd668622018-05-10 10:21:13 -07004150 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004151 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004152}
4153
Marissa Wall61c58622018-07-18 10:12:20 -07004154status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4155 uint32_t w, uint32_t h, uint32_t flags,
4156 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004157 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004158 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004159 *handle = layer->getHandle();
4160 *outLayer = layer;
4161
4162 return NO_ERROR;
4163}
4164
chaviw13fdc492017-06-27 12:40:18 -07004165status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004166 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004167 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004168{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004169 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004170 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004171 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004172}
4173
Robert Carr6b3f6c52018-08-13 13:05:17 -07004174status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4175 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4176 sp<IBinder>* handle, sp<Layer>* outLayer)
4177{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004178 *outLayer =
4179 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004180 *handle = (*outLayer)->getHandle();
4181 return NO_ERROR;
4182}
4183
4184
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004185void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004186 mLayersPendingRemoval.add(layer);
4187 mLayersRemoved = true;
4188 setTransactionFlags(eTransactionNeeded);
4189}
4190
Robert Carr695d5282018-12-18 15:27:58 -08004191void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004192{
Robert Carr2e102c92018-10-23 12:11:15 -07004193 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004194 // If a layer has a parent, we allow it to out-live it's handle
4195 // with the idea that the parent holds a reference and will eventually
4196 // be cleaned up. However no one cleans up the top-level so we do so
4197 // here.
4198 if (layer->getParent() == nullptr) {
4199 mCurrentState.layersSortedByZ.remove(layer);
4200 }
4201 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004202 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004203}
4204
Mathias Agopianb60314a2012-04-10 22:09:54 -07004205// ---------------------------------------------------------------------------
4206
Andy McFadden13a082e2012-08-24 10:16:42 -07004207void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004208 const auto display = getDefaultDisplayDeviceLocked();
4209 if (!display) return;
4210
4211 const sp<IBinder> token = display->getDisplayToken().promote();
4212 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004213
Jesse Hall01e29052013-02-19 16:13:35 -08004214 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004215 Vector<ComposerState> state;
4216 Vector<DisplayState> displays;
4217 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004218 d.what = DisplayState::eDisplayProjectionChanged |
4219 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004220 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004221 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004222 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004223 d.frame.makeInvalid();
4224 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004225 d.width = 0;
4226 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004227 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004228 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004229
Dominik Laskowskie9774092018-12-11 10:04:24 -08004230 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004231
Dominik Laskowski83b88212018-12-11 13:34:06 -08004232 const nsecs_t vsyncPeriod = getVsyncPeriod();
4233 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004234
Brian Andersond0010582017-03-07 13:20:31 -08004235 // Use phase of 0 since phase is not known.
4236 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004237 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004238 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004239}
4240
4241void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004242 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004243 postMessageAsync(
4244 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004245}
4246
Dominik Laskowskie9774092018-12-11 10:04:24 -08004247void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004248 if (display->isVirtual()) {
4249 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004250 return;
4251 }
4252
Dominik Laskowski075d3172018-05-24 15:50:06 -07004253 const auto displayId = display->getId();
4254 LOG_ALWAYS_FATAL_IF(!displayId);
4255
Dominik Laskowski34157762018-10-31 13:07:19 -07004256 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004257
4258 int currentMode = display->getPowerMode();
4259 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004260 return;
4261 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004262
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004263 display->setPowerMode(mode);
4264
Lloyd Pique4dccc412018-01-22 17:21:36 -08004265 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004266 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004267 }
4268
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004269 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004270 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004271 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004272 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004273 mScheduler->onScreenAcquired(mAppConnectionHandle);
4274 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004275 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004276
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004278 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004279 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004280
4281 struct sched_param param = {0};
4282 param.sched_priority = 1;
4283 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4284 ALOGW("Couldn't set SCHED_FIFO on display on");
4285 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004286 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004287 // Turn off the display
4288 struct sched_param param = {0};
4289 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4290 ALOGW("Couldn't set SCHED_OTHER on display off");
4291 }
4292
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004294 mScheduler->disableHardwareVsync(true);
4295 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004296 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004297
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004299 mVisibleRegionsDirty = true;
4300 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004301 } else if (mode == HWC_POWER_MODE_DOZE ||
4302 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004303 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004304 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004305 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004306 mScheduler->onScreenAcquired(mAppConnectionHandle);
4307 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004308 }
4309 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4310 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004311 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004312 mScheduler->disableHardwareVsync(true);
4313 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004314 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004315 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004316 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004317 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004318 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004319 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004320
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004321 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004322 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004323 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004324 // Update refresh rate stats.
4325 mRefreshRateStats->setPowerMode(mode);
4326 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004327 }
4328
Dominik Laskowski34157762018-10-31 13:07:19 -07004329 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004330}
4331
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004332void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004333 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004334 const auto display = getDisplayDevice(displayToken);
4335 if (!display) {
4336 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4337 displayToken.get());
4338 } else if (display->isVirtual()) {
4339 ALOGW("Attempt to set power mode %d for virtual display", mode);
4340 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004341 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004342 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004343 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004344}
4345
4346// ---------------------------------------------------------------------------
4347
Dominik Laskowskic2867142019-01-21 11:33:38 -08004348status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4349 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004351
Mathias Agopianbd115332013-04-18 16:41:04 -07004352 IPCThreadState* ipc = IPCThreadState::self();
4353 const int pid = ipc->getCallingPid();
4354 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004355
Mathias Agopianbd115332013-04-18 16:41:04 -07004356 if ((uid != AID_SHELL) &&
4357 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4359 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004361 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004362 // (this would indicate SF is stuck, but we want to be able to
4363 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004364 status_t err = mStateLock.timedLock(s2ns(1));
4365 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004366 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004367 StringAppendF(&result,
4368 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4369 "(no locks held)\n",
4370 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004371 }
4372
Dominik Laskowskic2867142019-01-21 11:33:38 -08004373 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004374
Dominik Laskowskic2867142019-01-21 11:33:38 -08004375 static const std::unordered_map<std::string, Dumper> dumpers = {
4376 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4377 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4378 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004379 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004380 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004381 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004382 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4383 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004384 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4385 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4386 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4387 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4388 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4389 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004390 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004391 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4392 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004393
Dominik Laskowskic2867142019-01-21 11:33:38 -08004394 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004395
Dominik Laskowskic2867142019-01-21 11:33:38 -08004396 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4397 (it->second)(args, asProto, result);
4398 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004399 if (asProto) {
4400 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4401 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4402 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004403 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004404 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004405 }
4406
Mathias Agopian9795c422009-08-26 16:36:26 -07004407 if (locked) {
4408 mStateLock.unlock();
4409 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004410 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004412 return NO_ERROR;
4413}
4414
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416 mCurrentState.traverseInZOrder(
4417 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004418}
4419
Dominik Laskowskic2867142019-01-21 11:33:38 -08004420void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004421 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004422
Dominik Laskowskic2867142019-01-21 11:33:38 -08004423 if (args.size() > 1) {
4424 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004425 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004426 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004427 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004428 }
Robert Carr2047fae2016-11-28 14:09:09 -08004429 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004430 } else {
4431 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004432 }
4433}
4434
Dominik Laskowskic2867142019-01-21 11:33:38 -08004435void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004436 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004437 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004438 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004439 }
Robert Carr2047fae2016-11-28 14:09:09 -08004440 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004441
Svetoslavd85084b2014-03-20 10:28:31 -07004442 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004443}
4444
Dominik Laskowskic2867142019-01-21 11:33:38 -08004445void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4446 mTimeStats->parseArgs(asProto, args, result);
4447}
4448
Jamie Gennis6547ff42013-07-16 20:12:42 -07004449// This should only be called from the main thread. Otherwise it would need
4450// the lock and should use mCurrentState rather than mDrawingState.
4451void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004452 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004453 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004454 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004455
4456 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4457}
4458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004460 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004461
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004462 if (isLayerTripleBufferingDisabled())
4463 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004464
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4466 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4467 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4468 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4469 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4470 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004471 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004472}
4473
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004474void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004475 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004476 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004477 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004478 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004479
Ana Krulecba13ab32019-02-20 14:14:12 -08004480 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4481 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4482 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004483 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004484}
4485
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4487 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004488 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4489 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004490 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004491 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004493 }
David Sodman4a36e932017-11-07 14:29:47 -08004494 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004495 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004496 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004497 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4498 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004499}
4500
Dan Stozae77c7662016-05-13 11:37:28 -07004501void SurfaceFlinger::recordBufferingStats(const char* layerName,
4502 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004503 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4504 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004505 for (const auto& segment : history) {
4506 if (!segment.usedThirdBuffer) {
4507 stats.twoBufferTime += segment.totalTime;
4508 }
4509 if (segment.occupancyAverage < 1.0f) {
4510 stats.doubleBufferedTime += segment.totalTime;
4511 } else if (segment.occupancyAverage < 2.0f) {
4512 stats.tripleBufferedTime += segment.totalTime;
4513 }
4514 ++stats.numSegments;
4515 stats.totalTime += segment.totalTime;
4516 }
4517}
4518
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4520 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004521
4522 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4523 const size_t count = currentLayers.size();
4524 for (size_t i=0 ; i<count ; i++) {
4525 currentLayers[i]->dumpFrameEvents(result);
4526 }
4527}
4528
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004530 result.append("Buffering stats:\n");
4531 result.append(" [Layer name] <Active time> <Two buffer> "
4532 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004533 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004534 typedef std::tuple<std::string, float, float, float> BufferTuple;
4535 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004536 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004537 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004538 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004539 if (stats.numSegments == 0) {
4540 continue;
4541 }
4542 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4543 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4544 stats.totalTime;
4545 float doubleBufferRatio = static_cast<float>(
4546 stats.doubleBufferedTime) / stats.totalTime;
4547 float tripleBufferRatio = static_cast<float>(
4548 stats.tripleBufferedTime) / stats.totalTime;
4549 sorted.insert({activeTime, {name, twoBufferRatio,
4550 doubleBufferRatio, tripleBufferRatio}});
4551 }
4552 for (const auto& sortedPair : sorted) {
4553 float activeTime = sortedPair.first;
4554 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4556 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004557 }
4558 result.append("\n");
4559}
4560
Yiwei Zhang5434a782018-12-05 18:06:32 -08004561void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004562 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004563 const auto displayId = display->getId();
4564 if (!displayId) {
4565 continue;
4566 }
4567 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004568 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004569 continue;
4570 }
4571
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572 StringAppendF(&result,
4573 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4574 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004575 uint8_t port;
4576 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004577 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004578 result.append("no identification data\n");
4579 continue;
4580 }
4581
4582 if (!isEdid(data)) {
4583 result.append("unknown identification data: ");
4584 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004585 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004586 }
4587 result.append("\n");
4588 continue;
4589 }
4590
4591 const auto edid = parseEdid(data);
4592 if (!edid) {
4593 result.append("invalid EDID: ");
4594 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004596 }
4597 result.append("\n");
4598 continue;
4599 }
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004602 result.append(edid->displayName.data(), edid->displayName.length());
4603 result.append("\"\n");
4604 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004605}
4606
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4608 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4609 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4610 StringAppendF(&result, "DisplayColorSetting: %s\n",
4611 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004612
4613 // TODO: print out if wide-color mode is active or not
4614
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004615 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004616 const auto displayId = display->getId();
4617 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004618 continue;
4619 }
4620
Yiwei Zhang5434a782018-12-05 18:06:32 -08004621 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004622 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004623 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004625 }
4626
Lloyd Pique32cbe282018-10-19 13:09:22 -07004627 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 StringAppendF(&result, " Current color mode: %s (%d)\n",
4629 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630 }
4631 result.append("\n");
4632}
4633
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004634LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004635 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004636 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4637 const State& state = useDrawing ? mDrawingState : mCurrentState;
4638 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004639 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004640 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004641 });
4642
4643 return layersProto;
4644}
4645
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004646LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4647 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004648 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004649
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004650 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004651 resolution->set_w(displayDevice->getWidth());
4652 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004653
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004654 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004655 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004656
Lloyd Pique32cbe282018-10-19 13:09:22 -07004657 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4658 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4659 layersProto.set_global_transform(displayState.orientation);
4660
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004661 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004662 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004663 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004664 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004665 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004666 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004667 }
4668 });
4669
4670 return layersProto;
4671}
4672
Dominik Laskowskic2867142019-01-21 11:33:38 -08004673void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4674 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 Colorizer colorizer(colorize);
4676
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004677 // figure out if we're stuck somewhere
4678 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004679 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4681
4682 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004683 * Dump library configuration.
4684 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004685
4686 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004687 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004688 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004689 appendSfConfigString(result);
4690 appendUiConfigString(result);
4691 appendGuiConfigString(result);
4692 result.append("\n");
4693
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004694 result.append("\nDisplay identification data:\n");
4695 dumpDisplayIdentificationData(result);
4696
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004697 result.append("\nWide-Color information:\n");
4698 dumpWideColorInfo(result);
4699
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004701 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004703 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004704 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004705
Andy McFadden41d67d72014-04-25 16:58:34 -07004706 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004707 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004708 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004709 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004710 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004711
Dan Stozab90cf072015-03-05 11:05:59 -08004712 dumpStaticScreenStats(result);
4713 result.append("\n");
4714
Yiwei Zhang5434a782018-12-05 18:06:32 -08004715 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004716
Dan Stozae77c7662016-05-13 11:37:28 -07004717 dumpBufferingStats(result);
4718
Andy McFadden4803b742012-09-24 19:07:20 -07004719 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004720 * Dump the visible layer list
4721 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004722 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004723 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4724 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4725 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004726 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004727
Chia-I Wu2f884132018-09-13 15:17:58 -07004728 {
4729 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4730 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004731 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004732 result.append("\n");
4733 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734
4735 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004736 * Dump Display state
4737 */
4738
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004739 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004741 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004742 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004743 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004744 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004745 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004746
4747 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004748 * Dump SurfaceFlinger global state
4749 */
4750
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004751 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004752 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004753 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004754
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004755 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
Dominik Laskowski075d3172018-05-24 15:50:06 -07004757 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004758 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4759 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004760 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4761 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004762 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result,
4764 " transaction-flags : %08x\n"
4765 " gpu_to_cpu_unsupported : %d\n",
4766 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004767
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004768 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004769 displayId && getHwComposer().isConnected(*displayId)) {
4770 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004771 StringAppendF(&result,
4772 " refresh-rate : %f fps\n"
4773 " x-dpi : %f\n"
4774 " y-dpi : %f\n",
4775 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4776 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004777 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780
Dan Stozae22aec72016-08-01 13:20:59 -07004781 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004782 * Tracing state
4783 */
4784 mTracing.dump(result);
4785 result.append("\n");
4786
4787 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004788 * HWC layer minidump
4789 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004790 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004791 const auto displayId = display->getId();
4792 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004793 continue;
4794 }
4795
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004797 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004798 const sp<DisplayDevice> displayDevice = display;
4799 mCurrentState.traverseInZOrder(
4800 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004801 result.append("\n");
4802 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803
4804 /*
4805 * Dump HWComposer state
4806 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004807 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004808 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004809 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004810 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004812 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004813
4814 /*
4815 * Dump gralloc state
4816 */
4817 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4818 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004819
4820 /*
4821 * Dump VrFlinger state if in use.
4822 */
4823 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4824 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004826 result.append("\n");
4827 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004828
4829 /**
4830 * Scheduler dump state.
4831 */
Ana Krulecc2870422019-01-29 19:00:58 -08004832 result.append("\nScheduler state:\n");
4833 result.append(mScheduler->doDump() + "\n");
4834 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835}
4836
Dominik Laskowski075d3172018-05-24 15:50:06 -07004837const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004838 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004839 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004840 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004841 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004842 }
4843 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004844
Dominik Laskowski34157762018-10-31 13:07:19 -07004845 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004846 static const Vector<sp<Layer>> empty;
4847 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004848}
4849
Chia-I Wu28f320b2018-05-03 11:02:56 -07004850void SurfaceFlinger::updateColorMatrixLocked() {
4851 mat4 colorMatrix;
4852 if (mGlobalSaturationFactor != 1.0f) {
4853 // Rec.709 luma coefficients
4854 float3 luminance{0.213f, 0.715f, 0.072f};
4855 luminance *= 1.0f - mGlobalSaturationFactor;
4856 mat4 saturationMatrix = mat4(
4857 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4858 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4859 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4860 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4861 );
4862 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4863 } else {
4864 colorMatrix = mClientColorMatrix * mDaltonizer();
4865 }
4866
4867 if (mCurrentState.colorMatrix != colorMatrix) {
4868 mCurrentState.colorMatrix = colorMatrix;
4869 mCurrentState.colorMatrixChanged = true;
4870 setTransactionFlags(eTransactionNeeded);
4871 }
4872}
4873
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004874status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004875#pragma clang diagnostic push
4876#pragma clang diagnostic error "-Wswitch-enum"
4877 switch (static_cast<ISurfaceComposerTag>(code)) {
4878 // These methods should at minimum make sure that the client requested
4879 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004880 case BOOT_FINISHED:
4881 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882 case CREATE_DISPLAY:
4883 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004884 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 case GET_ACTIVE_COLOR_MODE:
4886 case GET_ANIMATION_FRAME_STATS:
4887 case GET_HDR_CAPABILITIES:
4888 case SET_ACTIVE_CONFIG:
4889 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004890 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004891 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004892 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004893 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4894 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004895 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4896 IPCThreadState* ipc = IPCThreadState::self();
4897 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4898 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004899 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004900 }
Robert Carr1db73f62016-12-21 12:58:51 -08004901 return OK;
4902 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004903 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004904 IPCThreadState* ipc = IPCThreadState::self();
4905 const int pid = ipc->getCallingPid();
4906 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4908 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004909 return PERMISSION_DENIED;
4910 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004911 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004913 // Used by apps to hook Choreographer to SurfaceFlinger.
4914 case CREATE_DISPLAY_EVENT_CONNECTION:
4915 // The following calls are currently used by clients that do not
4916 // request necessary permissions. However, they do not expose any secret
4917 // information, so it is OK to pass them.
4918 case AUTHENTICATE_SURFACE:
4919 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004920 case GET_PHYSICAL_DISPLAY_IDS:
4921 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004923 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004924 case GET_DISPLAY_CONFIGS:
4925 case GET_DISPLAY_STATS:
4926 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4927 // Calling setTransactionState is safe, because you need to have been
4928 // granted a reference to Client* and Handle* to do anything with it.
4929 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004930 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004931 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004932 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004933 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004934 case IS_WIDE_COLOR_DISPLAY:
4935 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 return OK;
4937 }
4938 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004939 case CAPTURE_SCREEN:
4940 case ADD_REGION_SAMPLING_LISTENER:
4941 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004943 IPCThreadState* ipc = IPCThreadState::self();
4944 const int pid = ipc->getCallingPid();
4945 const int uid = ipc->getCallingUid();
4946 if ((uid != AID_GRAPHICS) &&
4947 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4948 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4949 return PERMISSION_DENIED;
4950 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004951 return OK;
4952 }
4953 // The following codes are deprecated and should never be allowed to access SF.
4954 case CONNECT_DISPLAY_UNUSED:
4955 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4956 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4957 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004958 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004959 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960
4961 // These codes are used for the IBinder protocol to either interrogate the recipient
4962 // side of the transaction for its canonical interface descriptor or to dump its state.
4963 // We let them pass by default.
4964 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4965 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4966 code == IBinder::SYSPROPS_TRANSACTION) {
4967 return OK;
4968 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004969 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004971 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004972 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4973 return OK;
4974 }
4975 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4976 return PERMISSION_DENIED;
4977#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004978}
4979
Ana Krulec13be8ad2018-08-21 02:43:56 +00004980status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4981 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004982 status_t credentialCheck = CheckTransactCodeCredentials(code);
4983 if (credentialCheck != OK) {
4984 return credentialCheck;
4985 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004986
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4988 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004989 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004990 IPCThreadState* ipc = IPCThreadState::self();
4991 const int uid = ipc->getCallingUid();
4992 if (CC_UNLIKELY(uid != AID_SYSTEM
4993 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004994 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004995 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004996 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004997 return PERMISSION_DENIED;
4998 }
4999 int n;
5000 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005001 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005002 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return NO_ERROR;
5004 case 1002: // SHOW_UPDATES
5005 n = data.readInt32();
5006 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005007 invalidateHwcGeometry();
5008 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005010 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005011 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005012 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005013 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005014 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005015 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005016 setTransactionFlags(
5017 eTransactionNeeded|
5018 eDisplayTransactionNeeded|
5019 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005020 return NO_ERROR;
5021 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005022 case 1006:{ // send empty update
5023 signalRefresh();
5024 return NO_ERROR;
5025 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005026 case 1008: // toggle use of hw composer
5027 n = data.readInt32();
5028 mDebugDisableHWC = n ? 1 : 0;
5029 invalidateHwcGeometry();
5030 repaintEverything();
5031 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005032 case 1009: // toggle use of transform hint
5033 n = data.readInt32();
5034 mDebugDisableTransformHint = n ? 1 : 0;
5035 invalidateHwcGeometry();
5036 repaintEverything();
5037 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005038 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005039 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005040 reply->writeInt32(0);
5041 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005042 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005043 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 return NO_ERROR;
5045 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005046 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005047 if (!display) {
5048 return NAME_NOT_FOUND;
5049 }
5050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005051 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005052 return NO_ERROR;
5053 }
5054 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005055 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005056 // daltonize
5057 n = data.readInt32();
5058 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005059 case 1:
5060 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5061 break;
5062 case 2:
5063 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5064 break;
5065 case 3:
5066 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5067 break;
5068 default:
5069 mDaltonizer.setType(ColorBlindnessType::None);
5070 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005071 }
5072 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005073 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005074 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005075 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005076 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005077
5078 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005079 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005080 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005081 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005082 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005083 // apply a color matrix
5084 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005085 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005086 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005087 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005088 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005089 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005090 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005091 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005092 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005093 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005094 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005095
5096 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5097 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005098 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005099 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5100 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5101 }
5102
Chia-I Wu28f320b2018-05-03 11:02:56 -07005103 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005104 return NO_ERROR;
5105 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005106 // This is an experimental interface
5107 // Needs to be shifted to proper binder interface when we productize
5108 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005109 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005110 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005111 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005112 return NO_ERROR;
5113 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005114 case 1017: {
5115 n = data.readInt32();
5116 mForceFullDamage = static_cast<bool>(n);
5117 return NO_ERROR;
5118 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005119 case 1018: { // Modify Choreographer's phase offset
5120 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005121 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005122 return NO_ERROR;
5123 }
5124 case 1019: { // Modify SurfaceFlinger's phase offset
5125 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005126 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005127 return NO_ERROR;
5128 }
Irvel468051e2016-06-13 16:44:44 -07005129 case 1020: { // Layer updates interceptor
5130 n = data.readInt32();
5131 if (n) {
5132 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005133 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005134 }
5135 else{
5136 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005137 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005138 }
5139 return NO_ERROR;
5140 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005141 case 1021: { // Disable HWC virtual displays
5142 n = data.readInt32();
5143 mUseHwcVirtualDisplays = !n;
5144 return NO_ERROR;
5145 }
Romain Guy0147a172017-06-01 13:53:56 -07005146 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005147 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005148 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005149
Chia-I Wu28f320b2018-05-03 11:02:56 -07005150 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005151 return NO_ERROR;
5152 }
Romain Guy54f154a2017-10-24 21:40:32 +01005153 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005154 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005155 invalidateHwcGeometry();
5156 repaintEverything();
5157 return NO_ERROR;
5158 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005159 // Deprecate, use 1030 to check whether the device is color managed.
5160 case 1024: {
5161 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005162 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005163 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005164 n = data.readInt32();
5165 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005166 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005167 mTracing.enable();
5168 doTracing("tracing.enable");
5169 reply->writeInt32(NO_ERROR);
5170 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005171 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005172 status_t err = mTracing.disable();
5173 reply->writeInt32(err);
5174 }
5175 return NO_ERROR;
5176 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005177 case 1026: { // Get layer tracing status
5178 reply->writeBool(mTracing.isEnabled());
5179 return NO_ERROR;
5180 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005181 // Is a DisplayColorSetting supported?
5182 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005183 const auto display = getDefaultDisplayDevice();
5184 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005185 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005186 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005187
5188 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5189 switch (setting) {
5190 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005191 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005192 break;
5193 case DisplayColorSetting::UNMANAGED:
5194 reply->writeBool(true);
5195 break;
5196 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005197 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005198 break;
5199 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005200 reply->writeBool(
5201 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005202 break;
5203 }
5204 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005205 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005206 // Is VrFlinger active?
5207 case 1028: {
5208 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005209 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005210 return NO_ERROR;
5211 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005212 // Is device color managed?
5213 case 1030: {
5214 reply->writeBool(useColorManagement);
5215 return NO_ERROR;
5216 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005217 // Override default composition data space
5218 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5219 // && adb shell stop zygote && adb shell start zygote
5220 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5221 // adb shell stop zygote && adb shell start zygote
5222 case 1031: {
5223 Mutex::Autolock _l(mStateLock);
5224 n = data.readInt32();
5225 if (n) {
5226 n = data.readInt32();
5227 if (n) {
5228 Dataspace dataspace = static_cast<Dataspace>(n);
5229 if (!validateCompositionDataspace(dataspace)) {
5230 return BAD_VALUE;
5231 }
5232 mDefaultCompositionDataspace = dataspace;
5233 }
5234 n = data.readInt32();
5235 if (n) {
5236 Dataspace dataspace = static_cast<Dataspace>(n);
5237 if (!validateCompositionDataspace(dataspace)) {
5238 return BAD_VALUE;
5239 }
5240 mWideColorGamutCompositionDataspace = dataspace;
5241 }
5242 } else {
5243 // restore composition data space.
5244 mDefaultCompositionDataspace = defaultCompositionDataspace;
5245 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5246 }
5247 return NO_ERROR;
5248 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005249 }
5250 }
5251 return err;
5252}
5253
Steven Thomas6d8110b2017-08-31 18:24:21 -07005254void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005255 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005256 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005257}
5258
Ana Krulec7d1d6832018-12-27 11:10:09 -08005259void SurfaceFlinger::repaintEverythingForHWC() {
5260 mRepaintEverything = true;
5261 mEventQueue->invalidateForHWC();
5262}
5263
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005264// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5265class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005266public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5268 ~WindowDisconnector() {
5269 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005270 }
5271
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005272private:
5273 ANativeWindow* mWindow;
5274 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005275};
5276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005277status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005278 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5279 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005280 uint32_t reqWidth, uint32_t reqHeight,
5281 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005282 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005283 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005285 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005286
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005287 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5288
Chia-I Wu20261cb2018-08-23 12:55:44 -07005289 sp<DisplayDevice> display;
5290 {
5291 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005292
Chia-I Wu20261cb2018-08-23 12:55:44 -07005293 display = getDisplayDeviceLocked(displayToken);
5294 if (!display) return BAD_VALUE;
5295
Chia-I Wucb023152018-08-28 12:57:23 -07005296 // set the requested width/height to the logical display viewport size
5297 // by default
5298 if (reqWidth == 0 || reqHeight == 0) {
5299 reqWidth = uint32_t(display->getViewport().width());
5300 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005301 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005302 }
5303
Peiyong Lin0e003c92018-09-17 11:09:51 -07005304 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5305 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005306
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005307 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5308 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005309 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5310 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005311}
5312
5313status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005314 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5315 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005316 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005317 ATRACE_CALL();
5318
5319 class LayerRenderArea : public RenderArea {
5320 public:
Robert Carr578038f2018-03-09 12:25:24 -08005321 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005322 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5323 bool childrenOnly)
5324 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005325 mLayer(layer),
5326 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005327 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005328 mFlinger(flinger),
5329 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005330 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005331 Rect getBounds() const override {
5332 const Layer::State& layerState(mLayer->getDrawingState());
5333 return mLayer->getBufferSize(layerState);
5334 }
Marissa Wall61c58622018-07-18 10:12:20 -07005335 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005336 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005337 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005338 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005339 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005340 }
chaviwa76b2712017-09-20 12:02:26 -07005341 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005342 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005343 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005344 Rect getSourceCrop() const override {
5345 if (mCrop.isEmpty()) {
5346 return getBounds();
5347 } else {
5348 return mCrop;
5349 }
5350 }
Robert Carr578038f2018-03-09 12:25:24 -08005351 class ReparentForDrawing {
5352 public:
5353 const sp<Layer>& oldParent;
5354 const sp<Layer>& newParent;
5355
Vishnu Nair4351ad52019-02-11 14:13:02 -08005356 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5357 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005358 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005359 // Compute and cache the bounds for the new parent layer.
5360 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005361 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005362 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005363 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005364 };
5365
5366 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005367 const Rect sourceCrop = getSourceCrop();
5368 // no need to check rotation because there is none
5369 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5370 sourceCrop.height() != getReqHeight();
5371
Robert Carr578038f2018-03-09 12:25:24 -08005372 if (!mChildrenOnly) {
5373 mTransform = mLayer->getTransform().inverse();
5374 drawLayers();
5375 } else {
5376 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005377 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005378 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5379 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005380
Vishnu Nair4351ad52019-02-11 14:13:02 -08005381 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005382 drawLayers();
5383 }
5384 }
chaviwa76b2712017-09-20 12:02:26 -07005385
chaviwa76b2712017-09-20 12:02:26 -07005386 private:
chaviw7206d492017-11-10 16:16:12 -08005387 const sp<Layer> mLayer;
5388 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005389
5390 // In the "childrenOnly" case we reparent the children to a screenshot
5391 // layer which has no properties set and which does not draw.
5392 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005393 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005394 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005395
5396 SurfaceFlinger* mFlinger;
5397 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005398 };
5399
5400 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5401 auto parent = layerHandle->owner.promote();
5402
Robert Carr2e102c92018-10-23 12:11:15 -07005403 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005404 ALOGE("captureLayers called with a removed parent");
5405 return NAME_NOT_FOUND;
5406 }
5407
Robert Carr578038f2018-03-09 12:25:24 -08005408 const int uid = IPCThreadState::self()->getCallingUid();
5409 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005410 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005411 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5412 return PERMISSION_DENIED;
5413 }
5414
chaviw7206d492017-11-10 16:16:12 -08005415 Rect crop(sourceCrop);
5416 if (sourceCrop.width() <= 0) {
5417 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005418 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005419 }
5420
5421 if (sourceCrop.height() <= 0) {
5422 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005423 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005424 }
5425
5426 int32_t reqWidth = crop.width() * frameScale;
5427 int32_t reqHeight = crop.height() * frameScale;
5428
Chia-I Wu20261cb2018-08-23 12:55:44 -07005429 // really small crop or frameScale
5430 if (reqWidth <= 0) {
5431 reqWidth = 1;
5432 }
5433 if (reqHeight <= 0) {
5434 reqHeight = 1;
5435 }
5436
Peiyong Lin0e003c92018-09-17 11:09:51 -07005437 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005438
Robert Carr578038f2018-03-09 12:25:24 -08005439 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005440 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5441 if (!layer->isVisible()) {
5442 return;
Robert Carr578038f2018-03-09 12:25:24 -08005443 } else if (childrenOnly && layer == parent.get()) {
5444 return;
chaviwa76b2712017-09-20 12:02:26 -07005445 }
5446 visitor(layer);
5447 });
5448 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005449 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005450}
5451
5452status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5453 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005454 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005455 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005456 bool useIdentityTransform) {
5457 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005458
Peiyong Lin0e003c92018-09-17 11:09:51 -07005459 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005460 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5461 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005462 *outBuffer =
5463 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5464 static_cast<android_pixel_format>(reqPixelFormat), 1,
5465 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005466
5467 // This mutex protects syncFd and captureResult for communication of the return values from the
5468 // main thread back to this Binder thread
5469 std::mutex captureMutex;
5470 std::condition_variable captureCondition;
5471 std::unique_lock<std::mutex> captureLock(captureMutex);
5472 int syncFd = -1;
5473 std::optional<status_t> captureResult;
5474
Robert Carr03480e22018-01-04 16:02:06 -08005475 const int uid = IPCThreadState::self()->getCallingUid();
5476 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5477
Dominik Laskowski8c001672018-05-30 16:52:06 -07005478 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005479 // If there is a refresh pending, bug out early and tell the binder thread to try again
5480 // after the refresh.
5481 if (mRefreshPending) {
5482 ATRACE_NAME("Skipping screenshot for now");
5483 std::unique_lock<std::mutex> captureLock(captureMutex);
5484 captureResult = std::make_optional<status_t>(EAGAIN);
5485 captureCondition.notify_one();
5486 return;
5487 }
5488
5489 status_t result = NO_ERROR;
5490 int fd = -1;
5491 {
5492 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005493 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005494 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5495 useIdentityTransform, forSystem, &fd);
5496 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005497 }
5498
5499 {
5500 std::unique_lock<std::mutex> captureLock(captureMutex);
5501 syncFd = fd;
5502 captureResult = std::make_optional<status_t>(result);
5503 captureCondition.notify_one();
5504 }
5505 });
5506
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005507 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005508 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005509 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005510 while (*captureResult == EAGAIN) {
5511 captureResult.reset();
5512 result = postMessageAsync(message);
5513 if (result != NO_ERROR) {
5514 return result;
5515 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005516 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005517 }
5518 result = *captureResult;
5519 }
5520
5521 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005522 sync_wait(syncFd, -1);
5523 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005524 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005525
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005527}
5528
chaviwa76b2712017-09-20 12:02:26 -07005529void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005530 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005531 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5532 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005533 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005534
chaviwa76b2712017-09-20 12:02:26 -07005535 const auto reqWidth = renderArea.getReqWidth();
5536 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005537 const auto sourceCrop = renderArea.getSourceCrop();
5538 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005539
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005540 renderengine::DisplaySettings clientCompositionDisplay;
5541 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005542
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005543 // assume that bounds are never offset, and that they are the same as the
5544 // buffer bounds.
5545 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5546 ui::Transform transform = renderArea.getTransform();
5547 mat4 m;
5548 m[0][0] = transform[0][0];
5549 m[0][1] = transform[0][1];
5550 m[0][3] = transform[0][2];
5551 m[1][0] = transform[1][0];
5552 m[1][1] = transform[1][1];
5553 m[1][3] = transform[1][2];
5554 m[3][0] = transform[2][0];
5555 m[3][1] = transform[2][1];
5556 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005557
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005558 clientCompositionDisplay.globalTransform = m;
5559 mat4 rotMatrix;
5560 // Displacement for repositioning the clipping rectangle after rotating it
5561 // with the rotation hint.
5562 int displacementX = 0;
5563 int displacementY = 0;
5564 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5565 switch (rotation) {
5566 case ui::Transform::ROT_90:
5567 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5568 displacementX = reqWidth;
5569 break;
5570 case ui::Transform::ROT_180:
5571 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5572 displacementX = reqWidth;
5573 displacementY = reqHeight;
5574 break;
5575 case ui::Transform::ROT_270:
5576 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5577 displacementY = reqHeight;
5578 break;
5579 default:
5580 break;
5581 }
5582 // We need to transform the clipping window into the right spot.
5583 // First, rotate the clipping rectangle by the rotation hint to get the
5584 // right orientation
5585 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5586 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5587 const vec4 rotClipTL = rotMatrix * clipTL;
5588 const vec4 rotClipBR = rotMatrix * clipBR;
5589 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5590 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5591 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5592 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5593
5594 // Now reposition the clipping rectangle with the displacement vector
5595 // computed above.
5596 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5597
5598 clientCompositionDisplay.clip =
5599 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5600 newClipRight + displacementX, newClipBottom + displacementY);
5601
5602 // We need to perform the same transformation in layer space, so propagate
5603 // it to the global transform.
5604 mat4 clipTransform = displacementMat * rotMatrix;
5605 clientCompositionDisplay.globalTransform *= clipTransform;
5606 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5607 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005608
chaviw50da5042018-04-09 13:49:37 -07005609 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005610
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005611 renderengine::LayerSettings fillLayer;
5612 fillLayer.source.buffer.buffer = nullptr;
5613 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5614 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5615 fillLayer.alpha = half(alpha);
5616 clientCompositionLayers.push_back(fillLayer);
5617
5618 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005619 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005620 renderengine::LayerSettings layerSettings;
5621 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5622 layerSettings);
5623 if (prepared) {
5624 clientCompositionLayers.push_back(layerSettings);
5625 }
chaviwa76b2712017-09-20 12:02:26 -07005626 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005627
5628 clientCompositionDisplay.clearRegion = clearRegion;
5629 base::unique_fd drawFence;
5630 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5631 &drawFence);
5632
5633 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005634}
5635
chaviwa76b2712017-09-20 12:02:26 -07005636status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5637 TraverseLayersFunction traverseLayers,
5638 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005639 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005640 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005641 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005642 ATRACE_CALL();
5643
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005644 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005645
5646 traverseLayers([&](Layer* layer) {
5647 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5648 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005649
Robert Carr03480e22018-01-04 16:02:06 -08005650 // We allow the system server to take screenshots of secure layers for
5651 // use in situations like the Screen-rotation animation and place
5652 // the impetus on WindowManager to not persist them.
5653 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005654 ALOGW("FB is protected: PERMISSION_DENIED");
5655 return PERMISSION_DENIED;
5656 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005658 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005659}
5660
chaviw5f21a5e2019-02-14 10:00:34 -08005661void SurfaceFlinger::setInputWindowsFinished() {}
5662
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005663// ---------------------------------------------------------------------------
5664
Dan Stoza412903f2017-04-27 13:42:17 -07005665void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5666 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005667}
5668
Dan Stoza412903f2017-04-27 13:42:17 -07005669void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5670 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005671}
5672
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005673void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005674 const LayerVector::Visitor& visitor) {
5675 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005676 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005677 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005678 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005679 continue;
5680 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005681 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005682 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005683 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005684 return;
5685 }
chaviwa76b2712017-09-20 12:02:26 -07005686 if (!layer->isVisible()) {
5687 return;
5688 }
5689 visitor(layer);
5690 });
5691 }
5692}
5693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005694}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005695
Lloyd Pique074e8122018-07-26 12:57:23 -07005696
Mathias Agopian3f844832013-08-07 21:24:32 -07005697#if defined(__gl_h_)
5698#error "don't include gl/gl.h in this file"
5699#endif
5700
5701#if defined(__gl2_h_)
5702#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005703#endif