blob: 3b4e456038a171afa78062d7e964e68af4bf2659 [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 Krulec757f63a2019-01-25 10:46:18 -0800399 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
400 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700401
Romain Guy11d63f42017-07-20 12:47:14 -0700402 // We should be reading 'persist.sys.sf.color_saturation' here
403 // but since /data may be encrypted, we need to wait until after vold
404 // comes online to attempt to read the property. The property is
405 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800406
407 if (useTrebleTestingOverride()) {
408 // Without the override SurfaceFlinger cannot connect to HIDL
409 // services that are not listed in the manifests. Considered
410 // deriving the setting from the set service name, but it
411 // would be brittle if the name that's not 'default' is used
412 // for production purposes later on.
413 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415}
416
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417void SurfaceFlinger::onFirstRef()
418{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800419 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422SurfaceFlinger::~SurfaceFlinger()
423{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Dan Stozac7014012014-02-14 15:03:43 -0800426void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427{
428 // the window manager died on us. prepare its eulogy.
429
Andy McFadden13a082e2012-08-24 10:16:42 -0700430 // restore initial conditions (default device unblank, etc)
431 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800432
433 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700434 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435}
436
Robert Carr1db73f62016-12-21 12:58:51 -0800437static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700438 status_t err = client->initCheck();
439 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800440 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441 }
Robert Carr1db73f62016-12-21 12:58:51 -0800442 return nullptr;
443}
444
445sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
446 return initClient(new Client(this));
447}
448
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700449sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
450 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451{
452 class DisplayToken : public BBinder {
453 sp<SurfaceFlinger> flinger;
454 virtual ~DisplayToken() {
455 // no more references, this display must be terminated
456 Mutex::Autolock _l(flinger->mStateLock);
457 flinger->mCurrentState.displays.removeItem(this);
458 flinger->setTransactionFlags(eDisplayTransactionNeeded);
459 }
460 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700461 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462 : flinger(flinger) {
463 }
464 };
465
466 sp<BBinder> token = new DisplayToken(this);
467
468 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 // Display ID is assigned when virtual display is allocated by HWC.
470 DisplayDeviceState state;
471 state.isSecure = secure;
472 state.displayName = displayName;
473 mCurrentState.displays.add(token, state);
474 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 return token;
476}
477
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700478void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 Mutex::Autolock _l(mStateLock);
480
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
482 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 return;
485 }
486
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
488 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700489 ALOGE("destroyDisplay called for non-virtual display");
490 return;
491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 mInterceptor->saveDisplayDeletion(state.sequenceId);
493 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700494 setTransactionFlags(eDisplayTransactionNeeded);
495}
496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
498 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 const auto internalDisplayId = getInternalDisplayIdLocked();
501 if (!internalDisplayId) {
502 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503 }
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 std::vector<PhysicalDisplayId> displayIds;
506 displayIds.reserve(mPhysicalDisplayTokens.size());
507 displayIds.push_back(internalDisplayId->value);
508
509 for (const auto& [id, token] : mPhysicalDisplayTokens) {
510 if (id != *internalDisplayId) {
511 displayIds.push_back(id.value);
512 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700514
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800515 return displayIds;
516}
517
518sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
519 Mutex::Autolock lock(mStateLock);
520 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521}
522
Ady Abraham37965d42018-11-01 13:43:32 -0700523status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
524 if (!outGetColorManagement) {
525 return BAD_VALUE;
526 }
527 *outGetColorManagement = useColorManagement;
528 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700529}
530
Lloyd Pique441d5042018-10-18 16:49:51 -0700531HWComposer& SurfaceFlinger::getHwComposer() const {
532 return mCompositionEngine->getHwComposer();
533}
534
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700535renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
536 return mCompositionEngine->getRenderEngine();
537}
538
Lloyd Pique70d91362018-10-18 16:02:55 -0700539compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
540 return *mCompositionEngine.get();
541}
542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543void SurfaceFlinger::bootFinished()
544{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
552 // wait patiently for the window manager death
553 const String16 name("window");
554 sp<IBinder> window(defaultServiceManager()->getService(name));
555 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700556 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 }
Robert Carr720e5062018-07-30 17:45:14 -0700558 sp<IBinder> input(defaultServiceManager()->getService(
559 String16("inputflinger")));
560 if (input == nullptr) {
561 ALOGE("Failed to link to input service");
562 } else {
563 mInputFlinger = interface_cast<IInputFlinger>(input);
564 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 if (mVrFlinger) {
567 mVrFlinger->OnBootFinished();
568 }
569
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700571 // formerly we would just kill the process, but we now ask it to exit so it
572 // can choose where to stop the animation.
573 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700574
575 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
576 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
577 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700578
Ana Krulecbd6654b2019-02-15 15:18:15 -0800579 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 readPersistentProperties();
581 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582
583 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
584 // away and it should be controlled by flipping the switch in setting. The switch in
585 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
586 // The boot must be complete before we can set the active config.
587
588 if (mUse90Hz) {
589 mPhaseOffsets->setRefreshRateType(
590 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
591 setRefreshRateTo(RefreshRateType::PERFORMANCE);
592 } else {
593 mPhaseOffsets->setRefreshRateType(
594 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
595 setRefreshRateTo(RefreshRateType::DEFAULT);
596 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800597 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800598}
599
Dan Stoza436ccf32018-06-21 12:10:12 -0700600uint32_t SurfaceFlinger::getNewTexture() {
601 {
602 std::lock_guard lock(mTexturePoolMutex);
603 if (!mTexturePool.empty()) {
604 uint32_t name = mTexturePool.back();
605 mTexturePool.pop_back();
606 ATRACE_INT("TexturePoolSize", mTexturePool.size());
607 return name;
608 }
609
610 // The pool was too small, so increase it for the future
611 ++mTexturePoolSize;
612 }
613
614 // The pool was empty, so we need to get a new texture name directly using a
615 // blocking call to the main thread
616 uint32_t name = 0;
617 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
618 return name;
619}
620
Mathias Agopian3f844832013-08-07 21:24:32 -0700621void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700622 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700623}
624
Wei Wangf9b05ee2017-07-19 20:59:39 -0700625// Do not call property_set on main thread which will be blocked by init
626// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700627void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700628 ALOGI( "SurfaceFlinger's main thread ready to run. "
629 "Initializing graphics H/W...");
630
Ana Krulec757f63a2019-01-25 10:46:18 -0800631 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900632
Steven Thomasb02664d2017-07-26 18:48:28 -0700633 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700634 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800635 mScheduler =
636 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
637 auto resyncCallback =
638 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800639
Ana Krulecc2870422019-01-29 19:00:58 -0800640 mAppConnectionHandle =
641 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
642 resyncCallback,
643 impl::EventThread::InterceptVSyncsCallback());
644 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
645 resyncCallback, [this](nsecs_t timestamp) {
646 mInterceptor->saveVSyncEvent(timestamp);
647 });
648
649 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
650 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
651 mSfConnectionHandle.get());
652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700654 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700655 renderEngineFeature |= (useColorManagement ?
656 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700657 renderEngineFeature |= (useContextPriority ?
658 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700659
660 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700661 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700662 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700663 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700664
665 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
666 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700667 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
668 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 const auto display = getDefaultDisplayDeviceLocked();
672 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700673 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800675
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 // This callback is called from the vr flinger dispatch thread. We
679 // need to call signalTransaction(), which requires holding
680 // mStateLock when we're not on the main thread. Acquiring
681 // mStateLock from the vr flinger dispatch thread might trigger a
682 // deadlock in surface flinger (see b/66916578), so post a message
683 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
686 mVrFlingerRequestsDisplay = requestDisplay;
687 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
691 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700692 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 .value_or(0),
694 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 if (!mVrFlinger) {
696 ALOGE("Failed to start vrflinger");
697 }
698 }
699
Mathias Agopian92a979a2012-08-02 18:32:23 -0700700 // initialize our drawing state
701 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700702
Andy McFadden13a082e2012-08-24 10:16:42 -0700703 // set initial conditions (e.g. unblank default device)
704 initializeDisplays();
705
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700706 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700707
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709
710 const bool presentFenceReliable =
711 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
712 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Ana Krulecc2870422019-01-29 19:00:58 -0800718 mScheduler->setExpiredIdleTimerCallback([this] {
719 Mutex::Autolock lock(mStateLock);
720 setRefreshRateTo(RefreshRateType::DEFAULT);
721 });
722 mScheduler->setResetIdleTimerCallback([this] {
723 Mutex::Autolock lock(mStateLock);
724 setRefreshRateTo(RefreshRateType::PERFORMANCE);
725 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800726
Ana Krulecc2870422019-01-29 19:00:58 -0800727 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
728 *display->getId()),
729 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700732}
733
Romain Guy11d63f42017-07-20 12:47:14 -0700734void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700735 Mutex::Autolock _l(mStateLock);
736
Romain Guy11d63f42017-07-20 12:47:14 -0700737 char value[PROPERTY_VALUE_MAX];
738
739 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800740 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100743
744 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700745 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800746
747 property_get("persist.sys.sf.color_mode", value, "0");
748 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700749}
750
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800752 // Start boot animation service by setting a property mailbox
753 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700756 if (mStartPropertySetThread->join() != NO_ERROR) {
757 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800758 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700762 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800769// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800770
Jamie Gennis582270d2011-08-17 18:19:00 -0700771bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800772 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800773 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800774 return authenticateSurfaceTextureLocked(bufferProducer);
775}
776
777bool SurfaceFlinger::authenticateSurfaceTextureLocked(
778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800779 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800780 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800781}
782
Brian Anderson6b376712017-04-04 10:51:39 -0700783status_t SurfaceFlinger::getSupportedFrameTimestamps(
784 std::vector<FrameEvent>* outSupported) const {
785 *outSupported = {
786 FrameEvent::REQUESTED_PRESENT,
787 FrameEvent::ACQUIRE,
788 FrameEvent::LATCH,
789 FrameEvent::FIRST_REFRESH_START,
790 FrameEvent::LAST_REFRESH_START,
791 FrameEvent::GPU_COMPOSITION_DONE,
792 FrameEvent::DEQUEUE_READY,
793 FrameEvent::RELEASE,
794 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700795 ConditionalLock _l(mStateLock,
796 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700797 if (!getHwComposer().hasCapability(
798 HWC2::Capability::PresentFenceIsNotReliable)) {
799 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
800 }
801 return NO_ERROR;
802}
803
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800804status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
805 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700806 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 return BAD_VALUE;
808 }
809
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800810 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700811 if (!displayId) {
812 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700813 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 // TODO: Not sure if display density should handled by SF any longer
816 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700817 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700819 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800820 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 }
823 return density;
824 }
825 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 return getDensityFromProperty("ro.sf.lcd_density"); }
830 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dominik Laskowski075d3172018-05-24 15:50:06 -0700834 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 DisplayInfo info = DisplayInfo();
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 float xdpi = hwConfig->getDpiX();
838 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700840 info.w = hwConfig->getWidth();
841 info.h = hwConfig->getHeight();
842 // Default display viewport to display width and height
843 info.viewportW = info.w;
844 info.viewportH = info.h;
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 // The density of the device is provided by a build property
848 float density = Density::getBuildDensity() / 160.0f;
849 if (density == 0) {
850 // the build doesn't provide a density -- this is wrong!
851 // use xdpi instead
852 ALOGE("ro.sf.lcd_density must be defined as a build property");
853 density = xdpi / 160.0f;
854 }
855 if (Density::getEmuDensity()) {
856 // if "qemu.sf.lcd_density" is specified, it overrides everything
857 xdpi = ydpi = density = Density::getEmuDensity();
858 density /= 160.0f;
859 }
860 info.density = density;
861
862 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863 const auto display = getDefaultDisplayDeviceLocked();
864 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865
866 // This is for screenrecord
867 const Rect viewport = display->getViewport();
868 if (viewport.isValid()) {
869 info.viewportW = uint32_t(viewport.getWidth());
870 info.viewportH = uint32_t(viewport.getHeight());
871 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 } else {
873 // TODO: where should this value come from?
874 static const int TV_DENSITY = 213;
875 info.density = TV_DENSITY / 160.0f;
876 info.orientation = 0;
877 }
878
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 info.xdpi = xdpi;
880 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800882 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883
Andy McFadden91b2ca82014-06-13 14:04:23 -0700884 // This is how far in advance a buffer must be queued for
885 // presentation at a given time. If you want a buffer to appear
886 // on the screen at time N, you must submit the buffer before
887 // (N - presentationDeadline).
888 //
889 // Normally it's one full refresh period (to give SF a chance to
890 // latch the buffer), but this can be reduced by configuring a
891 // DispSync offset. Any additional delays introduced by the hardware
892 // composer or panel must be accounted for here.
893 //
894 // We add an additional 1ms to allow for processing time and
895 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800896 info.presentationDeadline =
897 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
899 // All non-virtual displays are currently considered secure.
900 info.secure = true;
901
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800902 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700903 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800904 std::swap(info.w, info.h);
905 }
906
Michael Wright28f24d02016-07-12 13:30:53 -0700907 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 }
909
Dan Stoza7f7da322014-05-02 15:26:25 -0700910 return NO_ERROR;
911}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700912
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
914 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700915 return BAD_VALUE;
916 }
917
Ana Krulecc2870422019-01-29 19:00:58 -0800918 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return NO_ERROR;
920}
921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
923 const auto display = getDisplayDevice(displayToken);
924 if (!display) {
925 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800926 return BAD_VALUE;
927 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700930}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700931
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
933 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800934
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 // Lock is acquired by setRefreshRateTo.
937 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800938 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
939 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
940 return;
941 }
942
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 // Lock is acquired by setRefreshRateTo.
944 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800945 if (!display) {
946 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
947 displayToken.get());
948 return;
949 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700950 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800951 ALOGW("Attempt to set active config %d for virtual display", mode);
952 return;
953 }
954 int currentDisplayPowerMode = display->getPowerMode();
955 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
956 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700957 return;
958 }
959
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960 // Don't check against the current mode yet. Worst case we set the desired
961 // config twice.
962 {
963 std::lock_guard<std::mutex> lock(mActiveConfigLock);
964 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
965 }
966 // This will trigger HWC refresh without resetting the idle timer.
967 repaintEverythingForHWC();
968}
969
970status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
971 ATRACE_CALL();
972 postMessageSync(new LambdaMessage(
973 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
974 return NO_ERROR;
975}
976
977void SurfaceFlinger::setActiveConfigInHWC() {
978 ATRACE_CALL();
979
980 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
981 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700982 return;
983 }
Ana Krulecc2870422019-01-29 19:00:58 -0800984
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 const auto displayId = display->getId();
986 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700987
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
989 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
990 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
991 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
992}
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700993
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994void SurfaceFlinger::setActiveConfigInternal() {
995 ATRACE_CALL();
996
997 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800998 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999
1000 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1001 display->setActiveConfig(mUpcomingActiveConfig.configId);
1002
1003 mSetActiveConfigState = SetActiveConfigState::NONE;
1004 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1005
Ana Krulecc2870422019-01-29 19:00:58 -08001006 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1008}
1009
1010bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1011 // Store the local variable to release the lock.
1012 ActiveConfigInfo desiredActiveConfig;
1013 {
1014 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1015 desiredActiveConfig = mDesiredActiveConfig;
1016 }
1017
1018 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1019 if (display) {
1020 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1021 display->getActiveConfig() != desiredActiveConfig.configId) {
1022 // Step 1) Desired active config was set, it is different than the
1023 // config currently in use. Notify HWC.
1024 mUpcomingActiveConfig = desiredActiveConfig;
1025 setActiveConfigInHWC();
1026 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1027 // Step 2) HWC was notified and we received refresh from it.
1028 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1029 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1030 repaintEverythingForHWC();
1031 // We do not want to give another frame to HWC while we are transitioning.
1032 return false;
1033 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1034 !(mPreviousPresentFence != Fence::NO_FENCE &&
1035 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1036 // Step 3) We received the present fence from the HWC, so we assume it
1037 // successfully updated the config, hence we update SF.
1038 setActiveConfigInternal();
1039 // If the config changed again while we were transitioning, restart the
1040 // process.
1041 if (desiredActiveConfig != mUpcomingActiveConfig) {
1042 mUpcomingActiveConfig = desiredActiveConfig;
1043 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1044 }
1045 }
1046 }
1047 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001048}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001049
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1051 Vector<ColorMode>* outColorModes) {
1052 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001053 return BAD_VALUE;
1054 }
1055
Peiyong Lina52f0292018-03-14 17:26:31 -07001056 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001057 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001058 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1059
1060 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1061 if (!displayId) {
1062 return NAME_NOT_FOUND;
1063 }
1064
Dominik Laskowski075d3172018-05-24 15:50:06 -07001065 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001066 }
Michael Wright28f24d02016-07-12 13:30:53 -07001067 outColorModes->clear();
1068 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1069
1070 return NO_ERROR;
1071}
1072
Daniel Solomon42d04562019-01-20 21:03:19 -08001073status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1074 ui::DisplayPrimaries &primaries) {
1075 if (!displayToken) {
1076 return BAD_VALUE;
1077 }
1078
1079 // Currently we only support this API for a single internal display.
1080 if (getInternalDisplayToken() != displayToken) {
1081 return BAD_VALUE;
1082 }
1083
1084 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1085 return NO_ERROR;
1086}
1087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1089 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001090 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001091 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001092 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001093}
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001096 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097 Vector<ColorMode> modes;
1098 getDisplayColorModes(displayToken, &modes);
1099 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1100 if (mode < ColorMode::NATIVE || !exists) {
1101 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1102 decodeColorMode(mode).c_str(), mode, displayToken.get());
1103 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001104 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105 const auto display = getDisplayDevice(displayToken);
1106 if (!display) {
1107 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1108 decodeColorMode(mode).c_str(), mode, displayToken.get());
1109 } else if (display->isVirtual()) {
1110 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1111 decodeColorMode(mode).c_str(), mode);
1112 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001113 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1114 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 }
1116 }));
1117
Michael Wright28f24d02016-07-12 13:30:53 -07001118 return NO_ERROR;
1119}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001120
Svetoslavd85084b2014-03-20 10:28:31 -07001121status_t SurfaceFlinger::clearAnimationFrameStats() {
1122 Mutex::Autolock _l(mStateLock);
1123 mAnimFrameTracker.clearStats();
1124 return NO_ERROR;
1125}
1126
1127status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1128 Mutex::Autolock _l(mStateLock);
1129 mAnimFrameTracker.getStats(outStats);
1130 return NO_ERROR;
1131}
1132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1134 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001135 Mutex::Autolock _l(mStateLock);
1136
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 const auto display = getDisplayDeviceLocked(displayToken);
1138 if (!display) {
1139 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001140 return BAD_VALUE;
1141 }
1142
Peiyong Linfb069302018-04-25 14:34:31 -07001143 // At this point the DisplayDeivce should already be set up,
1144 // meaning the luminance information is already queried from
1145 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001147 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1148 capabilities.getDesiredMaxLuminance(),
1149 capabilities.getDesiredMaxAverageLuminance(),
1150 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001151
1152 return NO_ERROR;
1153}
1154
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001155status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1156 ui::PixelFormat* outFormat,
1157 ui::Dataspace* outDataspace,
1158 uint8_t* outComponentMask) const {
1159 if (!outFormat || !outDataspace || !outComponentMask) {
1160 return BAD_VALUE;
1161 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001162 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001163 if (!display || !display->getId()) {
1164 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1165 return BAD_VALUE;
1166 }
1167 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1168 outDataspace, outComponentMask);
1169}
1170
Kevin DuBois74e53772018-11-19 10:52:38 -08001171status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1172 bool enable, uint8_t componentMask,
1173 uint64_t maxFrames) const {
1174 const auto display = getDisplayDevice(displayToken);
1175 if (!display || !display->getId()) {
1176 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1177 return BAD_VALUE;
1178 }
1179
1180 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1181 componentMask, maxFrames);
1182}
1183
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001184status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1185 uint64_t maxFrames, uint64_t timestamp,
1186 DisplayedFrameStats* outStats) const {
1187 const auto display = getDisplayDevice(displayToken);
1188 if (!display || !display->getId()) {
1189 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1190 return BAD_VALUE;
1191 }
1192
1193 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1194 outStats);
1195}
1196
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001197status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1198 if (!outSupported) {
1199 return BAD_VALUE;
1200 }
1201 *outSupported = getRenderEngine().supportsProtectedContent();
1202 return NO_ERROR;
1203}
1204
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001205status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1206 bool* outIsWideColorDisplay) const {
1207 if (!displayToken || !outIsWideColorDisplay) {
1208 return BAD_VALUE;
1209 }
1210 Mutex::Autolock _l(mStateLock);
1211 const auto display = getDisplayDeviceLocked(displayToken);
1212 if (!display) {
1213 return BAD_VALUE;
1214 }
1215 *outIsWideColorDisplay = display->hasWideColorGamut();
1216 return NO_ERROR;
1217}
1218
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001219status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001220 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001221 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001222
Chia-I Wu90f669f2017-10-05 14:24:41 -07001223 if (mInjectVSyncs == enable) {
1224 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001225 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001226
Ana Krulecc2870422019-01-29 19:00:58 -08001227 auto resyncCallback =
1228 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001229
Ana Krulec98b5b242018-08-10 15:03:23 -07001230 // TODO(akrulec): Part of the Injector should be refactored, so that it
1231 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001232 if (enable) {
1233 ALOGV("VSync Injections enabled");
1234 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001235 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001236 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001237 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001238 impl::EventThread::InterceptVSyncsCallback(),
1239 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001240 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001241 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 } else {
1243 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001244 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1245 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246 }
1247
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001248 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001249 }));
1250
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251 return NO_ERROR;
1252}
1253
1254status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 Mutex::Autolock _l(mStateLock);
1256
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 if (!mInjectVSyncs) {
1258 ALOGE("VSync Injections not enabled");
1259 return BAD_VALUE;
1260 }
1261 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1262 ALOGV("Injecting VSync inside SurfaceFlinger");
1263 mVSyncInjector->onInjectSyncEvent(when);
1264 }
1265 return NO_ERROR;
1266}
1267
Lloyd Pique755e3192018-01-31 16:46:15 -08001268status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1269 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001270 // Try to acquire a lock for 1s, fail gracefully
1271 const status_t err = mStateLock.timedLock(s2ns(1));
1272 const bool locked = (err == NO_ERROR);
1273 if (!locked) {
1274 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1275 return TIMED_OUT;
1276 }
1277
1278 outLayers->clear();
1279 mCurrentState.traverseInZOrder([&](Layer* layer) {
1280 outLayers->push_back(layer->getLayerDebugInfo());
1281 });
1282
1283 mStateLock.unlock();
1284 return NO_ERROR;
1285}
1286
Peiyong Linc6780972018-10-28 15:24:08 -07001287status_t SurfaceFlinger::getCompositionPreference(
1288 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1289 Dataspace* outWideColorGamutDataspace,
1290 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001291 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001292 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001293 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001294 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001295 return NO_ERROR;
1296}
1297
Dan Stoza84ab9372018-12-17 15:27:57 -08001298status_t SurfaceFlinger::addRegionSamplingListener(
1299 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1300 const sp<IRegionSamplingListener>& /*listener*/) {
1301 return NO_ERROR;
1302}
1303
1304status_t SurfaceFlinger::removeRegionSamplingListener(
1305 const sp<IRegionSamplingListener>& /*listener*/) {
1306 return NO_ERROR;
1307}
1308
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001309// ----------------------------------------------------------------------------
1310
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001311sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1312 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001313 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001314 Mutex::Autolock lock(mStateLock);
1315 return getVsyncPeriod();
1316 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001317
Ana Krulecc2870422019-01-29 19:00:58 -08001318 const auto& handle =
1319 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001320
Ana Krulecc2870422019-01-29 19:00:58 -08001321 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001322}
1323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001324// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001325
1326void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001327 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001328}
1329
1330void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001331 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001332}
1333
1334void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001335 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001336}
1337
1338void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001339 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001340 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001341}
1342
1343status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001344 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001345 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001346}
1347
1348status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001349 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001350 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351 if (res == NO_ERROR) {
1352 msg->wait();
1353 }
1354 return res;
1355}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001356
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001357void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001358 do {
1359 waitForEvent();
1360 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001361}
1362
Dominik Laskowski83b88212018-12-11 13:34:06 -08001363nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001364 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001365 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1366 return 0;
1367 }
1368
1369 const auto config = getHwComposer().getActiveConfig(*displayId);
1370 return config ? config->getVsyncPeriod() : 0;
1371}
1372
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001373void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1374 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001375 ATRACE_NAME("SF onVsync");
1376
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001379 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001380 return;
1381 }
1382
Dominik Laskowski075d3172018-05-24 15:50:06 -07001383 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001384 return;
1385 }
1386
Dominik Laskowski075d3172018-05-24 15:50:06 -07001387 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001388 // For now, we don't do anything with external display vsyncs.
1389 return;
1390 }
1391
Ana Krulecc2870422019-01-29 19:00:58 -08001392 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001393}
1394
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001396 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1397 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001398}
1399
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001400void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1401 mPhaseOffsets->setRefreshRateType(refreshRate);
1402
1403 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1404 mVsyncModulator.setPhaseOffsets(early, gl, late);
1405
1406 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001407 return;
1408 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001409
Ana Krulec7d1d6832018-12-27 11:10:09 -08001410 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1411 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1412 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1413 // refresh cycle.
1414
1415 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001416 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001417 if (currentVsyncPeriod == 0) {
1418 return;
1419 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001420
Ana Krulec7d1d6832018-12-27 11:10:09 -08001421 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1422 // floating numbers.
1423 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001424 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1425 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001426 if (std::abs(currentFps - newFps) <= 1) {
1427 return;
1428 }
1429
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001430 const auto displayId = getInternalDisplayIdLocked();
1431 LOG_ALWAYS_FATAL_IF(!displayId);
1432
1433 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434 for (int i = 0; i < configs.size(); i++) {
1435 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1436 if (vsyncPeriod == 0) {
1437 continue;
1438 }
1439 const float fps = 1e9 / vsyncPeriod;
1440 // TODO(b/113612090): There should be a better way at determining which config
1441 // has the right refresh rate.
1442 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001443 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001444 }
1445 }
1446}
1447
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001448void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001449 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001450 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001451 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001452
Lloyd Piqueba04e622017-12-14 17:11:26 -08001453 // Ignore events that do not have the right sequenceId.
1454 if (sequenceId != getBE().mComposerSequenceId) {
1455 return;
1456 }
1457
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 // Only lock if we're not on the main thread. This function is normally
1459 // called on a hwbinder thread, but for the primary display it's called on
1460 // the main thread with the state lock already held, so don't attempt to
1461 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001462 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001463
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001464 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001465
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001466 if (std::this_thread::get_id() == mMainThreadId) {
1467 // Process all pending hot plug events immediately if we are on the main thread.
1468 processDisplayHotplugEventsLocked();
1469 }
1470
Lloyd Piqueba04e622017-12-14 17:11:26 -08001471 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001472}
1473
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001474void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001475 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001476 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001478 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001479 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001480}
1481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001482void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001483 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001485 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001486 getHwComposer().setVsyncEnabled(*displayId,
1487 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1488 }
Mathias Agopian86303202012-07-24 22:46:10 -07001489}
1490
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001492void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001493 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494 // Clear the drawing state so that the logic inside of
1495 // handleTransactionLocked will fire. It will determine the delta between
1496 // mCurrentState and mDrawingState and re-apply all changes when we make the
1497 // transition.
1498 mDrawingState.displays.clear();
1499 mDisplays.clear();
1500}
1501
Steven Thomas050b2c82017-03-06 11:45:16 -08001502void SurfaceFlinger::updateVrFlinger() {
1503 if (!mVrFlinger)
1504 return;
1505 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001506 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001507 return;
1508 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001509
Lloyd Pique441d5042018-10-18 16:49:51 -07001510 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 ALOGE("Vr flinger is only supported for remote hardware composer"
1512 " service connections. Ignoring request to transition to vr"
1513 " flinger.");
1514 mVrFlingerRequestsDisplay = false;
1515 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001516 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519
Steven Thomas0123ac62018-07-12 11:32:34 -07001520 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001521 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001522
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001523 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001524
1525 // Clear out all the output layers from the composition engine for all
1526 // displays before destroying the hardware composer interface. This ensures
1527 // any HWC layers are destroyed through that interface before it becomes
1528 // invalid.
1529 for (const auto& [token, displayDevice] : mDisplays) {
1530 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1531 compositionengine::Output::OutputLayers());
1532 }
1533
Steven Thomas0123ac62018-07-12 11:32:34 -07001534 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1535 // called below. Clear the reference now so we don't accidentally use it
1536 // later.
1537 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001538
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001542
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001544 // Delete the current instance before creating the new one
1545 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1546 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1547 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1548 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549
Lloyd Pique441d5042018-10-18 16:49:51 -07001550 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001551 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001552
1553 if (vrFlingerRequestsDisplay) {
1554 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001555 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001556
1557 mVisibleRegionsDirty = true;
1558 invalidateHwcGeometry();
1559
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001560 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001561 display = getDefaultDisplayDeviceLocked();
1562 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001563 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001566 const nsecs_t vsyncPeriod = getVsyncPeriod();
1567 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001568
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001569 // The present fences returned from vr_hwc are not an accurate
1570 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001571 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001572
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 // Use phase of 0 since phase is not known.
1574 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001575 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001576 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001577
Ana Krulecc2870422019-01-29 19:00:58 -08001578 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001580 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001582}
1583
Mathias Agopian4fec8732012-06-29 14:12:52 -07001584void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001585 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001586 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001587 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001588 if (!updateSetActiveConfigStateMachine()) {
1589 break;
1590 }
1591
Ana Krulecc2870422019-01-29 19:00:58 -08001592 // This call is made each time SF wakes up and creates a new frame.
1593 mScheduler->incrementFrameCounter();
1594
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001595 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1596 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001597 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001598 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001599 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001600 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001601 if (mPropagateBackpressure) {
1602 signalLayerUpdate();
1603 break;
1604 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001605 }
Dan Stoza50182882016-07-08 12:02:20 -07001606
Steven Thomas050b2c82017-03-06 11:45:16 -08001607 // Now that we're going to make it to the handleMessageTransaction()
1608 // call below it's safe to call updateVrFlinger(), which will
1609 // potentially trigger a display handoff.
1610 updateVrFlinger();
1611
Dan Stoza6b9454d2014-11-07 16:00:59 -08001612 bool refreshNeeded = handleMessageTransaction();
1613 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001614
1615 updateCursorAsync();
1616 updateInputFlinger();
1617
Dan Stoza58784442014-12-02 16:58:17 -08001618 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001619 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001620 // Signal a refresh if a transaction modified the window state,
1621 // a new buffer was latched, or if HWC has requested a full
1622 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001623 signalRefresh();
1624 }
1625 break;
1626 }
1627 case MessageQueue::REFRESH: {
1628 handleMessageRefresh();
1629 break;
1630 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001631 }
1632}
1633
Dan Stoza6b9454d2014-11-07 16:00:59 -08001634bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001635 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001636
1637 // Apply any ready transactions in the queues if there are still transactions that have not been
1638 // applied, wake up during the next vsync period and check again
1639 bool transactionNeeded = false;
1640 if (!flushTransactionQueues()) {
1641 transactionNeeded = true;
1642 }
1643
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001645 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001647
1648 if (transactionNeeded) {
1649 setTransactionFlags(eTransactionNeeded);
1650 }
1651
1652 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001653}
1654
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001657
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001658 mRefreshPending = false;
1659
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001660 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001661 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001662 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001663 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001664 for (const auto& [token, display] : mDisplays) {
1665 beginFrame(display);
1666 prepareFrame(display);
1667 doDebugFlashRegions(display, repaintEverything);
1668 doComposition(display, repaintEverything);
1669 }
1670
Adrian Roos1e1a1282017-11-01 19:05:31 +01001671 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001672 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001673
1674 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001675 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001676
Dan Stozabfbffeb2016-07-21 14:49:33 -07001677 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001678 for (const auto& [token, displayDevice] : mDisplays) {
1679 auto display = displayDevice->getCompositionDisplay();
1680 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001681 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001682 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001683 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001684
Jorim Jaggi90535212018-05-23 23:44:06 +02001685 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001686
David Sodman7e4ae112018-02-09 15:02:28 -08001687 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001688
1689 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001691
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692
1693bool SurfaceFlinger::handleMessageInvalidate() {
1694 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001695 bool refreshNeeded = handlePageFlip();
1696
Vishnu Nair4351ad52019-02-11 14:13:02 -08001697 if (mVisibleRegionsDirty) {
1698 computeLayerBounds();
1699 }
1700
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001701 for (auto& layer : mLayersPendingRefresh) {
1702 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001703 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001704 invalidateLayerStack(layer, visibleReg);
1705 }
1706 mLayersPendingRefresh.clear();
1707 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001708}
1709
David Sodman79bba0e2018-08-05 18:07:49 -07001710void SurfaceFlinger::calculateWorkingSet() {
1711 ATRACE_CALL();
1712 ALOGV(__FUNCTION__);
1713
David Sodman79bba0e2018-08-05 18:07:49 -07001714 // build the h/w work list
1715 if (CC_UNLIKELY(mGeometryInvalid)) {
1716 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001717 for (const auto& [token, displayDevice] : mDisplays) {
1718 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001719 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001720 if (!displayId) {
1721 continue;
1722 }
David Sodman79bba0e2018-08-05 18:07:49 -07001723
Lloyd Pique32cbe282018-10-19 13:09:22 -07001724 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001725 for (size_t i = 0; i < currentLayers.size(); i++) {
1726 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001727
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001728 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001729 layer->forceClientComposition(displayDevice);
1730 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001731 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001732
Lloyd Pique32cbe282018-10-19 13:09:22 -07001733 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001734 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001735 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001736 }
David Sodman79bba0e2018-08-05 18:07:49 -07001737 }
1738 }
1739 }
1740
1741 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001742 for (const auto& [token, displayDevice] : mDisplays) {
1743 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001744 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001745 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001746 continue;
1747 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001748 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001749
1750 if (mDrawingState.colorMatrixChanged) {
1751 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001752 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001753 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001754 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001755 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001756 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1757 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001758 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001759 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001760 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1761 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001762 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001763 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001764 }
1765
Peiyong Lind3788632018-09-18 16:01:31 -07001766 // TODO(b/111562338) remove when composer 2.3 is shipped.
1767 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001768 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001769 }
1770
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001771 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001772 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001773 }
1774
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001775 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001776 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001777 layer->setCompositionType(displayDevice,
1778 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001779 continue;
1780 }
1781
Lloyd Pique32cbe282018-10-19 13:09:22 -07001782 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001783 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001784 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001785 }
1786
Peiyong Lin13effd12018-07-24 17:01:47 -07001787 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001788 ColorMode colorMode;
1789 Dataspace dataSpace;
1790 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001791 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001792 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001793 }
1794 }
1795
1796 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001797
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001798 for (const auto& [token, displayDevice] : mDisplays) {
1799 auto display = displayDevice->getCompositionDisplay();
1800 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001801 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001802 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1803 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1804 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001805 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001806 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001807 }
1808 }
David Sodman79bba0e2018-08-05 18:07:49 -07001809}
1810
Lloyd Pique32cbe282018-10-19 13:09:22 -07001811void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1812 bool repaintEverything) {
1813 auto display = displayDevice->getCompositionDisplay();
1814 const auto& displayState = display->getState();
1815
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816 // is debugging enabled
1817 if (CC_LIKELY(!mDebugRegion))
1818 return;
1819
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001821 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001822 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001823 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001824 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001825 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001826 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001827
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001828 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829 }
1830 }
1831
Lloyd Pique32cbe282018-10-19 13:09:22 -07001832 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833
1834 if (mDebugRegion > 1) {
1835 usleep(mDebugRegion * 1000);
1836 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001837
Lloyd Pique32cbe282018-10-19 13:09:22 -07001838 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839}
1840
Adrian Roos1e1a1282017-11-01 19:05:31 +01001841void SurfaceFlinger::doTracing(const char* where) {
1842 ATRACE_CALL();
1843 ATRACE_NAME(where);
1844 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001845 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001846 }
1847}
1848
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001849void SurfaceFlinger::logLayerStats() {
1850 ATRACE_CALL();
1851 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001852 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001853 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001854 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001855 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001856 }
1857 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001858
1859 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001860 }
1861}
1862
David Sodman2b406362017-12-15 13:33:47 -08001863void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 ATRACE_CALL();
1866 ALOGV("preComposition");
1867
David Sodman2b406362017-12-15 13:33:47 -08001868 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001871 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001872 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 needExtraInvalidate = true;
1874 }
Robert Carr2047fae2016-11-28 14:09:09 -08001875 });
1876
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877 if (needExtraInvalidate) {
1878 signalLayerUpdate();
1879 }
1880}
1881
Ana Krulece588e312018-09-18 12:32:24 -07001882void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1883 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001884 // Update queue of past composite+present times and determine the
1885 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001886 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001887 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001888 while (!getBE().mCompositePresentTimes.empty()) {
1889 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890 // Cached values should have been updated before calling this method,
1891 // which helps avoid duplicate syscalls.
1892 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1893 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1894 break;
1895 }
1896 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001897 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898 }
1899
1900 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001901 while (getBE().mCompositePresentTimes.size() > 16) {
1902 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 }
1904
Ana Krulece588e312018-09-18 12:32:24 -07001905 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001906}
1907
Ana Krulece588e312018-09-18 12:32:24 -07001908void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1909 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001910 // Integer division and modulo round toward 0 not -inf, so we need to
1911 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001912 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1913 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1914 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915
Ana Krulec757f63a2019-01-25 10:46:18 -08001916 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001917 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001918 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001919 }
1920
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // Snap the latency to a value that removes scheduling jitter from the
1922 // composition and present times, which often have >1ms of jitter.
1923 // Reducing jitter is important if an app attempts to extrapolate
1924 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001925 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001927 nsecs_t bias = stats.vsyncPeriod / 2;
1928 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1929 nsecs_t snappedCompositeToPresentLatency =
1930 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931
David Sodman99974d22017-11-28 12:04:33 -08001932 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001933 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1934 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001935 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936}
1937
Ady Abraham8164d482019-01-11 14:47:59 -08001938// debug patch for b/119477596 - add stack guards to catch stack
1939// corruptions and disable clang optimizations.
1940// The code below is temporary and planned to be removed once stack
1941// corruptions are found.
1942#pragma clang optimize off
1943class StackGuard {
1944public:
1945 StackGuard(const char* name, const char* func, int line) {
1946 guarders.reserve(MIN_CAPACITY);
1947 guarders.push_back({this, name, func, line});
1948 validate();
1949 }
1950 ~StackGuard() {
1951 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1952 if (i->guard == this) {
1953 guarders.erase(i);
1954 break;
1955 }
1956 }
1957 }
1958
1959 static void validate() {
1960 for (const auto& guard : guarders) {
1961 if (guard.guard->cookie != COOKIE_VALUE) {
1962 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1963 CallStack stack(LOG_TAG);
1964 abort();
1965 }
1966 }
1967 }
1968
1969private:
1970 uint64_t cookie = COOKIE_VALUE;
1971 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1972 static constexpr size_t MIN_CAPACITY = 16;
1973
1974 struct GuarderElement {
1975 StackGuard* guard;
1976 const char* name;
1977 const char* func;
1978 int line;
1979 };
1980
1981 static std::vector<GuarderElement> guarders;
1982};
1983std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1984
1985#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1986
1987#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001988void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001989{
Ady Abraham8164d482019-01-11 14:47:59 -08001990 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 ATRACE_CALL();
1992 ALOGV("postComposition");
1993
Brian Anderson3546a3f2016-07-14 11:51:14 -07001994 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001995 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001996 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001997 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001998 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001999 }
Ady Abraham8164d482019-01-11 14:47:59 -08002000 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002001
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002002 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002003 const auto displayDevice = getDefaultDisplayDeviceLocked();
2004 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005
David Sodman73beded2017-11-15 11:56:06 -08002006 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002008 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2009
Lloyd Pique32cbe282018-10-19 13:09:22 -07002010 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002012 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2013 ->getRenderSurface()
2014 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002015 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016 } else {
2017 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2018 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019
Ady Abraham8164d482019-01-11 14:47:59 -08002020 ASSERT_ON_STACK_GUARD();
2021
David Sodman73beded2017-11-15 11:56:06 -08002022 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002023 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2024 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002025 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002026 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002027 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002028
Ana Krulece588e312018-09-18 12:32:24 -07002029 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002030 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002031 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032
Ady Abraham8164d482019-01-11 14:47:59 -08002033 ASSERT_ON_STACK_GUARD();
2034
David Sodman2b406362017-12-15 13:33:47 -08002035 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036 // when we started doing work for this frame, but that should be okay
2037 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002038 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002039 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002040 DEFINE_STACK_GUARD(compositorTiming);
2041
Brian Andersond0010582017-03-07 13:20:31 -08002042 {
David Sodman99974d22017-11-28 12:04:33 -08002043 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002044 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002045 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002046
2047 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002048 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049
Robert Carr2047fae2016-11-28 14:09:09 -08002050 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002051 bool frameLatched =
2052 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2053 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002054 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002055 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002056 recordBufferingStats(layer->getName().string(),
2057 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002058 }
Ady Abraham8164d482019-01-11 14:47:59 -08002059 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002060 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002061
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002062 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002063 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002064 mScheduler->addPresentFence(presentFenceTime);
2065 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002066 }
2067
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002068 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2070 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002071 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002072 }
2073 }
2074
Ady Abraham8164d482019-01-11 14:47:59 -08002075 ASSERT_ON_STACK_GUARD();
2076
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002077 if (mAnimCompositionPending) {
2078 mAnimCompositionPending = false;
2079
Brian Anderson4e606e32017-03-16 15:34:57 -07002080 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002081 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002082 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002083
2084 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002085 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002086 // The HWC doesn't support present fences, so use the refresh
2087 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002088 const nsecs_t presentTime =
2089 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002090 DEFINE_STACK_GUARD(presentTime);
2091
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002092 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002093 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002094 }
2095 mAnimFrameTracker.advanceFrame();
2096 }
Dan Stozab90cf072015-03-05 11:05:59 -08002097
Ady Abraham8164d482019-01-11 14:47:59 -08002098 ASSERT_ON_STACK_GUARD();
2099
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002100 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002101 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002102 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002103 }
2104
Ady Abraham8164d482019-01-11 14:47:59 -08002105 ASSERT_ON_STACK_GUARD();
2106
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002107 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002108
Ady Abraham8164d482019-01-11 14:47:59 -08002109 ASSERT_ON_STACK_GUARD();
2110
Lloyd Pique32cbe282018-10-19 13:09:22 -07002111 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2112 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002113 return;
2114 }
2115
2116 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002117 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002118 if (mHasPoweredOff) {
2119 mHasPoweredOff = false;
2120 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002121 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002122 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002123 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002124 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002125 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2126 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002127 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002128 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002129 }
David Sodman4a36e932017-11-07 14:29:47 -08002130 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002131
2132 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002133 }
David Sodman4a36e932017-11-07 14:29:47 -08002134 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002135 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002136
2137 {
2138 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002139 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002140 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002141 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002142 if (refillCount > 0) {
2143 const size_t offset = mTexturePool.size();
2144 mTexturePool.resize(mTexturePoolSize);
2145 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2146 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2147 }
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002149 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002150
Marissa Wallfda30bb2018-10-12 11:34:28 -07002151 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002152 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002153
2154 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002155}
Ady Abraham8164d482019-01-11 14:47:59 -08002156#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002157
Vishnu Nair4351ad52019-02-11 14:13:02 -08002158void SurfaceFlinger::computeLayerBounds() {
2159 for (const auto& pair : mDisplays) {
2160 const auto& displayDevice = pair.second;
2161 const auto display = displayDevice->getCompositionDisplay();
2162 for (const auto& layer : mDrawingState.layersSortedByZ) {
2163 // only consider the layers on the given layer stack
2164 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002165 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002166 }
2167
2168 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2169 }
2170 }
2171}
2172
Mathias Agopiancd60f992012-08-16 16:28:27 -07002173void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 ATRACE_CALL();
2175 ALOGV("rebuildLayerStacks");
2176
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002177 // We need to clear these out now as these may be holding on to a
2178 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2179 // also holds a reference. When the set of visible layers is recomputed,
2180 // some layers may be destroyed if the only thing keeping them alive was
2181 // that list of visible layers associated with each display. The layer
2182 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2183 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2184 for (const auto& [token, display] : mDisplays) {
2185 getBE().mCompositionInfo[token].clear();
2186 }
2187
Mathias Agopiancd60f992012-08-16 16:28:27 -07002188 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002189 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002190 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002191 mVisibleRegionsDirty = false;
2192 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002193
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002194 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002195 const auto& displayDevice = pair.second;
2196 auto display = displayDevice->getCompositionDisplay();
2197 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002198 Region opaqueRegion;
2199 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002200 compositionengine::Output::OutputLayers layersSortedByZ;
2201 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002202 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002203 const ui::Transform& tr = displayState.transform;
2204 const Rect bounds = displayState.bounds;
2205 if (displayState.isEnabled) {
2206 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002207
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002209 auto compositionLayer = layer->getCompositionLayer();
2210 if (compositionLayer == nullptr) {
2211 return;
2212 }
2213
Lloyd Pique32cbe282018-10-19 13:09:22 -07002214 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002215 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2216 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2217
Lloyd Pique07e33212018-12-18 16:33:37 -08002218 bool needsOutputLayer = false;
2219
Lloyd Piqueef36b002019-01-23 17:52:04 -08002220 if (display->belongsInOutput(layer->getLayerStack(),
2221 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002222 Region drawRegion(tr.transform(
2223 layer->visibleNonTransparentRegion));
2224 drawRegion.andSelf(bounds);
2225 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002226 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002227 }
Chia-I Wu83806892017-11-16 10:50:20 -08002228 }
2229
Lloyd Pique07e33212018-12-18 16:33:37 -08002230 if (needsOutputLayer) {
2231 layersSortedByZ.emplace_back(
2232 display->getOrCreateOutputLayer(displayId, compositionLayer,
2233 layerFE));
2234 deprecated_layersSortedByZ.add(layer);
2235
2236 auto& outputLayerState = layersSortedByZ.back()->editState();
2237 outputLayerState.visibleRegion =
2238 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2239 } else if (displayId) {
2240 // For layers that are being removed from a HWC display,
2241 // and that have queued frames, add them to a a list of
2242 // released layers so we can properly set a fence.
2243 bool hasExistingOutputLayer =
2244 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2245 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2246 mLayersWithQueuedFrames.cend(),
2247 layer) != mLayersWithQueuedFrames.cend();
2248
2249 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002250 layersNeedingFences.add(layer);
2251 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002252 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002253 });
2254 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002255
2256 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2257
2258 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002259 displayDevice->setLayersNeedingFences(layersNeedingFences);
2260
2261 Region undefinedRegion{bounds};
2262 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2263
2264 display->editState().undefinedRegion = undefinedRegion;
2265 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002266 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002267 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002268}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002269
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002271// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002272// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002274// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002275// The returned HDR data space is one of
2276// - Dataspace::UNKNOWN
2277// - Dataspace::BT2020_HLG
2278// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2280 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002281 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 *outHdrDataSpace = Dataspace::UNKNOWN;
2283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002285 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286 case Dataspace::V0_SCRGB:
2287 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002288 case Dataspace::BT2020:
2289 case Dataspace::BT2020_ITU:
2290 case Dataspace::BT2020_LINEAR:
2291 case Dataspace::DISPLAY_BT2020:
2292 bestDataSpace = Dataspace::DISPLAY_BT2020;
2293 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002295 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 case Dataspace::BT2020_PQ:
2298 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002299 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002302 case Dataspace::BT2020_HLG:
2303 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002304 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002305 // When there's mixed PQ content and HLG content, we set the HDR
2306 // data space to be BT2020_PQ and convert HLG to PQ.
2307 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2308 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002309 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 break;
2311 default:
2312 break;
2313 }
Romain Guy54f154a2017-10-24 21:40:32 +01002314 }
2315
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002316 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002317}
2318
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002320void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2321 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002322 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2323 *outMode = ColorMode::NATIVE;
2324 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002327 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002328
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002332 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2333
Peiyong Lina3ea5592019-02-10 14:45:00 -08002334 switch (mForceColorMode) {
2335 case ColorMode::SRGB:
2336 bestDataSpace = Dataspace::V0_SRGB;
2337 break;
2338 case ColorMode::DISPLAY_P3:
2339 bestDataSpace = Dataspace::DISPLAY_P3;
2340 break;
2341 default:
2342 break;
2343 }
2344
Peiyong Lindfde5112018-06-05 10:58:41 -07002345 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002346 const bool isHdr =
2347 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002348 if (isHdr) {
2349 bestDataSpace = hdrDataSpace;
2350 }
2351
Chia-I Wu0d711262018-05-21 15:19:35 -07002352 RenderIntent intent;
2353 switch (mDisplayColorSetting) {
2354 case DisplayColorSetting::MANAGED:
2355 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002356 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002357 break;
2358 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002359 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002360 break;
2361 default: // vendor display color setting
2362 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2363 break;
2364 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002365
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002366 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002367}
2368
Lloyd Pique32cbe282018-10-19 13:09:22 -07002369void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2370 auto display = displayDevice->getCompositionDisplay();
2371 const auto& displayState = display->getState();
2372
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002373 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002374 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2375 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002376
David Sodmanfa9b2af2017-12-24 13:28:59 -08002377 // If nothing has changed (!dirty), don't recompose.
2378 // If something changed, but we don't currently have any visible layers,
2379 // and didn't when we last did a composition, then skip it this time.
2380 // The second rule does two things:
2381 // - When all layers are removed from a display, we'll emit one black
2382 // frame, then nothing more until we get new layers.
2383 // - When a display is created with a private layer stack, we won't
2384 // emit any black frames until a layer is added to the layer stack.
2385 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002386
Dominik Laskowski075d3172018-05-24 15:50:06 -07002387 const char flagPrefix[] = {'-', '+'};
2388 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2390 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2391 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2392 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002393
Lloyd Pique31cb2942018-10-19 17:23:03 -07002394 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002395
David Sodmanfa9b2af2017-12-24 13:28:59 -08002396 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002397 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002398 }
2399}
2400
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2402 auto display = displayDevice->getCompositionDisplay();
2403 const auto& displayState = display->getState();
2404
2405 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002406 return;
David Sodman2b406362017-12-15 13:33:47 -08002407 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002408
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002409 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002412}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002413
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002415 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 ALOGV("doComposition");
2417
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 auto display = displayDevice->getCompositionDisplay();
2419 const auto& displayState = display->getState();
2420
2421 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002422 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002423 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002424
David Sodmanfa9b2af2017-12-24 13:28:59 -08002425 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002426 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002427
Lloyd Pique32cbe282018-10-19 13:09:22 -07002428 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002429 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002430 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002432}
2433
David Sodmanfa9b2af2017-12-24 13:28:59 -08002434void SurfaceFlinger::postFrame()
2435{
2436 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002437 const auto display = getDefaultDisplayDeviceLocked();
2438 if (display && getHwComposer().isConnected(*display->getId())) {
2439 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2441 logFrameStats();
2442 }
2443 }
2444}
2445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002447 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002449
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 auto display = displayDevice->getCompositionDisplay();
2451 const auto& displayState = display->getState();
2452 const auto displayId = display->getId();
2453
David Sodmanfa9b2af2017-12-24 13:28:59 -08002454 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002455
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002457 if (displayId) {
2458 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002459 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002460 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002462 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002463
Chia-I Wu7b549592017-11-15 09:14:57 -08002464 // The layer buffer from the previous frame (if any) is released
2465 // by HWC only when the release fence from this frame (if any) is
2466 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002467 if (displayId && layer->hasHwcLayer(displayDevice)) {
2468 releaseFence =
2469 getHwComposer().getLayerReleaseFence(*displayId,
2470 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002471 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002472
2473 // If the layer was client composited in the previous frame, we
2474 // need to merge with the previous client target acquire fence.
2475 // Since we do not track that, always merge with the current
2476 // client target acquire fence when it is available, even though
2477 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002478 if (layer->getCompositionType(displayDevice) ==
2479 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002480 releaseFence =
2481 Fence::merge("LayerRelease", releaseFence,
2482 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002483 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002484
David Sodman15094112018-10-11 09:39:37 -07002485 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 }
Chia-I Wu83806892017-11-16 10:50:20 -08002487
2488 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002489 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002490 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002493 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002494 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002495 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002496 }
2497 }
2498
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 if (displayId) {
2500 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002501 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002502 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503}
2504
Mathias Agopian87baae12012-07-31 12:38:26 -07002505void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506{
Mathias Agopian841cde52012-03-01 15:44:37 -08002507 ATRACE_CALL();
2508
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002509 // here we keep a copy of the drawing state (that is the state that's
2510 // going to be overwritten by handleTransactionLocked()) outside of
2511 // mStateLock so that the side-effects of the State assignment
2512 // don't happen with mStateLock held (which can cause deadlocks).
2513 State drawingState(mDrawingState);
2514
Mathias Agopianca4d3602011-05-19 15:38:14 -07002515 Mutex::Autolock _l(mStateLock);
2516 const nsecs_t now = systemTime();
2517 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
Mathias Agopianca4d3602011-05-19 15:38:14 -07002519 // Here we're guaranteed that some transaction flags are set
2520 // so we can call handleTransactionLocked() unconditionally.
2521 // We call getTransactionFlags(), which will also clear the flags,
2522 // with mStateLock held to guarantee that mCurrentState won't change
2523 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002524
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002525 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002526 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002527 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002528
Mathias Agopianca4d3602011-05-19 15:38:14 -07002529 mLastTransactionTime = systemTime() - now;
2530 mDebugInTransaction = 0;
2531 invalidateHwcGeometry();
2532 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002533}
2534
Lloyd Piqueba04e622017-12-14 17:11:26 -08002535void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2536 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002537 const std::optional<DisplayIdentificationInfo> info =
2538 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002539
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002541 continue;
2542 }
2543
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002546 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002547 mPhysicalDisplayTokens[info->id] = new BBinder();
2548 DisplayDeviceState state;
2549 state.displayId = info->id;
2550 state.isSecure = true; // All physical displays are currently considered secure.
2551 state.displayName = info->name;
2552 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2553 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002554 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002555 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002556 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002557
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2559 if (index >= 0) {
2560 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2561 mInterceptor->saveDisplayDeletion(state.sequenceId);
2562 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002563 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002565 }
2566
2567 processDisplayChangesLocked();
2568 }
2569
2570 mPendingHotplugEvents.clear();
2571}
2572
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002573void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002574 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2575 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002576}
2577
Lloyd Pique99d3da52018-01-22 17:48:03 -08002578sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002580 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002581 const sp<IGraphicBufferProducer>& producer) {
2582 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002583 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002585 creationArgs.isSecure = state.isSecure;
2586 creationArgs.displaySurface = dispSurface;
2587 creationArgs.hasWideColorGamut = false;
2588 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002589
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002590 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 creationArgs.isPrimary = isInternalDisplay;
2592
2593 if (useColorManagement && displayId) {
2594 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002595 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002596 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002597 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002599
Dominik Laskowski7e045462018-05-30 13:02:02 -07002600 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002602 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002603 }
tangrobin6753a022018-08-10 10:58:54 +08002604 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002605
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 if (displayId) {
2607 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002608 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002610 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611
Lloyd Pique90c115d2018-09-18 21:39:42 -07002612 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002614 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 // Make sure that composition can never be stalled by a virtual display
2617 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002618 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002619 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2621 }
2622
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 creationArgs.displayInstallOrientation =
2624 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002625
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002627 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628
Lloyd Pique90c115d2018-09-18 21:39:42 -07002629 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630
2631 if (maxFrameBufferAcquiredBuffers >= 3) {
2632 nativeWindowSurface->preallocateBuffers();
2633 }
2634
2635 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002636 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002637 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002639 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002640 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002641 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2642 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 if (!state.isVirtual()) {
2644 LOG_ALWAYS_FATAL_IF(!displayId);
2645 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002646 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002648 display->setLayerStack(state.layerStack);
2649 display->setProjection(state.orientation, state.viewport, state.frame);
2650 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653}
2654
Lloyd Pique347200f2017-12-14 17:00:15 -08002655void SurfaceFlinger::processDisplayChangesLocked() {
2656 // here we take advantage of Vector's copy-on-write semantics to
2657 // improve performance by skipping the transaction entirely when
2658 // know that the lists are identical
2659 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2660 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2661 if (!curr.isIdenticalTo(draw)) {
2662 mVisibleRegionsDirty = true;
2663 const size_t cc = curr.size();
2664 size_t dc = draw.size();
2665
2666 // find the displays that were removed
2667 // (ie: in drawing state but not in current state)
2668 // also handle displays that changed
2669 // (ie: displays that are in both lists)
2670 for (size_t i = 0; i < dc;) {
2671 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2672 if (j < 0) {
2673 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002675 // Save display ID before disconnecting.
2676 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002677 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002678
2679 if (!display->isVirtual()) {
2680 LOG_ALWAYS_FATAL_IF(!displayId);
2681 dispatchDisplayHotplugEvent(displayId->value, false);
2682 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002684
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002685 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 } else {
2687 // this display is in both lists. see if something changed.
2688 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002690 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2691 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2692 if (state_binder != draw_binder) {
2693 // changing the surface is like destroying and
2694 // recreating the DisplayDevice, so we just remove it
2695 // from the drawing state, so that it get re-added
2696 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002698 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002699 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 mDrawingState.displays.removeItemsAt(i);
2702 dc--;
2703 // at this point we must loop to the next item
2704 continue;
2705 }
2706
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002707 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 }
2711 if ((state.orientation != draw[i].orientation) ||
2712 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 }
2715 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002716 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 }
2718 }
2719 }
2720 ++i;
2721 }
2722
2723 // find displays that were added
2724 // (ie: in current state but not in drawing state)
2725 for (size_t i = 0; i < cc; i++) {
2726 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2727 const DisplayDeviceState& state(curr[i]);
2728
Lloyd Pique542307f2018-10-19 13:24:08 -07002729 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 sp<IGraphicBufferProducer> producer;
2731 sp<IGraphicBufferProducer> bqProducer;
2732 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002733 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002734
Dominik Laskowski075d3172018-05-24 15:50:06 -07002735 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002736 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 // Virtual displays without a surface are dormant:
2738 // they have external state (layer stack, projection,
2739 // etc.) but no internal state (i.e. a DisplayDevice).
2740 if (state.surface != nullptr) {
2741 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002742 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 int width = 0;
2744 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2745 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2746 int height = 0;
2747 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2748 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2749 int intFormat = 0;
2750 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2751 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002752 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002753
Dominik Laskowski075d3172018-05-24 15:50:06 -07002754 displayId =
2755 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 }
2757
2758 // TODO: Plumb requested format back up to consumer
2759
2760 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002761 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 bqProducer, bqConsumer,
2763 state.displayName);
2764
2765 dispSurface = vds;
2766 producer = vds;
2767 }
2768 } else {
2769 ALOGE_IF(state.surface != nullptr,
2770 "adding a supported display, but rendering "
2771 "surface is provided (%p), ignoring it",
2772 state.surface.get());
2773
Dominik Laskowski075d3172018-05-24 15:50:06 -07002774 displayId = state.displayId;
2775 LOG_ALWAYS_FATAL_IF(!displayId);
2776 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 producer = bqProducer;
2778 }
2779
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002780 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002783 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002784 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002785 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002787 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 }
2789 }
2790 }
2791 }
2792 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002793
2794 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002795}
2796
Mathias Agopian87baae12012-07-31 12:38:26 -07002797void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002798{
Dan Stoza7dde5992015-05-22 09:51:44 -07002799 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002800 mCurrentState.traverseInZOrder([](Layer* layer) {
2801 layer->notifyAvailableFrames();
2802 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 /*
2805 * Traversal of the children
2806 * (perform the transaction for each of them if needed)
2807 */
2808
Mathias Agopian3559b072012-08-15 13:46:03 -07002809 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002812 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813
2814 const uint32_t flags = layer->doTransaction(0);
2815 if (flags & Layer::eVisibleRegion)
2816 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002817
2818 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002819 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002820 }
Robert Carr2047fae2016-11-28 14:09:09 -08002821 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 }
2823
2824 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002825 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 */
2827
Mathias Agopiane57f2922012-08-09 16:29:12 -07002828 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002829 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002830 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002831 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002833 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002834 // The transform hint might have changed for some layers
2835 // (either because a display has changed, or because a layer
2836 // as changed).
2837 //
2838 // Walk through all the layers in currentLayers,
2839 // and update their transform hint.
2840 //
2841 // If a layer is visible only on a single display, then that
2842 // display is used to calculate the hint, otherwise we use the
2843 // default display.
2844 //
2845 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2846 // the hint is set before we acquire a buffer from the surface texture.
2847 //
2848 // NOTE: layer transactions have taken place already, so we use their
2849 // drawing state. However, SurfaceFlinger's own transaction has not
2850 // happened yet, so we must use the current state layer list
2851 // (soon to become the drawing state list).
2852 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002854 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002855 bool first = true;
2856 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002857 // NOTE: we rely on the fact that layers are sorted by
2858 // layerStack first (so we don't have to traverse the list
2859 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002861 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002862 currentlayerStack = layerStack;
2863 // figure out if this layerstack is mirrored
2864 // (more than one display) if so, pick the default display,
2865 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 hintDisplay = nullptr;
2867 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002868 if (display->getCompositionDisplay()
2869 ->belongsInOutput(layer->getLayerStack(),
2870 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 if (hintDisplay) {
2872 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002873 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002874 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002875 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002876 }
2877 }
2878 }
2879 }
Chet Haase91d25932013-04-11 15:24:55 -07002880
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002882 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2883 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002884
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002885 // could be null when this layer is using a layerStack
2886 // that is not visible on any display. Also can occur at
2887 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002889 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002890
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002891 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002892 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 if (hintDisplay) {
2894 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002895 }
Robert Carr2047fae2016-11-28 14:09:09 -08002896
2897 first = false;
2898 });
Mathias Agopian84300952012-11-21 16:02:13 -08002899 }
2900
2901
Mathias Agopian3559b072012-08-15 13:46:03 -07002902 /*
2903 * Perform our own transaction if needed
2904 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905
2906 if (mLayersAdded) {
2907 mLayersAdded = false;
2908 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002909 mVisibleRegionsDirty = true;
2910 }
2911
2912 // some layers might have been removed, so
2913 // we need to update the regions they're exposing.
2914 if (mLayersRemoved) {
2915 mLayersRemoved = false;
2916 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002917 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002919 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002921 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002922 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002923 }
Robert Carr2047fae2016-11-28 14:09:09 -08002924 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002925 }
2926
Vishnu Nairec0ab382019-02-13 15:32:56 -08002927 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002929}
2930
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002931void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002932 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002933 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002934 return;
2935 }
2936
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002937 if (mVisibleRegionsDirty || mInputInfoChanged) {
2938 mInputInfoChanged = false;
2939 updateInputWindowInfo();
2940 }
2941
2942 executeInputWindowCommands();
2943}
2944
2945void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002946 Vector<InputWindowInfo> inputHandles;
2947
2948 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2949 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002950 // When calculating the screen bounds we ignore the transparent region since it may
2951 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002952 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002953 }
2954 });
2955 mInputFlinger->setInputWindows(inputHandles);
2956}
2957
Vishnu Nairec0ab382019-02-13 15:32:56 -08002958void SurfaceFlinger::commitInputWindowCommands() {
2959 mInputWindowCommands.merge(mPendingInputWindowCommands);
2960 mPendingInputWindowCommands.clear();
2961}
2962
chaviwfbe5d9c2018-12-26 12:23:37 -08002963void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002964 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2965 if (transferTouchFocusCommand.fromToken != nullptr &&
2966 transferTouchFocusCommand.toToken != nullptr &&
2967 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2968 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2969 transferTouchFocusCommand.toToken);
2970 }
2971 }
2972
2973 mInputWindowCommands.clear();
2974}
2975
Riley Andrews03414a12014-07-01 14:22:59 -07002976void SurfaceFlinger::updateCursorAsync()
2977{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002978 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002979 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002980 continue;
2981 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002983 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2984 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002985 }
2986 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002987}
2988
chaviw61626f22018-11-15 16:26:27 -08002989void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2990 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002991 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08002992 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08002993 }
2994 layer->releasePendingBuffer(systemTime());
2995}
2996
Mathias Agopian4fec8732012-06-29 14:12:52 -07002997void SurfaceFlinger::commitTransaction()
2998{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002999 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003001 for (const auto& l : mLayersPendingRemoval) {
3002 recordBufferingStats(l->getName().string(),
3003 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003004
Lloyd Pique07e33212018-12-18 16:33:37 -08003005 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003006 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003007 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003008 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009 }
3010 mLayersPendingRemoval.clear();
3011 }
3012
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003013 // If this transaction is part of a window animation then the next frame
3014 // we composite should be considered an animation as well.
3015 mAnimCompositionPending = mAnimTransactionPending;
3016
Mathias Agopian4fec8732012-06-29 14:12:52 -07003017 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003018 // clear the "changed" flags in current state
3019 mCurrentState.colorMatrixChanged = false;
3020
Robert Carr1f0a16a2016-10-24 16:27:39 -07003021 mDrawingState.traverseInZOrder([](Layer* layer) {
3022 layer->commitChildList();
3023 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003024 mTransactionPending = false;
3025 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003026 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027}
3028
Lloyd Pique32cbe282018-10-19 13:09:22 -07003029void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003031 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003033
Lloyd Pique32cbe282018-10-19 13:09:22 -07003034 auto display = displayDevice->getCompositionDisplay();
3035
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036 Region aboveOpaqueLayers;
3037 Region aboveCoveredLayers;
3038 Region dirty;
3039
Mathias Agopian87baae12012-07-31 12:38:26 -07003040 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041
Robert Carr2047fae2016-11-28 14:09:09 -08003042 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003043 // start with the whole surface at its current location
3044 const Layer::State& s(layer->getDrawingState());
3045
Jesse Hall01e29052013-02-19 16:13:35 -08003046 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003047 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003048 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003050
Mathias Agopianab028732010-03-16 16:41:46 -07003051 /*
3052 * opaqueRegion: area of a surface that is fully opaque.
3053 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003055
3056 /*
3057 * visibleRegion: area of a surface that is visible on screen
3058 * and not fully transparent. This is essentially the layer's
3059 * footprint minus the opaque regions above it.
3060 * Areas covered by a translucent surface are considered visible.
3061 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003063
3064 /*
3065 * coveredRegion: area of a surface that is covered by all
3066 * visible regions above it (which includes the translucent areas).
3067 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003069
Jesse Halla8026d22012-09-25 13:25:04 -07003070 /*
3071 * transparentRegion: area of a surface that is hinted to be completely
3072 * transparent. This is only used to tell when the layer has no visible
3073 * non-transparent regions and can be removed from the layer list. It
3074 * does not affect the visibleRegion of this layer or any layers
3075 * beneath it. The hint may not be correct if apps don't respect the
3076 * SurfaceView restrictions (which, sadly, some don't).
3077 */
3078 Region transparentRegion;
3079
Mathias Agopianab028732010-03-16 16:41:46 -07003080
3081 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003082 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003083 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003084 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003086 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003087 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003088 if (!visibleRegion.isEmpty()) {
3089 // Remove the transparent area from the visible region
3090 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003091 if (tr.preserveRects()) {
3092 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003093 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003094 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003095 // transformation too complex, can't do the
3096 // transparent region optimization.
3097 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003098 }
Mathias Agopianab028732010-03-16 16:41:46 -07003099 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100
Mathias Agopianab028732010-03-16 16:41:46 -07003101 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003102 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003103 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003104 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003105 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003106 // the opaque region is the layer's footprint
3107 opaqueRegion = visibleRegion;
3108 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 }
3110 }
3111
Robert Carre5f4f692018-01-12 13:12:28 -08003112 if (visibleRegion.isEmpty()) {
3113 layer->clearVisibilityRegions();
3114 return;
3115 }
3116
Mathias Agopianab028732010-03-16 16:41:46 -07003117 // Clip the covered region to the visible region
3118 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3119
3120 // Update aboveCoveredLayers for next (lower) layer
3121 aboveCoveredLayers.orSelf(visibleRegion);
3122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 // subtract the opaque region covered by the layers above us
3124 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125
3126 // compute this layer's dirty region
3127 if (layer->contentDirty) {
3128 // we need to invalidate the whole region
3129 dirty = visibleRegion;
3130 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003131 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132 layer->contentDirty = false;
3133 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003134 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003135 * the exposed region consists of two components:
3136 * 1) what's VISIBLE now and was COVERED before
3137 * 2) what's EXPOSED now less what was EXPOSED before
3138 *
3139 * note that (1) is conservative, we start with the whole
3140 * visible region but only keep what used to be covered by
3141 * something -- which mean it may have been exposed.
3142 *
3143 * (2) handles areas that were not covered by anything but got
3144 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003145 */
Mathias Agopianab028732010-03-16 16:41:46 -07003146 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003147 const Region oldVisibleRegion = layer->visibleRegion;
3148 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003149 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3150 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 }
3152 dirty.subtractSelf(aboveOpaqueLayers);
3153
3154 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003155 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156
Mathias Agopianab028732010-03-16 16:41:46 -07003157 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003159
Jesse Halla8026d22012-09-25 13:25:04 -07003160 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 layer->setVisibleRegion(visibleRegion);
3162 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003163 layer->setVisibleNonTransparentRegion(
3164 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003165 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166
Mathias Agopian87baae12012-07-31 12:38:26 -07003167 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168}
3169
Chia-I Wuab0c3192017-08-01 11:29:00 -07003170void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003171 for (const auto& [token, displayDevice] : mDisplays) {
3172 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003173 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003174 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003175 }
3176 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003177}
3178
Daniel Solomon42d04562019-01-20 21:03:19 -08003179void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3180 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3181 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3182 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3183 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3184 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3185 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3186 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3187 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3188 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3189 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3190 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3191 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3192}
3193
Dan Stoza6b9454d2014-11-07 16:00:59 -08003194bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003196 ALOGV("handlePageFlip");
3197
Brian Andersond6927fb2016-07-23 23:37:30 -07003198 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199
Mathias Agopian4fec8732012-06-29 14:12:52 -07003200 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003201 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003202 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003203
3204 // Store the set of layers that need updates. This set must not change as
3205 // buffers are being latched, as this could result in a deadlock.
3206 // Example: Two producers share the same command stream and:
3207 // 1.) Layer 0 is latched
3208 // 2.) Layer 0 gets a new frame
3209 // 2.) Layer 1 gets a new frame
3210 // 3.) Layer 1 is latched.
3211 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3212 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003213 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003214 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003215 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003216 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003217 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003218 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003219 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003220 } else {
3221 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003222 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003223 } else {
3224 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003225 }
Robert Carr2047fae2016-11-28 14:09:09 -08003226 });
3227
Lloyd Piquef2c79392018-12-20 16:23:33 -08003228 if (!mLayersWithQueuedFrames.empty()) {
3229 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3230 // writes to Layer current state. See also b/119481871
3231 Mutex::Autolock lock(mStateLock);
3232
3233 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003234 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003235 mLayersPendingRefresh.push_back(layer);
3236 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003237 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003238 if (layer->isBufferLatched()) {
3239 newDataLatched = true;
3240 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003241 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003242 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003243
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003244 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003245
3246 // If we will need to wake up at some time in the future to deal with a
3247 // queued frame that shouldn't be displayed during this vsync period, wake
3248 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003249 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003250 signalLayerUpdate();
3251 }
3252
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003253 // enter boot animation on first buffer latch
3254 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3255 ALOGI("Enter boot animation");
3256 mBootStage = BootStage::BOOTANIMATION;
3257 }
3258
Dan Stoza6b9454d2014-11-07 16:00:59 -08003259 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003260 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261}
3262
Mathias Agopianad456f92011-01-13 17:53:01 -08003263void SurfaceFlinger::invalidateHwcGeometry()
3264{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003265 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003266}
3267
Lloyd Pique32cbe282018-10-19 13:09:22 -07003268void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003269 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003270 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003271 // We only need to actually compose the display if:
3272 // 1) It is being handled by hardware composer, which may need this to
3273 // keep its virtual display state machine in sync, or
3274 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003275 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003276 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003277 return;
3278 }
3279
Dan Stoza9e56aa02015-11-02 13:00:03 -08003280 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003281 base::unique_fd readyFence;
3282 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003283
3284 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003285 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286}
3287
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003288bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3289 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003290 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003291 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003292
Lloyd Pique32cbe282018-10-19 13:09:22 -07003293 auto display = displayDevice->getCompositionDisplay();
3294 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003295 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003296
3297 const Region bounds(displayState.bounds);
3298 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003299 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003300 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003301
Peiyong Lind3788632018-09-18 16:01:31 -07003302 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003303 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003304
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003305 renderengine::DisplaySettings clientCompositionDisplay;
3306 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3307 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003308
Dan Stoza9e56aa02015-11-02 13:00:03 -08003309 if (hasClientComposition) {
3310 ALOGV("hasClientComposition");
3311
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003312 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003313
3314 if (buf == nullptr) {
3315 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3316 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003317 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003318 return false;
3319 }
3320
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003321 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3322 clientCompositionDisplay.clip = displayState.scissor;
3323 const ui::Transform& displayTransform = displayState.transform;
3324 mat4 m;
3325 m[0][0] = displayTransform[0][0];
3326 m[0][1] = displayTransform[0][1];
3327 m[0][3] = displayTransform[0][2];
3328 m[1][0] = displayTransform[1][0];
3329 m[1][1] = displayTransform[1][1];
3330 m[1][3] = displayTransform[1][2];
3331 m[3][0] = displayTransform[2][0];
3332 m[3][1] = displayTransform[2][1];
3333 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003334
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003335 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003336
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003337 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003338 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003339 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003340 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003341 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003342 clientCompositionDisplay.outputDataspace = outputDataspace;
3343 clientCompositionDisplay.maxLuminance =
3344 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003345
Lloyd Pique441d5042018-10-18 16:49:51 -07003346 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003347 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003348 getHwComposer()
3349 .hasDisplayCapability(displayId,
3350 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003351
Peiyong Lind3788632018-09-18 16:01:31 -07003352 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003353 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3354 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003355 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003356 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003357 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003358
Mathias Agopian85d751c2012-08-29 16:59:24 -07003359 /*
3360 * and then, render the layers targeted at the framebuffer
3361 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003362
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003364 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003365 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003366 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003367 const Region viewportRegion(displayState.viewport);
3368 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003369 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003370 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003371 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003372 switch (layer->getCompositionType(displayDevice)) {
3373 case Hwc2::IComposerClient::Composition::CURSOR:
3374 case Hwc2::IComposerClient::Composition::DEVICE:
3375 case Hwc2::IComposerClient::Composition::SIDEBAND:
3376 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003377 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003378 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003379 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003380 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003381 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003382 // never clear the very first layer since we're
3383 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003384 renderengine::LayerSettings layerSettings;
3385 Region dummyRegion;
3386 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3387 layerSettings);
3388
3389 if (prepared) {
3390 layerSettings.source.buffer.buffer = nullptr;
3391 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3392 layerSettings.alpha = half(0.0);
3393 layerSettings.disableBlending = true;
3394 clientCompositionLayers.push_back(layerSettings);
3395 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003396 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003397 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003398 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003399 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003400 renderengine::LayerSettings layerSettings;
3401 bool prepared =
3402 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3403 if (prepared) {
3404 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003405 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003406 break;
3407 }
3408 default:
3409 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003410 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003411 } else {
3412 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003413 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003414 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003415 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003416
Alec Mouri820c7402019-01-23 13:02:39 -08003417 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003418 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003419 clientCompositionDisplay.clearRegion = clearRegion;
3420 if (!debugRegion.isEmpty()) {
3421 Region::const_iterator it = debugRegion.begin();
3422 Region::const_iterator end = debugRegion.end();
3423 while (it != end) {
3424 const Rect& rect = *it++;
3425 renderengine::LayerSettings layerSettings;
3426 layerSettings.source.buffer.buffer = nullptr;
3427 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3428 layerSettings.geometry.boundaries = rect.toFloatRect();
3429 layerSettings.alpha = half(1.0);
3430 clientCompositionLayers.push_back(layerSettings);
3431 }
3432 }
3433 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3434 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003435 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003436 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003437}
3438
Chia-I Wu28e3a252018-09-07 12:05:02 -07003439void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003440 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003441 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003442}
3443
Dan Stoza7d89d062015-04-30 13:29:25 -07003444status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003445 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003446 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003447 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003448 const sp<Layer>& parent,
3449 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003450{
Dan Stoza7d89d062015-04-30 13:29:25 -07003451 // add this layer to the current state list
3452 {
3453 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003454 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003455 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3456 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003457 return NO_MEMORY;
3458 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003459 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003460 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003461 } else if (parent == nullptr) {
3462 lbc->onRemovedFromCurrentState();
3463 } else if (parent->isRemovedFromCurrentState()) {
3464 parent->addChild(lbc);
3465 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003466 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003467 parent->addChild(lbc);
3468 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003469
Yiwei Zhang243b3782018-05-15 17:40:04 -07003470 if (gbc != nullptr) {
3471 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3472 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3473 mMaxGraphicBufferProducerListSize,
3474 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3475 mGraphicBufferProducerList.size(),
3476 mMaxGraphicBufferProducerListSize, mNumLayers);
3477 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003478 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003479 }
3480
Mathias Agopian96f08192010-06-02 23:28:45 -07003481 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003482 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003483
Dan Stoza7d89d062015-04-30 13:29:25 -07003484 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003485}
3486
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003487uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003488 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003489}
3490
Mathias Agopian3f844832013-08-07 21:24:32 -07003491uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003492 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003493}
3494
Mathias Agopian3f844832013-08-07 21:24:32 -07003495uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003496 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003497}
3498
3499uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003500 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003501 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003502 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003504 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 }
3506 return old;
3507}
3508
Marissa Wall713b63f2018-10-17 15:42:43 -07003509bool SurfaceFlinger::flushTransactionQueues() {
3510 Mutex::Autolock _l(mStateLock);
3511 auto it = mTransactionQueues.begin();
3512 while (it != mTransactionQueues.end()) {
3513 auto& [applyToken, transactionQueue] = *it;
3514
3515 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003516 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3517 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003518 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003519 break;
3520 }
Robert Carr14167e02019-02-13 13:50:55 -08003521 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003522 transactionQueue.pop();
3523 }
3524
3525 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3526 }
3527 return mTransactionQueues.empty();
3528}
3529
chaviwca27f252018-02-06 16:46:39 -08003530bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3531 for (const ComposerState& state : states) {
3532 // Here we need to check that the interface we're given is indeed
3533 // one of our own. A malicious client could give us a nullptr
3534 // IInterface, or one of its own or even one of our own but a
3535 // different type. All these situations would cause us to crash.
3536 if (state.client == nullptr) {
3537 return true;
3538 }
3539
3540 sp<IBinder> binder = IInterface::asBinder(state.client);
3541 if (binder == nullptr) {
3542 return true;
3543 }
3544
3545 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3546 return true;
3547 }
3548 }
3549 return false;
3550}
3551
Marissa Wall17b4e452018-12-26 16:32:34 -08003552bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3553 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003554 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003555 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3556 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3557 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3558 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3559 return false;
3560 }
3561
Marissa Wall713b63f2018-10-17 15:42:43 -07003562 for (const ComposerState& state : states) {
3563 const layer_state_t& s = state.state;
3564 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3565 continue;
3566 }
3567 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003568 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003569 }
3570 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003571 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003572}
3573
3574void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3575 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003576 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003577 const InputWindowCommands& inputWindowCommands,
3578 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003579 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003580
3581 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3582
Mathias Agopian698c0872011-06-28 19:09:31 -07003583 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003584
chaviwca27f252018-02-06 16:46:39 -08003585 if (containsAnyInvalidClientState(states)) {
3586 return;
3587 }
3588
Marissa Wall713b63f2018-10-17 15:42:43 -07003589 // If its TransactionQueue already has a pending TransactionState or if it is pending
3590 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003591 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003592 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3593 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003594 setTransactionFlags(eTransactionNeeded);
3595 return;
3596 }
3597
Robert Carr14167e02019-02-13 13:50:55 -08003598 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003599}
3600
3601void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003602 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003603 const InputWindowCommands& inputWindowCommands,
3604 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003605 uint32_t transactionFlags = 0;
3606
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003607 if (flags & eAnimation) {
3608 // For window updates that are part of an animation we must wait for
3609 // previous animation "frames" to be handled.
3610 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003611 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003612 if (CC_UNLIKELY(err != NO_ERROR)) {
3613 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003614 // caller after a few seconds.
3615 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3616 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003617 mAnimTransactionPending = false;
3618 break;
3619 }
3620 }
3621 }
3622
chaviwca27f252018-02-06 16:46:39 -08003623 for (const DisplayState& display : displays) {
3624 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003625 }
3626
Marissa Walle2ffb422018-10-12 11:33:52 -07003627 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003628 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003629 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003630 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003631 // If the state doesn't require a traversal and there are callbacks, send them now
3632 if (!(clientStateFlags & eTraversalNeeded)) {
3633 mTransactionCompletedThread.sendCallbacks();
3634 }
3635 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003636
chaviw273171b2018-12-26 11:46:30 -08003637 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3638
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003639 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3640 // anyway. This can be used as a flush mechanism for previous async transactions.
3641 // Empty animation transaction can be used to simulate back-pressure, so also force a
3642 // transaction for empty animation transactions.
3643 if (transactionFlags == 0 &&
3644 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003645 transactionFlags = eTransactionNeeded;
3646 }
3647
Mathias Agopian386aa982011-11-07 21:58:03 -08003648 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003649 if (mInterceptor->isEnabled()) {
3650 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003651 }
Irvel468051e2016-06-13 16:44:44 -07003652
Mathias Agopian386aa982011-11-07 21:58:03 -08003653 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003654 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3655 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003656 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003657
3658 // if this is a synchronous transaction, wait for it to take effect
3659 // before returning.
3660 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003661 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003662 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003663 if (flags & eAnimation) {
3664 mAnimTransactionPending = true;
3665 }
3666 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003667 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3668 if (CC_UNLIKELY(err != NO_ERROR)) {
3669 // just in case something goes wrong in SF, return to the
3670 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003671 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3672 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003673 break;
3674 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003675 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003676 }
3677}
3678
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003679uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3680 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3681 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003682
Mathias Agopiane57f2922012-08-09 16:29:12 -07003683 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003684 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3685
3686 const uint32_t what = s.what;
3687 if (what & DisplayState::eSurfaceChanged) {
3688 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3689 state.surface = s.surface;
3690 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003691 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003692 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003693 if (what & DisplayState::eLayerStackChanged) {
3694 if (state.layerStack != s.layerStack) {
3695 state.layerStack = s.layerStack;
3696 flags |= eDisplayTransactionNeeded;
3697 }
3698 }
3699 if (what & DisplayState::eDisplayProjectionChanged) {
3700 if (state.orientation != s.orientation) {
3701 state.orientation = s.orientation;
3702 flags |= eDisplayTransactionNeeded;
3703 }
3704 if (state.frame != s.frame) {
3705 state.frame = s.frame;
3706 flags |= eDisplayTransactionNeeded;
3707 }
3708 if (state.viewport != s.viewport) {
3709 state.viewport = s.viewport;
3710 flags |= eDisplayTransactionNeeded;
3711 }
3712 }
3713 if (what & DisplayState::eDisplaySizeChanged) {
3714 if (state.width != s.width) {
3715 state.width = s.width;
3716 flags |= eDisplayTransactionNeeded;
3717 }
3718 if (state.height != s.height) {
3719 state.height = s.height;
3720 flags |= eDisplayTransactionNeeded;
3721 }
3722 }
3723
Mathias Agopiane57f2922012-08-09 16:29:12 -07003724 return flags;
3725}
3726
Robert Carr14167e02019-02-13 13:50:55 -08003727bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003728 IPCThreadState* ipc = IPCThreadState::self();
3729 const int pid = ipc->getCallingPid();
3730 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003731 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003732 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003733 return false;
3734 }
3735 return true;
3736}
3737
Robert Carr14167e02019-02-13 13:50:55 -08003738uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3739 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003740 const layer_state_t& s = composerState.state;
3741 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3742
Mathias Agopian13127d82013-03-05 17:47:11 -08003743 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003744 if (layer == nullptr) {
3745 return 0;
3746 }
3747
chaviw8b3871a2017-11-01 17:41:01 -07003748 uint32_t flags = 0;
3749
Garfield Tan8a3083e2018-12-03 13:21:07 -08003750 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003751 bool geometryAppliesWithResize =
3752 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003753
3754 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3755 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003756 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003757 layer->pushPendingState();
3758 }
3759
chaviw8b3871a2017-11-01 17:41:01 -07003760 if (what & layer_state_t::ePositionChanged) {
3761 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3762 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003763 }
chaviw8b3871a2017-11-01 17:41:01 -07003764 }
3765 if (what & layer_state_t::eLayerChanged) {
3766 // NOTE: index needs to be calculated before we update the state
3767 const auto& p = layer->getParent();
3768 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003769 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003770 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003771 mCurrentState.layersSortedByZ.removeAt(idx);
3772 mCurrentState.layersSortedByZ.add(layer);
3773 // we need traversal (state changed)
3774 // AND transaction (list changed)
3775 flags |= eTransactionNeeded|eTraversalNeeded;
3776 }
chaviw8b3871a2017-11-01 17:41:01 -07003777 } else {
3778 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003779 flags |= eTransactionNeeded|eTraversalNeeded;
3780 }
3781 }
chaviw8b3871a2017-11-01 17:41:01 -07003782 }
3783 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003784 // NOTE: index needs to be calculated before we update the state
3785 const auto& p = layer->getParent();
3786 if (p == nullptr) {
3787 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3788 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3789 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 }
3795 } else {
3796 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3797 flags |= eTransactionNeeded|eTraversalNeeded;
3798 }
chaviw8b3871a2017-11-01 17:41:01 -07003799 }
3800 }
3801 if (what & layer_state_t::eSizeChanged) {
3802 if (layer->setSize(s.w, s.h)) {
3803 flags |= eTraversalNeeded;
3804 }
3805 }
3806 if (what & layer_state_t::eAlphaChanged) {
3807 if (layer->setAlpha(s.alpha))
3808 flags |= eTraversalNeeded;
3809 }
3810 if (what & layer_state_t::eColorChanged) {
3811 if (layer->setColor(s.color))
3812 flags |= eTraversalNeeded;
3813 }
Peiyong Lind3788632018-09-18 16:01:31 -07003814 if (what & layer_state_t::eColorTransformChanged) {
3815 if (layer->setColorTransform(s.colorTransform)) {
3816 flags |= eTraversalNeeded;
3817 }
3818 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003819 if (what & layer_state_t::eBackgroundColorChanged) {
3820 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3821 flags |= eTraversalNeeded;
3822 }
3823 }
chaviw8b3871a2017-11-01 17:41:01 -07003824 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003825 // TODO: b/109894387
3826 //
3827 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3828 // rotation. To see the problem observe that if we have a square parent, and a child
3829 // of the same size, then we rotate the child 45 degrees around it's center, the child
3830 // must now be cropped to a non rectangular 8 sided region.
3831 //
3832 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3833 // private API, and the WindowManager only uses rotation in one case, which is on a top
3834 // level layer in which cropping is not an issue.
3835 //
3836 // However given that abuse of rotation matrices could lead to surfaces extending outside
3837 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3838 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3839 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003840 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003841 flags |= eTraversalNeeded;
3842 }
3843 if (what & layer_state_t::eTransparentRegionChanged) {
3844 if (layer->setTransparentRegionHint(s.transparentRegion))
3845 flags |= eTraversalNeeded;
3846 }
3847 if (what & layer_state_t::eFlagsChanged) {
3848 if (layer->setFlags(s.flags, s.mask))
3849 flags |= eTraversalNeeded;
3850 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003851 if (what & layer_state_t::eCropChanged_legacy) {
3852 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003853 flags |= eTraversalNeeded;
3854 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003855 if (what & layer_state_t::eCornerRadiusChanged) {
3856 if (layer->setCornerRadius(s.cornerRadius))
3857 flags |= eTraversalNeeded;
3858 }
chaviw8b3871a2017-11-01 17:41:01 -07003859 if (what & layer_state_t::eLayerStackChanged) {
3860 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3861 // We only allow setting layer stacks for top level layers,
3862 // everything else inherits layer stack from its parent.
3863 if (layer->hasParent()) {
3864 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3865 layer->getName().string());
3866 } else if (idx < 0) {
3867 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3868 "that also does not appear in the top level layer list. Something"
3869 " has gone wrong.", layer->getName().string());
3870 } else if (layer->setLayerStack(s.layerStack)) {
3871 mCurrentState.layersSortedByZ.removeAt(idx);
3872 mCurrentState.layersSortedByZ.add(layer);
3873 // we need traversal (state changed)
3874 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003875 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003876 }
3877 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003878 if (what & layer_state_t::eDeferTransaction_legacy) {
3879 if (s.barrierHandle_legacy != nullptr) {
3880 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3881 } else if (s.barrierGbp_legacy != nullptr) {
3882 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003883 if (authenticateSurfaceTextureLocked(gbp)) {
3884 const auto& otherLayer =
3885 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003886 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003887 } else {
3888 ALOGE("Attempt to defer transaction to to an"
3889 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003890 }
3891 }
chaviw8b3871a2017-11-01 17:41:01 -07003892 // We don't trigger a traversal here because if no other state is
3893 // changed, we don't want this to cause any more work
3894 }
3895 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003896 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003897 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003898 if (!hadParent) {
3899 mCurrentState.layersSortedByZ.remove(layer);
3900 }
chaviw8b3871a2017-11-01 17:41:01 -07003901 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003902 }
chaviw8b3871a2017-11-01 17:41:01 -07003903 }
3904 if (what & layer_state_t::eReparentChildren) {
3905 if (layer->reparentChildren(s.reparentHandle)) {
3906 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003907 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003908 }
chaviw8b3871a2017-11-01 17:41:01 -07003909 if (what & layer_state_t::eDetachChildren) {
3910 layer->detachChildren();
3911 }
3912 if (what & layer_state_t::eOverrideScalingModeChanged) {
3913 layer->setOverrideScalingMode(s.overrideScalingMode);
3914 // We don't trigger a traversal here because if no other state is
3915 // changed, we don't want this to cause any more work
3916 }
Marissa Wall61c58622018-07-18 10:12:20 -07003917 if (what & layer_state_t::eTransformChanged) {
3918 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3919 }
3920 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3921 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3922 flags |= eTraversalNeeded;
3923 }
3924 if (what & layer_state_t::eCropChanged) {
3925 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3926 }
Marissa Wall861616d2018-10-22 12:52:23 -07003927 if (what & layer_state_t::eFrameChanged) {
3928 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3929 }
Marissa Wall61c58622018-07-18 10:12:20 -07003930 if (what & layer_state_t::eAcquireFenceChanged) {
3931 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eDataspaceChanged) {
3934 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3935 }
3936 if (what & layer_state_t::eHdrMetadataChanged) {
3937 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3938 }
3939 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3940 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3941 }
3942 if (what & layer_state_t::eApiChanged) {
3943 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3944 }
3945 if (what & layer_state_t::eSidebandStreamChanged) {
3946 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3947 }
Robert Carr720e5062018-07-30 17:45:14 -07003948 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003949 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3950 layer->setInputInfo(s.inputInfo);
3951 flags |= eTraversalNeeded;
3952 } else {
3953 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3954 }
Robert Carr720e5062018-07-30 17:45:14 -07003955 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003956 if (what & layer_state_t::eMetadataChanged) {
3957 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3958 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003959 std::vector<sp<CallbackHandle>> callbackHandles;
3960 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3961 mTransactionCompletedThread.run();
3962 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3963 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3964 }
3965 }
Marissa Wall73411622019-01-25 10:45:41 -08003966
3967 if (what & layer_state_t::eBufferChanged) {
3968 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3969 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3970 s.buffer);
3971 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003972 if (what & layer_state_t::eCachedBufferChanged) {
3973 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003974 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3975 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003976 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3977 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003978 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3979 // Do not put anything that updates layer state or modifies flags after
3980 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003981 return flags;
3982}
3983
chaviw273171b2018-12-26 11:46:30 -08003984uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3985 uint32_t flags = 0;
3986 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3987 flags |= eTraversalNeeded;
3988 }
3989
chaviwa911b102019-02-14 10:18:33 -08003990 if (inputWindowCommands.syncInputWindows) {
3991 flags |= eTraversalNeeded;
3992 }
3993
Vishnu Nairec0ab382019-02-13 15:32:56 -08003994 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003995 return flags;
3996}
3997
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003998status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3999 uint32_t h, PixelFormat format, uint32_t flags,
4000 LayerMetadata metadata, sp<IBinder>* handle,
4001 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004002 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004003 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004004 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004005 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004006 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004007
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004008 status_t result = NO_ERROR;
4009
4010 sp<Layer> layer;
4011
Cody Northropbc755282017-03-31 12:00:08 -06004012 String8 uniqueName = getUniqueLayerName(name);
4013
Mathias Agopian3165cc22012-08-08 19:42:09 -07004014 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004015 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004016 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4017 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004018
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004020 case ISurfaceComposerClient::eFXSurfaceBufferState:
4021 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4022 break;
chaviw13fdc492017-06-27 12:40:18 -07004023 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004024 // check if buffer size is set for color layer.
4025 if (w > 0 || h > 0) {
4026 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4027 int(w), int(h));
4028 return BAD_VALUE;
4029 }
4030
chaviw13fdc492017-06-27 12:40:18 -07004031 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004032 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004033 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004034 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004035 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004036 // check if buffer size is set for container layer.
4037 if (w > 0 || h > 0) {
4038 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4039 int(w), int(h));
4040 return BAD_VALUE;
4041 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004042 result = createContainerLayer(client,
4043 uniqueName, w, h, flags,
4044 handle, &layer);
4045 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004046 default:
4047 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004048 break;
4049 }
4050
Dan Stoza7d89d062015-04-30 13:29:25 -07004051 if (result != NO_ERROR) {
4052 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004054
Chia-I Wuab0c3192017-08-01 11:29:00 -07004055 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4056 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004057 if (metadata.has(METADATA_WINDOW_TYPE)) {
4058 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4059 if (windowType == 441731) {
4060 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4061 layer->setPrimaryDisplayOnly();
4062 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004063 }
4064
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004065 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004066
Robert Carrb89ea9d2018-12-10 13:01:14 -08004067 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4068 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4069 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004070 if (result != NO_ERROR) {
4071 return result;
4072 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004073 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004074
4075 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004076 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004077}
4078
Cody Northropbc755282017-03-31 12:00:08 -06004079String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4080{
4081 bool matchFound = true;
4082 uint32_t dupeCounter = 0;
4083
4084 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4085 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4086
Dan Stoza436ccf32018-06-21 12:10:12 -07004087 // Grab the state lock since we're accessing mCurrentState
4088 Mutex::Autolock lock(mStateLock);
4089
Cody Northropbc755282017-03-31 12:00:08 -06004090 // Loop over layers until we're sure there is no matching name
4091 while (matchFound) {
4092 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004093 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004094 if (layer->getName() == uniqueName) {
4095 matchFound = true;
4096 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4097 }
4098 });
4099 }
4100
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004101 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4102 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004103
4104 return uniqueName;
4105}
4106
Marissa Wallfd668622018-05-10 10:21:13 -07004107status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4108 uint32_t w, uint32_t h, uint32_t flags,
4109 PixelFormat& format, sp<IBinder>* handle,
4110 sp<IGraphicBufferProducer>* gbp,
4111 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004113 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004114 case PIXEL_FORMAT_TRANSPARENT:
4115 case PIXEL_FORMAT_TRANSLUCENT:
4116 format = PIXEL_FORMAT_RGBA_8888;
4117 break;
4118 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004119 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004120 break;
4121 }
4122
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004123 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004124 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004125 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004126 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004127 *handle = layer->getHandle();
4128 *gbp = layer->getProducer();
4129 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004130 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131
Marissa Wallfd668622018-05-10 10:21:13 -07004132 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004133 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134}
4135
Marissa Wall61c58622018-07-18 10:12:20 -07004136status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4137 uint32_t w, uint32_t h, uint32_t flags,
4138 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004139 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004140 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004141 *handle = layer->getHandle();
4142 *outLayer = layer;
4143
4144 return NO_ERROR;
4145}
4146
chaviw13fdc492017-06-27 12:40:18 -07004147status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004148 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004149 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004150{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004151 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004152 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004153 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004154}
4155
Robert Carr6b3f6c52018-08-13 13:05:17 -07004156status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4157 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4158 sp<IBinder>* handle, sp<Layer>* outLayer)
4159{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004160 *outLayer =
4161 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004162 *handle = (*outLayer)->getHandle();
4163 return NO_ERROR;
4164}
4165
4166
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004167void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004168 mLayersPendingRemoval.add(layer);
4169 mLayersRemoved = true;
4170 setTransactionFlags(eTransactionNeeded);
4171}
4172
Robert Carr695d5282018-12-18 15:27:58 -08004173void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004174{
Robert Carr2e102c92018-10-23 12:11:15 -07004175 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004176 // If a layer has a parent, we allow it to out-live it's handle
4177 // with the idea that the parent holds a reference and will eventually
4178 // be cleaned up. However no one cleans up the top-level so we do so
4179 // here.
4180 if (layer->getParent() == nullptr) {
4181 mCurrentState.layersSortedByZ.remove(layer);
4182 }
4183 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004184 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004185}
4186
Mathias Agopianb60314a2012-04-10 22:09:54 -07004187// ---------------------------------------------------------------------------
4188
Andy McFadden13a082e2012-08-24 10:16:42 -07004189void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004190 const auto display = getDefaultDisplayDeviceLocked();
4191 if (!display) return;
4192
4193 const sp<IBinder> token = display->getDisplayToken().promote();
4194 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004195
Jesse Hall01e29052013-02-19 16:13:35 -08004196 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004197 Vector<ComposerState> state;
4198 Vector<DisplayState> displays;
4199 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004200 d.what = DisplayState::eDisplayProjectionChanged |
4201 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004202 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004203 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004204 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004205 d.frame.makeInvalid();
4206 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004207 d.width = 0;
4208 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004209 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004210 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004211
Dominik Laskowskie9774092018-12-11 10:04:24 -08004212 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004213
Dominik Laskowski83b88212018-12-11 13:34:06 -08004214 const nsecs_t vsyncPeriod = getVsyncPeriod();
4215 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004216
Brian Andersond0010582017-03-07 13:20:31 -08004217 // Use phase of 0 since phase is not known.
4218 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004220 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004221}
4222
4223void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004224 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004225 postMessageAsync(
4226 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004227}
4228
Dominik Laskowskie9774092018-12-11 10:04:24 -08004229void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004230 if (display->isVirtual()) {
4231 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004232 return;
4233 }
4234
Dominik Laskowski075d3172018-05-24 15:50:06 -07004235 const auto displayId = display->getId();
4236 LOG_ALWAYS_FATAL_IF(!displayId);
4237
Dominik Laskowski34157762018-10-31 13:07:19 -07004238 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004239
4240 int currentMode = display->getPowerMode();
4241 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004242 return;
4243 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004245 display->setPowerMode(mode);
4246
Lloyd Pique4dccc412018-01-22 17:21:36 -08004247 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004248 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004249 }
4250
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004251 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004252 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004253 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004254 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004255 mScheduler->onScreenAcquired(mAppConnectionHandle);
4256 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004257 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004258
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004259 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004260 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004261 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004262
4263 struct sched_param param = {0};
4264 param.sched_priority = 1;
4265 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4266 ALOGW("Couldn't set SCHED_FIFO on display on");
4267 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004268 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004269 // Turn off the display
4270 struct sched_param param = {0};
4271 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4272 ALOGW("Couldn't set SCHED_OTHER on display off");
4273 }
4274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004275 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004276 mScheduler->disableHardwareVsync(true);
4277 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004278 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004279
Dominik Laskowski075d3172018-05-24 15:50:06 -07004280 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004281 mVisibleRegionsDirty = true;
4282 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004283 } else if (mode == HWC_POWER_MODE_DOZE ||
4284 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004285 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004286 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004287 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004288 mScheduler->onScreenAcquired(mAppConnectionHandle);
4289 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004290 }
4291 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4292 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004293 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004294 mScheduler->disableHardwareVsync(true);
4295 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004296 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004297 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004298 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004299 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004300 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004301 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004302
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004303 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004304 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004305 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004306 // Update refresh rate stats.
4307 mRefreshRateStats->setPowerMode(mode);
4308 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004309 }
4310
Dominik Laskowski34157762018-10-31 13:07:19 -07004311 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004312}
4313
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004314void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004315 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 const auto display = getDisplayDevice(displayToken);
4317 if (!display) {
4318 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4319 displayToken.get());
4320 } else if (display->isVirtual()) {
4321 ALOGW("Attempt to set power mode %d for virtual display", mode);
4322 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004323 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004324 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004325 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004326}
4327
4328// ---------------------------------------------------------------------------
4329
Dominik Laskowskic2867142019-01-21 11:33:38 -08004330status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4331 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004333
Mathias Agopianbd115332013-04-18 16:41:04 -07004334 IPCThreadState* ipc = IPCThreadState::self();
4335 const int pid = ipc->getCallingPid();
4336 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004337
Mathias Agopianbd115332013-04-18 16:41:04 -07004338 if ((uid != AID_SHELL) &&
4339 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004340 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4341 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004342 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004343 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004344 // (this would indicate SF is stuck, but we want to be able to
4345 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004346 status_t err = mStateLock.timedLock(s2ns(1));
4347 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004348 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349 StringAppendF(&result,
4350 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4351 "(no locks held)\n",
4352 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004353 }
4354
Dominik Laskowskic2867142019-01-21 11:33:38 -08004355 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004356
Dominik Laskowskic2867142019-01-21 11:33:38 -08004357 static const std::unordered_map<std::string, Dumper> dumpers = {
4358 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4359 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4360 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004361 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004362 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004363 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004364 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4365 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004366 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4367 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4368 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4369 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4370 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4371 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004372 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004373 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4374 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004375
Dominik Laskowskic2867142019-01-21 11:33:38 -08004376 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004377
Dominik Laskowskic2867142019-01-21 11:33:38 -08004378 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4379 (it->second)(args, asProto, result);
4380 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004381 if (asProto) {
4382 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4383 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4384 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004385 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004386 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004387 }
4388
Mathias Agopian9795c422009-08-26 16:36:26 -07004389 if (locked) {
4390 mStateLock.unlock();
4391 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004393 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004394 return NO_ERROR;
4395}
4396
Dominik Laskowskic2867142019-01-21 11:33:38 -08004397void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004398 mCurrentState.traverseInZOrder(
4399 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004400}
4401
Dominik Laskowskic2867142019-01-21 11:33:38 -08004402void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004403 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004404
Dominik Laskowskic2867142019-01-21 11:33:38 -08004405 if (args.size() > 1) {
4406 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004407 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004408 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004409 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004410 }
Robert Carr2047fae2016-11-28 14:09:09 -08004411 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004412 } else {
4413 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414 }
4415}
4416
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004418 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004419 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004420 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004421 }
Robert Carr2047fae2016-11-28 14:09:09 -08004422 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004423
Svetoslavd85084b2014-03-20 10:28:31 -07004424 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004425}
4426
Dominik Laskowskic2867142019-01-21 11:33:38 -08004427void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4428 mTimeStats->parseArgs(asProto, args, result);
4429}
4430
Jamie Gennis6547ff42013-07-16 20:12:42 -07004431// This should only be called from the main thread. Otherwise it would need
4432// the lock and should use mCurrentState rather than mDrawingState.
4433void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004434 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004435 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004436 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004437
4438 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4439}
4440
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004442 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004443
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004444 if (isLayerTripleBufferingDisabled())
4445 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4448 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4449 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4450 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4451 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4452 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004453 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004454}
4455
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004456void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004457 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004458 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004459 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004460 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004461
Ana Krulecc2870422019-01-29 19:00:58 -08004462 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n\n", mUse90Hz ? "on" : "off");
4463 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004464}
4465
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4467 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004468 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4469 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004470 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004471 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004473 }
David Sodman4a36e932017-11-07 14:29:47 -08004474 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004475 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004476 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004477 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4478 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004479}
4480
Dan Stozae77c7662016-05-13 11:37:28 -07004481void SurfaceFlinger::recordBufferingStats(const char* layerName,
4482 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004483 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4484 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004485 for (const auto& segment : history) {
4486 if (!segment.usedThirdBuffer) {
4487 stats.twoBufferTime += segment.totalTime;
4488 }
4489 if (segment.occupancyAverage < 1.0f) {
4490 stats.doubleBufferedTime += segment.totalTime;
4491 } else if (segment.occupancyAverage < 2.0f) {
4492 stats.tripleBufferedTime += segment.totalTime;
4493 }
4494 ++stats.numSegments;
4495 stats.totalTime += segment.totalTime;
4496 }
4497}
4498
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4500 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004501
4502 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4503 const size_t count = currentLayers.size();
4504 for (size_t i=0 ; i<count ; i++) {
4505 currentLayers[i]->dumpFrameEvents(result);
4506 }
4507}
4508
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004510 result.append("Buffering stats:\n");
4511 result.append(" [Layer name] <Active time> <Two buffer> "
4512 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004513 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004514 typedef std::tuple<std::string, float, float, float> BufferTuple;
4515 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004516 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004517 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004518 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004519 if (stats.numSegments == 0) {
4520 continue;
4521 }
4522 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4523 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4524 stats.totalTime;
4525 float doubleBufferRatio = static_cast<float>(
4526 stats.doubleBufferedTime) / stats.totalTime;
4527 float tripleBufferRatio = static_cast<float>(
4528 stats.tripleBufferedTime) / stats.totalTime;
4529 sorted.insert({activeTime, {name, twoBufferRatio,
4530 doubleBufferRatio, tripleBufferRatio}});
4531 }
4532 for (const auto& sortedPair : sorted) {
4533 float activeTime = sortedPair.first;
4534 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004535 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4536 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004537 }
4538 result.append("\n");
4539}
4540
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004542 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004543 const auto displayId = display->getId();
4544 if (!displayId) {
4545 continue;
4546 }
4547 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004548 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004549 continue;
4550 }
4551
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552 StringAppendF(&result,
4553 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4554 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004555 uint8_t port;
4556 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004557 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004558 result.append("no identification data\n");
4559 continue;
4560 }
4561
4562 if (!isEdid(data)) {
4563 result.append("unknown identification data: ");
4564 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004565 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004566 }
4567 result.append("\n");
4568 continue;
4569 }
4570
4571 const auto edid = parseEdid(data);
4572 if (!edid) {
4573 result.append("invalid EDID: ");
4574 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004575 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004576 }
4577 result.append("\n");
4578 continue;
4579 }
4580
Yiwei Zhang5434a782018-12-05 18:06:32 -08004581 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004582 result.append(edid->displayName.data(), edid->displayName.length());
4583 result.append("\"\n");
4584 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004585}
4586
Yiwei Zhang5434a782018-12-05 18:06:32 -08004587void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4588 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4589 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4590 StringAppendF(&result, "DisplayColorSetting: %s\n",
4591 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004592
4593 // TODO: print out if wide-color mode is active or not
4594
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004595 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004596 const auto displayId = display->getId();
4597 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004598 continue;
4599 }
4600
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004602 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004603 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004605 }
4606
Lloyd Pique32cbe282018-10-19 13:09:22 -07004607 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, " Current color mode: %s (%d)\n",
4609 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004610 }
4611 result.append("\n");
4612}
4613
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004614LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004615 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004616 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4617 const State& state = useDrawing ? mDrawingState : mCurrentState;
4618 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004619 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004620 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004621 });
4622
4623 return layersProto;
4624}
4625
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004626LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4627 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004628 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004629
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004630 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004631 resolution->set_w(displayDevice->getWidth());
4632 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004633
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004634 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004635 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004636
Lloyd Pique32cbe282018-10-19 13:09:22 -07004637 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4638 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4639 layersProto.set_global_transform(displayState.orientation);
4640
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004641 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004642 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004643 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004644 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004645 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004646 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004647 }
4648 });
4649
4650 return layersProto;
4651}
4652
Dominik Laskowskic2867142019-01-21 11:33:38 -08004653void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4654 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 Colorizer colorizer(colorize);
4656
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004657 // figure out if we're stuck somewhere
4658 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004659 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004660 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4661
4662 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004663 * Dump library configuration.
4664 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004665
4666 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004667 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004668 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004669 appendSfConfigString(result);
4670 appendUiConfigString(result);
4671 appendGuiConfigString(result);
4672 result.append("\n");
4673
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004674 result.append("\nDisplay identification data:\n");
4675 dumpDisplayIdentificationData(result);
4676
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004677 result.append("\nWide-Color information:\n");
4678 dumpWideColorInfo(result);
4679
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004681 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004683 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004684 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004685
Andy McFadden41d67d72014-04-25 16:58:34 -07004686 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004687 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004688 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004689 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004690 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004691
Dan Stozab90cf072015-03-05 11:05:59 -08004692 dumpStaticScreenStats(result);
4693 result.append("\n");
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004696
Dan Stozae77c7662016-05-13 11:37:28 -07004697 dumpBufferingStats(result);
4698
Andy McFadden4803b742012-09-24 19:07:20 -07004699 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004700 * Dump the visible layer list
4701 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004702 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004703 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4704 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4705 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004706 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004707
Chia-I Wu2f884132018-09-13 15:17:58 -07004708 {
4709 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4710 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004712 result.append("\n");
4713 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
4715 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004716 * Dump Display state
4717 */
4718
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004721 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004722 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004723 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004724 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004725 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004726
4727 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004728 * Dump SurfaceFlinger global state
4729 */
4730
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004731 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004732 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004735 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004736
Dominik Laskowski075d3172018-05-24 15:50:06 -07004737 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004738 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4739 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4741 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004742 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004743 StringAppendF(&result,
4744 " transaction-flags : %08x\n"
4745 " gpu_to_cpu_unsupported : %d\n",
4746 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004747
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004748 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004749 displayId && getHwComposer().isConnected(*displayId)) {
4750 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result,
4752 " refresh-rate : %f fps\n"
4753 " x-dpi : %f\n"
4754 " y-dpi : %f\n",
4755 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4756 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004757 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758
Yiwei Zhang5434a782018-12-05 18:06:32 -08004759 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004760
Dan Stozae22aec72016-08-01 13:20:59 -07004761 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004762 * Tracing state
4763 */
4764 mTracing.dump(result);
4765 result.append("\n");
4766
4767 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004768 * HWC layer minidump
4769 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004770 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004771 const auto displayId = display->getId();
4772 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004773 continue;
4774 }
4775
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004777 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004778 const sp<DisplayDevice> displayDevice = display;
4779 mCurrentState.traverseInZOrder(
4780 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004781 result.append("\n");
4782 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004783
4784 /*
4785 * Dump HWComposer state
4786 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004788 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004789 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004790 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004791 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004792 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004793
4794 /*
4795 * Dump gralloc state
4796 */
4797 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4798 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004799
4800 /*
4801 * Dump VrFlinger state if in use.
4802 */
4803 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4804 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004805 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004806 result.append("\n");
4807 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004808
4809 /**
4810 * Scheduler dump state.
4811 */
Ana Krulecc2870422019-01-29 19:00:58 -08004812 result.append("\nScheduler state:\n");
4813 result.append(mScheduler->doDump() + "\n");
4814 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004815}
4816
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004818 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004819 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004820 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004821 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004822 }
4823 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004824
Dominik Laskowski34157762018-10-31 13:07:19 -07004825 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004826 static const Vector<sp<Layer>> empty;
4827 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004828}
4829
Chia-I Wu28f320b2018-05-03 11:02:56 -07004830void SurfaceFlinger::updateColorMatrixLocked() {
4831 mat4 colorMatrix;
4832 if (mGlobalSaturationFactor != 1.0f) {
4833 // Rec.709 luma coefficients
4834 float3 luminance{0.213f, 0.715f, 0.072f};
4835 luminance *= 1.0f - mGlobalSaturationFactor;
4836 mat4 saturationMatrix = mat4(
4837 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4838 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4839 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4840 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4841 );
4842 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4843 } else {
4844 colorMatrix = mClientColorMatrix * mDaltonizer();
4845 }
4846
4847 if (mCurrentState.colorMatrix != colorMatrix) {
4848 mCurrentState.colorMatrix = colorMatrix;
4849 mCurrentState.colorMatrixChanged = true;
4850 setTransactionFlags(eTransactionNeeded);
4851 }
4852}
4853
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004854status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855#pragma clang diagnostic push
4856#pragma clang diagnostic error "-Wswitch-enum"
4857 switch (static_cast<ISurfaceComposerTag>(code)) {
4858 // These methods should at minimum make sure that the client requested
4859 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004860 case BOOT_FINISHED:
4861 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 case CREATE_DISPLAY:
4863 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004864 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 case GET_ACTIVE_COLOR_MODE:
4866 case GET_ANIMATION_FRAME_STATS:
4867 case GET_HDR_CAPABILITIES:
4868 case SET_ACTIVE_CONFIG:
4869 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004870 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004871 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004872 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004873 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4874 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004875 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4876 IPCThreadState* ipc = IPCThreadState::self();
4877 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4878 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004879 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880 }
Robert Carr1db73f62016-12-21 12:58:51 -08004881 return OK;
4882 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004884 IPCThreadState* ipc = IPCThreadState::self();
4885 const int pid = ipc->getCallingPid();
4886 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4888 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004889 return PERMISSION_DENIED;
4890 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004891 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004892 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893 // Used by apps to hook Choreographer to SurfaceFlinger.
4894 case CREATE_DISPLAY_EVENT_CONNECTION:
4895 // The following calls are currently used by clients that do not
4896 // request necessary permissions. However, they do not expose any secret
4897 // information, so it is OK to pass them.
4898 case AUTHENTICATE_SURFACE:
4899 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004900 case GET_PHYSICAL_DISPLAY_IDS:
4901 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004902 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004903 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 case GET_DISPLAY_CONFIGS:
4905 case GET_DISPLAY_STATS:
4906 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4907 // Calling setTransactionState is safe, because you need to have been
4908 // granted a reference to Client* and Handle* to do anything with it.
4909 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004910 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004911 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004912 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004913 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004914 case IS_WIDE_COLOR_DISPLAY:
4915 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 return OK;
4917 }
4918 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004919 case CAPTURE_SCREEN:
4920 case ADD_REGION_SAMPLING_LISTENER:
4921 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004922 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004923 IPCThreadState* ipc = IPCThreadState::self();
4924 const int pid = ipc->getCallingPid();
4925 const int uid = ipc->getCallingUid();
4926 if ((uid != AID_GRAPHICS) &&
4927 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4928 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4929 return PERMISSION_DENIED;
4930 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 return OK;
4932 }
4933 // The following codes are deprecated and should never be allowed to access SF.
4934 case CONNECT_DISPLAY_UNUSED:
4935 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4936 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4937 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004938 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940
4941 // These codes are used for the IBinder protocol to either interrogate the recipient
4942 // side of the transaction for its canonical interface descriptor or to dump its state.
4943 // We let them pass by default.
4944 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4945 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4946 code == IBinder::SYSPROPS_TRANSACTION) {
4947 return OK;
4948 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004949 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004950 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004951 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4953 return OK;
4954 }
4955 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4956 return PERMISSION_DENIED;
4957#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004958}
4959
Ana Krulec13be8ad2018-08-21 02:43:56 +00004960status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4961 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004962 status_t credentialCheck = CheckTransactCodeCredentials(code);
4963 if (credentialCheck != OK) {
4964 return credentialCheck;
4965 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004967 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4968 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004969 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004970 IPCThreadState* ipc = IPCThreadState::self();
4971 const int uid = ipc->getCallingUid();
4972 if (CC_UNLIKELY(uid != AID_SYSTEM
4973 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004974 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004975 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004976 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 return PERMISSION_DENIED;
4978 }
4979 int n;
4980 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004981 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004982 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 return NO_ERROR;
4984 case 1002: // SHOW_UPDATES
4985 n = data.readInt32();
4986 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004987 invalidateHwcGeometry();
4988 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004990 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004991 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004992 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004994 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004995 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004996 setTransactionFlags(
4997 eTransactionNeeded|
4998 eDisplayTransactionNeeded|
4999 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005000 return NO_ERROR;
5001 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005002 case 1006:{ // send empty update
5003 signalRefresh();
5004 return NO_ERROR;
5005 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005006 case 1008: // toggle use of hw composer
5007 n = data.readInt32();
5008 mDebugDisableHWC = n ? 1 : 0;
5009 invalidateHwcGeometry();
5010 repaintEverything();
5011 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005012 case 1009: // toggle use of transform hint
5013 n = data.readInt32();
5014 mDebugDisableTransformHint = n ? 1 : 0;
5015 invalidateHwcGeometry();
5016 repaintEverything();
5017 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005019 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005020 reply->writeInt32(0);
5021 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005022 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005023 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 return NO_ERROR;
5025 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005026 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005027 if (!display) {
5028 return NAME_NOT_FOUND;
5029 }
5030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005031 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005032 return NO_ERROR;
5033 }
5034 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005035 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005036 // daltonize
5037 n = data.readInt32();
5038 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005039 case 1:
5040 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5041 break;
5042 case 2:
5043 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5044 break;
5045 case 3:
5046 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5047 break;
5048 default:
5049 mDaltonizer.setType(ColorBlindnessType::None);
5050 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005051 }
5052 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005053 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005054 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005055 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005056 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005057
5058 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005060 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005062 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005063 // apply a color matrix
5064 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005065 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005066 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005067 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005068 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005069 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005070 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005072 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005073 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005074 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005075
5076 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5077 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005078 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005079 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5080 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5081 }
5082
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005084 return NO_ERROR;
5085 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005086 // This is an experimental interface
5087 // Needs to be shifted to proper binder interface when we productize
5088 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005089 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005090 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005091 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005092 return NO_ERROR;
5093 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005094 case 1017: {
5095 n = data.readInt32();
5096 mForceFullDamage = static_cast<bool>(n);
5097 return NO_ERROR;
5098 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005099 case 1018: { // Modify Choreographer's phase offset
5100 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005101 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005102 return NO_ERROR;
5103 }
5104 case 1019: { // Modify SurfaceFlinger's phase offset
5105 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005106 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005107 return NO_ERROR;
5108 }
Irvel468051e2016-06-13 16:44:44 -07005109 case 1020: { // Layer updates interceptor
5110 n = data.readInt32();
5111 if (n) {
5112 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005113 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005114 }
5115 else{
5116 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005117 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005118 }
5119 return NO_ERROR;
5120 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005121 case 1021: { // Disable HWC virtual displays
5122 n = data.readInt32();
5123 mUseHwcVirtualDisplays = !n;
5124 return NO_ERROR;
5125 }
Romain Guy0147a172017-06-01 13:53:56 -07005126 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005128 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005129
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005131 return NO_ERROR;
5132 }
Romain Guy54f154a2017-10-24 21:40:32 +01005133 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005134 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005135 invalidateHwcGeometry();
5136 repaintEverything();
5137 return NO_ERROR;
5138 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005139 // Deprecate, use 1030 to check whether the device is color managed.
5140 case 1024: {
5141 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005142 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005143 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005144 n = data.readInt32();
5145 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005146 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005147 mTracing.enable();
5148 doTracing("tracing.enable");
5149 reply->writeInt32(NO_ERROR);
5150 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005151 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005152 status_t err = mTracing.disable();
5153 reply->writeInt32(err);
5154 }
5155 return NO_ERROR;
5156 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005157 case 1026: { // Get layer tracing status
5158 reply->writeBool(mTracing.isEnabled());
5159 return NO_ERROR;
5160 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 // Is a DisplayColorSetting supported?
5162 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163 const auto display = getDefaultDisplayDevice();
5164 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005165 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005166 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005167
5168 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5169 switch (setting) {
5170 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005171 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 break;
5173 case DisplayColorSetting::UNMANAGED:
5174 reply->writeBool(true);
5175 break;
5176 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005177 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005178 break;
5179 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005180 reply->writeBool(
5181 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005182 break;
5183 }
5184 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005185 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005186 // Is VrFlinger active?
5187 case 1028: {
5188 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005189 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005190 return NO_ERROR;
5191 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005192 // Is device color managed?
5193 case 1030: {
5194 reply->writeBool(useColorManagement);
5195 return NO_ERROR;
5196 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005197 // Override default composition data space
5198 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5199 // && adb shell stop zygote && adb shell start zygote
5200 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5201 // adb shell stop zygote && adb shell start zygote
5202 case 1031: {
5203 Mutex::Autolock _l(mStateLock);
5204 n = data.readInt32();
5205 if (n) {
5206 n = data.readInt32();
5207 if (n) {
5208 Dataspace dataspace = static_cast<Dataspace>(n);
5209 if (!validateCompositionDataspace(dataspace)) {
5210 return BAD_VALUE;
5211 }
5212 mDefaultCompositionDataspace = dataspace;
5213 }
5214 n = data.readInt32();
5215 if (n) {
5216 Dataspace dataspace = static_cast<Dataspace>(n);
5217 if (!validateCompositionDataspace(dataspace)) {
5218 return BAD_VALUE;
5219 }
5220 mWideColorGamutCompositionDataspace = dataspace;
5221 }
5222 } else {
5223 // restore composition data space.
5224 mDefaultCompositionDataspace = defaultCompositionDataspace;
5225 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5226 }
5227 return NO_ERROR;
5228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005229 }
5230 }
5231 return err;
5232}
5233
Steven Thomas6d8110b2017-08-31 18:24:21 -07005234void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005235 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005236 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005237}
5238
Ana Krulec7d1d6832018-12-27 11:10:09 -08005239void SurfaceFlinger::repaintEverythingForHWC() {
5240 mRepaintEverything = true;
5241 mEventQueue->invalidateForHWC();
5242}
5243
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5245class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005246public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005247 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5248 ~WindowDisconnector() {
5249 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005250 }
5251
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005252private:
5253 ANativeWindow* mWindow;
5254 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005255};
5256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005257status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005258 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5259 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005260 uint32_t reqWidth, uint32_t reqHeight,
5261 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005262 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005263 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005265 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005266
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005267 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5268
Chia-I Wu20261cb2018-08-23 12:55:44 -07005269 sp<DisplayDevice> display;
5270 {
5271 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005272
Chia-I Wu20261cb2018-08-23 12:55:44 -07005273 display = getDisplayDeviceLocked(displayToken);
5274 if (!display) return BAD_VALUE;
5275
Chia-I Wucb023152018-08-28 12:57:23 -07005276 // set the requested width/height to the logical display viewport size
5277 // by default
5278 if (reqWidth == 0 || reqHeight == 0) {
5279 reqWidth = uint32_t(display->getViewport().width());
5280 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005281 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005282 }
5283
Peiyong Lin0e003c92018-09-17 11:09:51 -07005284 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5285 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005286
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005287 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5288 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005289 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5290 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005291}
5292
5293status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005294 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5295 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005296 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005297 ATRACE_CALL();
5298
5299 class LayerRenderArea : public RenderArea {
5300 public:
Robert Carr578038f2018-03-09 12:25:24 -08005301 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005302 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5303 bool childrenOnly)
5304 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005305 mLayer(layer),
5306 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005307 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005308 mFlinger(flinger),
5309 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005310 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005311 Rect getBounds() const override {
5312 const Layer::State& layerState(mLayer->getDrawingState());
5313 return mLayer->getBufferSize(layerState);
5314 }
Marissa Wall61c58622018-07-18 10:12:20 -07005315 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005316 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005317 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005318 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005319 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005320 }
chaviwa76b2712017-09-20 12:02:26 -07005321 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005322 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005323 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005324 Rect getSourceCrop() const override {
5325 if (mCrop.isEmpty()) {
5326 return getBounds();
5327 } else {
5328 return mCrop;
5329 }
5330 }
Robert Carr578038f2018-03-09 12:25:24 -08005331 class ReparentForDrawing {
5332 public:
5333 const sp<Layer>& oldParent;
5334 const sp<Layer>& newParent;
5335
Vishnu Nair4351ad52019-02-11 14:13:02 -08005336 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5337 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005338 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005339 // Compute and cache the bounds for the new parent layer.
5340 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005341 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005342 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005343 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005344 };
5345
5346 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005347 const Rect sourceCrop = getSourceCrop();
5348 // no need to check rotation because there is none
5349 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5350 sourceCrop.height() != getReqHeight();
5351
Robert Carr578038f2018-03-09 12:25:24 -08005352 if (!mChildrenOnly) {
5353 mTransform = mLayer->getTransform().inverse();
5354 drawLayers();
5355 } else {
5356 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005357 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005358 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5359 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005360
Vishnu Nair4351ad52019-02-11 14:13:02 -08005361 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005362 drawLayers();
5363 }
5364 }
chaviwa76b2712017-09-20 12:02:26 -07005365
chaviwa76b2712017-09-20 12:02:26 -07005366 private:
chaviw7206d492017-11-10 16:16:12 -08005367 const sp<Layer> mLayer;
5368 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005369
5370 // In the "childrenOnly" case we reparent the children to a screenshot
5371 // layer which has no properties set and which does not draw.
5372 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005373 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005374 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005375
5376 SurfaceFlinger* mFlinger;
5377 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005378 };
5379
5380 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5381 auto parent = layerHandle->owner.promote();
5382
Robert Carr2e102c92018-10-23 12:11:15 -07005383 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005384 ALOGE("captureLayers called with a removed parent");
5385 return NAME_NOT_FOUND;
5386 }
5387
Robert Carr578038f2018-03-09 12:25:24 -08005388 const int uid = IPCThreadState::self()->getCallingUid();
5389 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005390 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005391 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5392 return PERMISSION_DENIED;
5393 }
5394
chaviw7206d492017-11-10 16:16:12 -08005395 Rect crop(sourceCrop);
5396 if (sourceCrop.width() <= 0) {
5397 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005398 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005399 }
5400
5401 if (sourceCrop.height() <= 0) {
5402 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005403 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005404 }
5405
5406 int32_t reqWidth = crop.width() * frameScale;
5407 int32_t reqHeight = crop.height() * frameScale;
5408
Chia-I Wu20261cb2018-08-23 12:55:44 -07005409 // really small crop or frameScale
5410 if (reqWidth <= 0) {
5411 reqWidth = 1;
5412 }
5413 if (reqHeight <= 0) {
5414 reqHeight = 1;
5415 }
5416
Peiyong Lin0e003c92018-09-17 11:09:51 -07005417 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005418
Robert Carr578038f2018-03-09 12:25:24 -08005419 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005420 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5421 if (!layer->isVisible()) {
5422 return;
Robert Carr578038f2018-03-09 12:25:24 -08005423 } else if (childrenOnly && layer == parent.get()) {
5424 return;
chaviwa76b2712017-09-20 12:02:26 -07005425 }
5426 visitor(layer);
5427 });
5428 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005429 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005430}
5431
5432status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5433 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005434 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005436 bool useIdentityTransform) {
5437 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005438
Peiyong Lin0e003c92018-09-17 11:09:51 -07005439 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005440 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5441 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005442 *outBuffer =
5443 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5444 static_cast<android_pixel_format>(reqPixelFormat), 1,
5445 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005446
5447 // This mutex protects syncFd and captureResult for communication of the return values from the
5448 // main thread back to this Binder thread
5449 std::mutex captureMutex;
5450 std::condition_variable captureCondition;
5451 std::unique_lock<std::mutex> captureLock(captureMutex);
5452 int syncFd = -1;
5453 std::optional<status_t> captureResult;
5454
Robert Carr03480e22018-01-04 16:02:06 -08005455 const int uid = IPCThreadState::self()->getCallingUid();
5456 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5457
Dominik Laskowski8c001672018-05-30 16:52:06 -07005458 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005459 // If there is a refresh pending, bug out early and tell the binder thread to try again
5460 // after the refresh.
5461 if (mRefreshPending) {
5462 ATRACE_NAME("Skipping screenshot for now");
5463 std::unique_lock<std::mutex> captureLock(captureMutex);
5464 captureResult = std::make_optional<status_t>(EAGAIN);
5465 captureCondition.notify_one();
5466 return;
5467 }
5468
5469 status_t result = NO_ERROR;
5470 int fd = -1;
5471 {
5472 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005473 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005474 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5475 useIdentityTransform, forSystem, &fd);
5476 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005477 }
5478
5479 {
5480 std::unique_lock<std::mutex> captureLock(captureMutex);
5481 syncFd = fd;
5482 captureResult = std::make_optional<status_t>(result);
5483 captureCondition.notify_one();
5484 }
5485 });
5486
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005487 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005488 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005489 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005490 while (*captureResult == EAGAIN) {
5491 captureResult.reset();
5492 result = postMessageAsync(message);
5493 if (result != NO_ERROR) {
5494 return result;
5495 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005496 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005497 }
5498 result = *captureResult;
5499 }
5500
5501 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005502 sync_wait(syncFd, -1);
5503 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005504 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005505
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005506 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005507}
5508
chaviwa76b2712017-09-20 12:02:26 -07005509void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005510 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005511 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5512 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005513 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005514
chaviwa76b2712017-09-20 12:02:26 -07005515 const auto reqWidth = renderArea.getReqWidth();
5516 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005517 const auto sourceCrop = renderArea.getSourceCrop();
5518 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005519
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005520 renderengine::DisplaySettings clientCompositionDisplay;
5521 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005522
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005523 // assume that bounds are never offset, and that they are the same as the
5524 // buffer bounds.
5525 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5526 ui::Transform transform = renderArea.getTransform();
5527 mat4 m;
5528 m[0][0] = transform[0][0];
5529 m[0][1] = transform[0][1];
5530 m[0][3] = transform[0][2];
5531 m[1][0] = transform[1][0];
5532 m[1][1] = transform[1][1];
5533 m[1][3] = transform[1][2];
5534 m[3][0] = transform[2][0];
5535 m[3][1] = transform[2][1];
5536 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005537
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005538 clientCompositionDisplay.globalTransform = m;
5539 mat4 rotMatrix;
5540 // Displacement for repositioning the clipping rectangle after rotating it
5541 // with the rotation hint.
5542 int displacementX = 0;
5543 int displacementY = 0;
5544 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5545 switch (rotation) {
5546 case ui::Transform::ROT_90:
5547 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5548 displacementX = reqWidth;
5549 break;
5550 case ui::Transform::ROT_180:
5551 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5552 displacementX = reqWidth;
5553 displacementY = reqHeight;
5554 break;
5555 case ui::Transform::ROT_270:
5556 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5557 displacementY = reqHeight;
5558 break;
5559 default:
5560 break;
5561 }
5562 // We need to transform the clipping window into the right spot.
5563 // First, rotate the clipping rectangle by the rotation hint to get the
5564 // right orientation
5565 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5566 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5567 const vec4 rotClipTL = rotMatrix * clipTL;
5568 const vec4 rotClipBR = rotMatrix * clipBR;
5569 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5570 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5571 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5572 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5573
5574 // Now reposition the clipping rectangle with the displacement vector
5575 // computed above.
5576 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5577
5578 clientCompositionDisplay.clip =
5579 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5580 newClipRight + displacementX, newClipBottom + displacementY);
5581
5582 // We need to perform the same transformation in layer space, so propagate
5583 // it to the global transform.
5584 mat4 clipTransform = displacementMat * rotMatrix;
5585 clientCompositionDisplay.globalTransform *= clipTransform;
5586 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5587 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005588
chaviw50da5042018-04-09 13:49:37 -07005589 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005590
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005591 renderengine::LayerSettings fillLayer;
5592 fillLayer.source.buffer.buffer = nullptr;
5593 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5594 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5595 fillLayer.alpha = half(alpha);
5596 clientCompositionLayers.push_back(fillLayer);
5597
5598 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005599 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005600 renderengine::LayerSettings layerSettings;
5601 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5602 layerSettings);
5603 if (prepared) {
5604 clientCompositionLayers.push_back(layerSettings);
5605 }
chaviwa76b2712017-09-20 12:02:26 -07005606 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005607
5608 clientCompositionDisplay.clearRegion = clearRegion;
5609 base::unique_fd drawFence;
5610 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5611 &drawFence);
5612
5613 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005614}
5615
chaviwa76b2712017-09-20 12:02:26 -07005616status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5617 TraverseLayersFunction traverseLayers,
5618 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005619 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005620 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005621 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005622 ATRACE_CALL();
5623
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005624 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005625
5626 traverseLayers([&](Layer* layer) {
5627 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5628 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005629
Robert Carr03480e22018-01-04 16:02:06 -08005630 // We allow the system server to take screenshots of secure layers for
5631 // use in situations like the Screen-rotation animation and place
5632 // the impetus on WindowManager to not persist them.
5633 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005634 ALOGW("FB is protected: PERMISSION_DENIED");
5635 return PERMISSION_DENIED;
5636 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005639}
5640
chaviw5f21a5e2019-02-14 10:00:34 -08005641void SurfaceFlinger::setInputWindowsFinished() {}
5642
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005643// ---------------------------------------------------------------------------
5644
Dan Stoza412903f2017-04-27 13:42:17 -07005645void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5646 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005647}
5648
Dan Stoza412903f2017-04-27 13:42:17 -07005649void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5650 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005651}
5652
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005653void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005654 const LayerVector::Visitor& visitor) {
5655 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005656 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005657 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005658 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005659 continue;
5660 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005661 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005662 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005663 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005664 return;
5665 }
chaviwa76b2712017-09-20 12:02:26 -07005666 if (!layer->isVisible()) {
5667 return;
5668 }
5669 visitor(layer);
5670 });
5671 }
5672}
5673
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005674}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005675
Lloyd Pique074e8122018-07-26 12:57:23 -07005676
Mathias Agopian3f844832013-08-07 21:24:32 -07005677#if defined(__gl_h_)
5678#error "don't include gl/gl.h in this file"
5679#endif
5680
5681#if defined(__gl2_h_)
5682#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005683#endif