blob: 3ff7e96dfc76e477afbe3745fac45a6dd6c1a388 [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
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 postMessageAsync(new LambdaMessage([this] {
580 readPersistentProperties();
581 mBootStage = BootStage::FINISHED;
582 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800583}
584
Dan Stoza436ccf32018-06-21 12:10:12 -0700585uint32_t SurfaceFlinger::getNewTexture() {
586 {
587 std::lock_guard lock(mTexturePoolMutex);
588 if (!mTexturePool.empty()) {
589 uint32_t name = mTexturePool.back();
590 mTexturePool.pop_back();
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
592 return name;
593 }
594
595 // The pool was too small, so increase it for the future
596 ++mTexturePoolSize;
597 }
598
599 // The pool was empty, so we need to get a new texture name directly using a
600 // blocking call to the main thread
601 uint32_t name = 0;
602 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
603 return name;
604}
605
Mathias Agopian3f844832013-08-07 21:24:32 -0700606void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700607 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700608}
609
Wei Wangf9b05ee2017-07-19 20:59:39 -0700610// Do not call property_set on main thread which will be blocked by init
611// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700613 ALOGI( "SurfaceFlinger's main thread ready to run. "
614 "Initializing graphics H/W...");
615
Ana Krulec757f63a2019-01-25 10:46:18 -0800616 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800620 mScheduler =
621 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
622 auto resyncCallback =
623 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800624
Ana Krulecc2870422019-01-29 19:00:58 -0800625 mAppConnectionHandle =
626 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
627 resyncCallback,
628 impl::EventThread::InterceptVSyncsCallback());
629 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
630 resyncCallback, [this](nsecs_t timestamp) {
631 mInterceptor->saveVSyncEvent(timestamp);
632 });
633
634 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
635 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
636 mSfConnectionHandle.get());
637
638 if (mUse90Hz) {
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 mPhaseOffsets->setRefreshRateType(
640 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Ana Krulec98b5b242018-08-10 15:03:23 -0700641 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800642
Steven Thomasb02664d2017-07-26 18:48:28 -0700643 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700644 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700645 renderEngineFeature |= (useColorManagement ?
646 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700647 renderEngineFeature |= (useContextPriority ?
648 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700649
650 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700651 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700652 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700653 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700654
655 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
656 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700657 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
658 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800659 // Process any initial hotplug and resulting display changes.
660 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 const auto display = getDefaultDisplayDeviceLocked();
662 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700663 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800665
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700667 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700668 // This callback is called from the vr flinger dispatch thread. We
669 // need to call signalTransaction(), which requires holding
670 // mStateLock when we're not on the main thread. Acquiring
671 // mStateLock from the vr flinger dispatch thread might trigger a
672 // deadlock in surface flinger (see b/66916578), so post a message
673 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700675 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
676 mVrFlingerRequestsDisplay = requestDisplay;
677 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700678 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
681 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 .value_or(0),
684 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (!mVrFlinger) {
686 ALOGE("Failed to start vrflinger");
687 }
688 }
689
Mathias Agopian92a979a2012-08-02 18:32:23 -0700690 // initialize our drawing state
691 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700692
Andy McFadden13a082e2012-08-24 10:16:42 -0700693 // set initial conditions (e.g. unblank default device)
694 initializeDisplays();
695
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700696 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700699
700 const bool presentFenceReliable =
701 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
702 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703
704 if (mStartPropertySetThread->Start() != NO_ERROR) {
705 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800706 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707
Ana Krulecc2870422019-01-29 19:00:58 -0800708 mScheduler->setExpiredIdleTimerCallback([this] {
709 Mutex::Autolock lock(mStateLock);
710 setRefreshRateTo(RefreshRateType::DEFAULT);
711 });
712 mScheduler->setResetIdleTimerCallback([this] {
713 Mutex::Autolock lock(mStateLock);
714 setRefreshRateTo(RefreshRateType::PERFORMANCE);
715 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800716
Ana Krulecc2870422019-01-29 19:00:58 -0800717 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
718 *display->getId()),
719 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800736
737 property_get("persist.sys.sf.color_mode", value, "0");
738 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700739}
740
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Start boot animation service by setting a property mailbox
743 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 if (mStartPropertySetThread->join() != NO_ERROR) {
747 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700752 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700756 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760
Jamie Gennis582270d2011-08-17 18:19:00 -0700761bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800763 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800764 return authenticateSurfaceTextureLocked(bufferProducer);
765}
766
767bool SurfaceFlinger::authenticateSurfaceTextureLocked(
768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800769 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800770 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800771}
772
Brian Anderson6b376712017-04-04 10:51:39 -0700773status_t SurfaceFlinger::getSupportedFrameTimestamps(
774 std::vector<FrameEvent>* outSupported) const {
775 *outSupported = {
776 FrameEvent::REQUESTED_PRESENT,
777 FrameEvent::ACQUIRE,
778 FrameEvent::LATCH,
779 FrameEvent::FIRST_REFRESH_START,
780 FrameEvent::LAST_REFRESH_START,
781 FrameEvent::GPU_COMPOSITION_DONE,
782 FrameEvent::DEQUEUE_READY,
783 FrameEvent::RELEASE,
784 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700787 if (!getHwComposer().hasCapability(
788 HWC2::Capability::PresentFenceIsNotReliable)) {
789 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
790 }
791 return NO_ERROR;
792}
793
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800794status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
795 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 return BAD_VALUE;
798 }
799
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800800 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700801 if (!displayId) {
802 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700803 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700804
Mathias Agopian8b736f12012-08-13 17:54:26 -0700805 // TODO: Not sure if display density should handled by SF any longer
806 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700807 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700809 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800810 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700811 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812 }
813 return density;
814 }
815 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700816 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("ro.sf.lcd_density"); }
820 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 DisplayInfo info = DisplayInfo();
826
Dan Stoza9e56aa02015-11-02 13:00:03 -0800827 float xdpi = hwConfig->getDpiX();
828 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700830 info.w = hwConfig->getWidth();
831 info.h = hwConfig->getHeight();
832 // Default display viewport to display width and height
833 info.viewportW = info.w;
834 info.viewportH = info.h;
835
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800836 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 // The density of the device is provided by a build property
838 float density = Density::getBuildDensity() / 160.0f;
839 if (density == 0) {
840 // the build doesn't provide a density -- this is wrong!
841 // use xdpi instead
842 ALOGE("ro.sf.lcd_density must be defined as a build property");
843 density = xdpi / 160.0f;
844 }
845 if (Density::getEmuDensity()) {
846 // if "qemu.sf.lcd_density" is specified, it overrides everything
847 xdpi = ydpi = density = Density::getEmuDensity();
848 density /= 160.0f;
849 }
850 info.density = density;
851
852 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700853 const auto display = getDefaultDisplayDeviceLocked();
854 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855
856 // This is for screenrecord
857 const Rect viewport = display->getViewport();
858 if (viewport.isValid()) {
859 info.viewportW = uint32_t(viewport.getWidth());
860 info.viewportH = uint32_t(viewport.getHeight());
861 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 } else {
863 // TODO: where should this value come from?
864 static const int TV_DENSITY = 213;
865 info.density = TV_DENSITY / 160.0f;
866 info.orientation = 0;
867 }
868
Dan Stoza7f7da322014-05-02 15:26:25 -0700869 info.xdpi = xdpi;
870 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800872 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873
Andy McFadden91b2ca82014-06-13 14:04:23 -0700874 // This is how far in advance a buffer must be queued for
875 // presentation at a given time. If you want a buffer to appear
876 // on the screen at time N, you must submit the buffer before
877 // (N - presentationDeadline).
878 //
879 // Normally it's one full refresh period (to give SF a chance to
880 // latch the buffer), but this can be reduced by configuring a
881 // DispSync offset. Any additional delays introduced by the hardware
882 // composer or panel must be accounted for here.
883 //
884 // We add an additional 1ms to allow for processing time and
885 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800886 info.presentationDeadline =
887 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
889 // All non-virtual displays are currently considered secure.
890 info.secure = true;
891
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800892 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700893 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800894 std::swap(info.w, info.h);
895 }
896
Michael Wright28f24d02016-07-12 13:30:53 -0700897 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700898 }
899
Dan Stoza7f7da322014-05-02 15:26:25 -0700900 return NO_ERROR;
901}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700902
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700903status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
904 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700905 return BAD_VALUE;
906 }
907
Ana Krulecc2870422019-01-29 19:00:58 -0800908 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700909 return NO_ERROR;
910}
911
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700912int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
913 const auto display = getDisplayDevice(displayToken);
914 if (!display) {
915 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800916 return BAD_VALUE;
917 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700918
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700919 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700920}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
923 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800924
Ana Krulec7d1d6832018-12-27 11:10:09 -0800925 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 // Lock is acquired by setRefreshRateTo.
927 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800928 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
929 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
930 return;
931 }
932
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933 // Lock is acquired by setRefreshRateTo.
934 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935 if (!display) {
936 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
937 displayToken.get());
938 return;
939 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700940 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800941 ALOGW("Attempt to set active config %d for virtual display", mode);
942 return;
943 }
944 int currentDisplayPowerMode = display->getPowerMode();
945 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
946 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700947 return;
948 }
949
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800950 // Don't check against the current mode yet. Worst case we set the desired
951 // config twice.
952 {
953 std::lock_guard<std::mutex> lock(mActiveConfigLock);
954 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
955 }
956 // This will trigger HWC refresh without resetting the idle timer.
957 repaintEverythingForHWC();
958}
959
960status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
961 ATRACE_CALL();
962 postMessageSync(new LambdaMessage(
963 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
964 return NO_ERROR;
965}
966
967void SurfaceFlinger::setActiveConfigInHWC() {
968 ATRACE_CALL();
969
970 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
971 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 return;
973 }
Ana Krulecc2870422019-01-29 19:00:58 -0800974
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 const auto displayId = display->getId();
976 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700977
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
979 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
980 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
981 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
982}
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700983
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984void SurfaceFlinger::setActiveConfigInternal() {
985 ATRACE_CALL();
986
987 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800988 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989
990 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
991 display->setActiveConfig(mUpcomingActiveConfig.configId);
992
993 mSetActiveConfigState = SetActiveConfigState::NONE;
994 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
995
Ana Krulecc2870422019-01-29 19:00:58 -0800996 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
998}
999
1000bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1001 // Store the local variable to release the lock.
1002 ActiveConfigInfo desiredActiveConfig;
1003 {
1004 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1005 desiredActiveConfig = mDesiredActiveConfig;
1006 }
1007
1008 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1009 if (display) {
1010 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1011 display->getActiveConfig() != desiredActiveConfig.configId) {
1012 // Step 1) Desired active config was set, it is different than the
1013 // config currently in use. Notify HWC.
1014 mUpcomingActiveConfig = desiredActiveConfig;
1015 setActiveConfigInHWC();
1016 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1017 // Step 2) HWC was notified and we received refresh from it.
1018 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1019 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1020 repaintEverythingForHWC();
1021 // We do not want to give another frame to HWC while we are transitioning.
1022 return false;
1023 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1024 !(mPreviousPresentFence != Fence::NO_FENCE &&
1025 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1026 // Step 3) We received the present fence from the HWC, so we assume it
1027 // successfully updated the config, hence we update SF.
1028 setActiveConfigInternal();
1029 // If the config changed again while we were transitioning, restart the
1030 // process.
1031 if (desiredActiveConfig != mUpcomingActiveConfig) {
1032 mUpcomingActiveConfig = desiredActiveConfig;
1033 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1034 }
1035 }
1036 }
1037 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001038}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1041 Vector<ColorMode>* outColorModes) {
1042 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001043 return BAD_VALUE;
1044 }
1045
Peiyong Lina52f0292018-03-14 17:26:31 -07001046 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001047 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001048 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1049
1050 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1051 if (!displayId) {
1052 return NAME_NOT_FOUND;
1053 }
1054
Dominik Laskowski075d3172018-05-24 15:50:06 -07001055 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001056 }
Michael Wright28f24d02016-07-12 13:30:53 -07001057 outColorModes->clear();
1058 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1059
1060 return NO_ERROR;
1061}
1062
Daniel Solomon42d04562019-01-20 21:03:19 -08001063status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1064 ui::DisplayPrimaries &primaries) {
1065 if (!displayToken) {
1066 return BAD_VALUE;
1067 }
1068
1069 // Currently we only support this API for a single internal display.
1070 if (getInternalDisplayToken() != displayToken) {
1071 return BAD_VALUE;
1072 }
1073
1074 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1075 return NO_ERROR;
1076}
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1079 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001080 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001081 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001082 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001086 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 Vector<ColorMode> modes;
1088 getDisplayColorModes(displayToken, &modes);
1089 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1090 if (mode < ColorMode::NATIVE || !exists) {
1091 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1092 decodeColorMode(mode).c_str(), mode, displayToken.get());
1093 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001094 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const auto display = getDisplayDevice(displayToken);
1096 if (!display) {
1097 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1098 decodeColorMode(mode).c_str(), mode, displayToken.get());
1099 } else if (display->isVirtual()) {
1100 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1101 decodeColorMode(mode).c_str(), mode);
1102 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001103 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1104 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105 }
1106 }));
1107
Michael Wright28f24d02016-07-12 13:30:53 -07001108 return NO_ERROR;
1109}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001110
Svetoslavd85084b2014-03-20 10:28:31 -07001111status_t SurfaceFlinger::clearAnimationFrameStats() {
1112 Mutex::Autolock _l(mStateLock);
1113 mAnimFrameTracker.clearStats();
1114 return NO_ERROR;
1115}
1116
1117status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1118 Mutex::Autolock _l(mStateLock);
1119 mAnimFrameTracker.getStats(outStats);
1120 return NO_ERROR;
1121}
1122
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1124 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001125 Mutex::Autolock _l(mStateLock);
1126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127 const auto display = getDisplayDeviceLocked(displayToken);
1128 if (!display) {
1129 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001130 return BAD_VALUE;
1131 }
1132
Peiyong Linfb069302018-04-25 14:34:31 -07001133 // At this point the DisplayDeivce should already be set up,
1134 // meaning the luminance information is already queried from
1135 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001136 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001137 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1138 capabilities.getDesiredMaxLuminance(),
1139 capabilities.getDesiredMaxAverageLuminance(),
1140 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001141
1142 return NO_ERROR;
1143}
1144
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001145status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1146 ui::PixelFormat* outFormat,
1147 ui::Dataspace* outDataspace,
1148 uint8_t* outComponentMask) const {
1149 if (!outFormat || !outDataspace || !outComponentMask) {
1150 return BAD_VALUE;
1151 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001152 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001153 if (!display || !display->getId()) {
1154 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1155 return BAD_VALUE;
1156 }
1157 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1158 outDataspace, outComponentMask);
1159}
1160
Kevin DuBois74e53772018-11-19 10:52:38 -08001161status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1162 bool enable, uint8_t componentMask,
1163 uint64_t maxFrames) const {
1164 const auto display = getDisplayDevice(displayToken);
1165 if (!display || !display->getId()) {
1166 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1167 return BAD_VALUE;
1168 }
1169
1170 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1171 componentMask, maxFrames);
1172}
1173
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001174status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1175 uint64_t maxFrames, uint64_t timestamp,
1176 DisplayedFrameStats* outStats) const {
1177 const auto display = getDisplayDevice(displayToken);
1178 if (!display || !display->getId()) {
1179 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1180 return BAD_VALUE;
1181 }
1182
1183 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1184 outStats);
1185}
1186
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001187status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1188 if (!outSupported) {
1189 return BAD_VALUE;
1190 }
1191 *outSupported = getRenderEngine().supportsProtectedContent();
1192 return NO_ERROR;
1193}
1194
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001195status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1196 bool* outIsWideColorDisplay) const {
1197 if (!displayToken || !outIsWideColorDisplay) {
1198 return BAD_VALUE;
1199 }
1200 Mutex::Autolock _l(mStateLock);
1201 const auto display = getDisplayDeviceLocked(displayToken);
1202 if (!display) {
1203 return BAD_VALUE;
1204 }
1205 *outIsWideColorDisplay = display->hasWideColorGamut();
1206 return NO_ERROR;
1207}
1208
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001210 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001211 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212
Chia-I Wu90f669f2017-10-05 14:24:41 -07001213 if (mInjectVSyncs == enable) {
1214 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001216
Ana Krulecc2870422019-01-29 19:00:58 -08001217 auto resyncCallback =
1218 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001219
Ana Krulec98b5b242018-08-10 15:03:23 -07001220 // TODO(akrulec): Part of the Injector should be refactored, so that it
1221 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001222 if (enable) {
1223 ALOGV("VSync Injections enabled");
1224 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001225 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001226 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001227 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001228 impl::EventThread::InterceptVSyncsCallback(),
1229 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001231 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001232 } else {
1233 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001234 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1235 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236 }
1237
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001239 }));
1240
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001241 return NO_ERROR;
1242}
1243
1244status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001245 Mutex::Autolock _l(mStateLock);
1246
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001247 if (!mInjectVSyncs) {
1248 ALOGE("VSync Injections not enabled");
1249 return BAD_VALUE;
1250 }
1251 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1252 ALOGV("Injecting VSync inside SurfaceFlinger");
1253 mVSyncInjector->onInjectSyncEvent(when);
1254 }
1255 return NO_ERROR;
1256}
1257
Lloyd Pique755e3192018-01-31 16:46:15 -08001258status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1259 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001260 // Try to acquire a lock for 1s, fail gracefully
1261 const status_t err = mStateLock.timedLock(s2ns(1));
1262 const bool locked = (err == NO_ERROR);
1263 if (!locked) {
1264 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1265 return TIMED_OUT;
1266 }
1267
1268 outLayers->clear();
1269 mCurrentState.traverseInZOrder([&](Layer* layer) {
1270 outLayers->push_back(layer->getLayerDebugInfo());
1271 });
1272
1273 mStateLock.unlock();
1274 return NO_ERROR;
1275}
1276
Peiyong Linc6780972018-10-28 15:24:08 -07001277status_t SurfaceFlinger::getCompositionPreference(
1278 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1279 Dataspace* outWideColorGamutDataspace,
1280 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001281 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001282 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001283 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001284 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001285 return NO_ERROR;
1286}
1287
Dan Stoza84ab9372018-12-17 15:27:57 -08001288status_t SurfaceFlinger::addRegionSamplingListener(
1289 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1290 const sp<IRegionSamplingListener>& /*listener*/) {
1291 return NO_ERROR;
1292}
1293
1294status_t SurfaceFlinger::removeRegionSamplingListener(
1295 const sp<IRegionSamplingListener>& /*listener*/) {
1296 return NO_ERROR;
1297}
1298
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001299// ----------------------------------------------------------------------------
1300
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001301sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1302 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001303 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001304 Mutex::Autolock lock(mStateLock);
1305 return getVsyncPeriod();
1306 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001307
Ana Krulecc2870422019-01-29 19:00:58 -08001308 const auto& handle =
1309 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001310
Ana Krulecc2870422019-01-29 19:00:58 -08001311 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001312}
1313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001314// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315
1316void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001317 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001318}
1319
1320void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001321 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001322}
1323
1324void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001325 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001326}
1327
1328void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001329 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001330 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001331}
1332
1333status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001334 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001335 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001336}
1337
1338status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001339 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001340 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001341 if (res == NO_ERROR) {
1342 msg->wait();
1343 }
1344 return res;
1345}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001346
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001347void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001348 do {
1349 waitForEvent();
1350 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351}
1352
Dominik Laskowski83b88212018-12-11 13:34:06 -08001353nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001354 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001355 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1356 return 0;
1357 }
1358
1359 const auto config = getHwComposer().getActiveConfig(*displayId);
1360 return config ? config->getVsyncPeriod() : 0;
1361}
1362
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001363void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1364 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001365 ATRACE_NAME("SF onVsync");
1366
Steven Thomas3cfac282017-02-06 12:29:30 -08001367 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001369 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 return;
1371 }
1372
Dominik Laskowski075d3172018-05-24 15:50:06 -07001373 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001374 return;
1375 }
1376
Dominik Laskowski075d3172018-05-24 15:50:06 -07001377 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001378 // For now, we don't do anything with external display vsyncs.
1379 return;
1380 }
1381
Ana Krulecc2870422019-01-29 19:00:58 -08001382 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001383}
1384
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001385void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001386 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1387 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388}
1389
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001390void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1391 mPhaseOffsets->setRefreshRateType(refreshRate);
1392
1393 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1394 mVsyncModulator.setPhaseOffsets(early, gl, late);
1395
1396 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001397 return;
1398 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001399
Ana Krulec7d1d6832018-12-27 11:10:09 -08001400 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1401 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1402 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1403 // refresh cycle.
1404
1405 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001406 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001407 if (currentVsyncPeriod == 0) {
1408 return;
1409 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001410
Ana Krulec7d1d6832018-12-27 11:10:09 -08001411 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1412 // floating numbers.
1413 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001414 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1415 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001416 if (std::abs(currentFps - newFps) <= 1) {
1417 return;
1418 }
1419
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001420 const auto displayId = getInternalDisplayIdLocked();
1421 LOG_ALWAYS_FATAL_IF(!displayId);
1422
1423 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001424 for (int i = 0; i < configs.size(); i++) {
1425 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1426 if (vsyncPeriod == 0) {
1427 continue;
1428 }
1429 const float fps = 1e9 / vsyncPeriod;
1430 // TODO(b/113612090): There should be a better way at determining which config
1431 // has the right refresh rate.
1432 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001433 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434 }
1435 }
1436}
1437
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001438void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001439 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001440 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001441 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001442
Lloyd Piqueba04e622017-12-14 17:11:26 -08001443 // Ignore events that do not have the right sequenceId.
1444 if (sequenceId != getBE().mComposerSequenceId) {
1445 return;
1446 }
1447
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 // Only lock if we're not on the main thread. This function is normally
1449 // called on a hwbinder thread, but for the primary display it's called on
1450 // the main thread with the state lock already held, so don't attempt to
1451 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001452 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001455
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001456 if (std::this_thread::get_id() == mMainThreadId) {
1457 // Process all pending hot plug events immediately if we are on the main thread.
1458 processDisplayHotplugEventsLocked();
1459 }
1460
Lloyd Piqueba04e622017-12-14 17:11:26 -08001461 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001462}
1463
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001464void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001465 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001466 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001467 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001468 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001469 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001470}
1471
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001472void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001473 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001474 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001475 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001476 getHwComposer().setVsyncEnabled(*displayId,
1477 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1478 }
Mathias Agopian86303202012-07-24 22:46:10 -07001479}
1480
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001482void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001483 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001484 // Clear the drawing state so that the logic inside of
1485 // handleTransactionLocked will fire. It will determine the delta between
1486 // mCurrentState and mDrawingState and re-apply all changes when we make the
1487 // transition.
1488 mDrawingState.displays.clear();
1489 mDisplays.clear();
1490}
1491
Steven Thomas050b2c82017-03-06 11:45:16 -08001492void SurfaceFlinger::updateVrFlinger() {
1493 if (!mVrFlinger)
1494 return;
1495 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001496 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001497 return;
1498 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001499
Lloyd Pique441d5042018-10-18 16:49:51 -07001500 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 ALOGE("Vr flinger is only supported for remote hardware composer"
1502 " service connections. Ignoring request to transition to vr"
1503 " flinger.");
1504 mVrFlingerRequestsDisplay = false;
1505 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001506 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001507
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001508 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001509
Steven Thomas0123ac62018-07-12 11:32:34 -07001510 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001511 LOG_ALWAYS_FATAL_IF(!display);
1512 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001513 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1514 // called below. Clear the reference now so we don't accidentally use it
1515 // later.
1516 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517
Steven Thomasb02664d2017-07-26 18:48:28 -07001518 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001521
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001523 // Delete the current instance before creating the new one
1524 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1525 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1526 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1527 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001528
Lloyd Pique441d5042018-10-18 16:49:51 -07001529 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001530 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001531
1532 if (vrFlingerRequestsDisplay) {
1533 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001534 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001535
1536 mVisibleRegionsDirty = true;
1537 invalidateHwcGeometry();
1538
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001539 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001540 display = getDefaultDisplayDeviceLocked();
1541 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001542 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001543
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001545 const nsecs_t vsyncPeriod = getVsyncPeriod();
1546 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001547
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001548 // The present fences returned from vr_hwc are not an accurate
1549 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001550 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001551
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 // Use phase of 0 since phase is not known.
1553 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001554 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001555 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001556
Ana Krulecc2870422019-01-29 19:00:58 -08001557 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001558
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001559 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001561}
1562
Mathias Agopian4fec8732012-06-29 14:12:52 -07001563void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001564 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001565 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001566 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001567 if (!updateSetActiveConfigStateMachine()) {
1568 break;
1569 }
1570
Ana Krulecc2870422019-01-29 19:00:58 -08001571 // This call is made each time SF wakes up and creates a new frame.
1572 mScheduler->incrementFrameCounter();
1573
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001574 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1575 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001576 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001577 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001578 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001579 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001580 if (mPropagateBackpressure) {
1581 signalLayerUpdate();
1582 break;
1583 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001584 }
Dan Stoza50182882016-07-08 12:02:20 -07001585
Steven Thomas050b2c82017-03-06 11:45:16 -08001586 // Now that we're going to make it to the handleMessageTransaction()
1587 // call below it's safe to call updateVrFlinger(), which will
1588 // potentially trigger a display handoff.
1589 updateVrFlinger();
1590
Dan Stoza6b9454d2014-11-07 16:00:59 -08001591 bool refreshNeeded = handleMessageTransaction();
1592 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001593
1594 updateCursorAsync();
1595 updateInputFlinger();
1596
Dan Stoza58784442014-12-02 16:58:17 -08001597 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001598 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001599 // Signal a refresh if a transaction modified the window state,
1600 // a new buffer was latched, or if HWC has requested a full
1601 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001602 signalRefresh();
1603 }
1604 break;
1605 }
1606 case MessageQueue::REFRESH: {
1607 handleMessageRefresh();
1608 break;
1609 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001610 }
1611}
1612
Dan Stoza6b9454d2014-11-07 16:00:59 -08001613bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001614 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001615
1616 // Apply any ready transactions in the queues if there are still transactions that have not been
1617 // applied, wake up during the next vsync period and check again
1618 bool transactionNeeded = false;
1619 if (!flushTransactionQueues()) {
1620 transactionNeeded = true;
1621 }
1622
Mathias Agopian4fec8732012-06-29 14:12:52 -07001623 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001624 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001625 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001626
1627 if (transactionNeeded) {
1628 setTransactionFlags(eTransactionNeeded);
1629 }
1630
1631 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001632}
1633
Mathias Agopian4fec8732012-06-29 14:12:52 -07001634void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001635 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001636
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001637 mRefreshPending = false;
1638
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001639 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001640 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001641 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001642 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001643 for (const auto& [token, display] : mDisplays) {
1644 beginFrame(display);
1645 prepareFrame(display);
1646 doDebugFlashRegions(display, repaintEverything);
1647 doComposition(display, repaintEverything);
1648 }
1649
Adrian Roos1e1a1282017-11-01 19:05:31 +01001650 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001651 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001652
1653 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001654 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001655
Dan Stozabfbffeb2016-07-21 14:49:33 -07001656 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001657 for (const auto& [token, displayDevice] : mDisplays) {
1658 auto display = displayDevice->getCompositionDisplay();
1659 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001660 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001661 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001662 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001663
Alec Mouri86770e52018-09-24 22:40:58 +00001664 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001665 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001666 if (mHadClientComposition) {
1667 base::unique_fd flushFence(getRenderEngine().flush());
1668 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1669 getBE().flushFence = new Fence(std::move(flushFence));
1670 } else {
1671 // Cleanup for hygiene.
1672 getBE().flushFence = Fence::NO_FENCE;
1673 }
1674 }
1675
Jorim Jaggi90535212018-05-23 23:44:06 +02001676 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001677
David Sodman7e4ae112018-02-09 15:02:28 -08001678 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001679
1680 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682
David Sodmanfa9b2af2017-12-24 13:28:59 -08001683
1684bool SurfaceFlinger::handleMessageInvalidate() {
1685 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001686 bool refreshNeeded = handlePageFlip();
1687
Vishnu Nair4351ad52019-02-11 14:13:02 -08001688 if (mVisibleRegionsDirty) {
1689 computeLayerBounds();
1690 }
1691
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001692 for (auto& layer : mLayersPendingRefresh) {
1693 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001694 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001695 invalidateLayerStack(layer, visibleReg);
1696 }
1697 mLayersPendingRefresh.clear();
1698 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001699}
1700
David Sodman79bba0e2018-08-05 18:07:49 -07001701void SurfaceFlinger::calculateWorkingSet() {
1702 ATRACE_CALL();
1703 ALOGV(__FUNCTION__);
1704
David Sodman79bba0e2018-08-05 18:07:49 -07001705 // build the h/w work list
1706 if (CC_UNLIKELY(mGeometryInvalid)) {
1707 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001708 for (const auto& [token, displayDevice] : mDisplays) {
1709 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001710 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001711 if (!displayId) {
1712 continue;
1713 }
David Sodman79bba0e2018-08-05 18:07:49 -07001714
Lloyd Pique32cbe282018-10-19 13:09:22 -07001715 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001716 for (size_t i = 0; i < currentLayers.size(); i++) {
1717 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001718
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001719 if (!layer->hasHwcLayer(displayDevice)) {
1720 if (!layer->createHwcLayer(&getHwComposer(), displayDevice)) {
1721 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001722 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001723 }
1724 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001725
Lloyd Pique32cbe282018-10-19 13:09:22 -07001726 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001727 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001728 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001729 }
David Sodman79bba0e2018-08-05 18:07:49 -07001730 }
1731 }
1732 }
1733
1734 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001735 for (const auto& [token, displayDevice] : mDisplays) {
1736 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001737 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001739 continue;
1740 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001741 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001742
1743 if (mDrawingState.colorMatrixChanged) {
1744 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001745 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001746 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001747 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001748 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001749 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1750 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001751 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001752 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001753 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1754 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001755 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001756 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001757 }
1758
Peiyong Lind3788632018-09-18 16:01:31 -07001759 // TODO(b/111562338) remove when composer 2.3 is shipped.
1760 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001761 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001762 }
1763
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001764 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001765 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001766 }
1767
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001768 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001769 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001770 layer->setCompositionType(displayDevice,
1771 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001772 continue;
1773 }
1774
Lloyd Pique32cbe282018-10-19 13:09:22 -07001775 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001776 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001777 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001778 }
1779
Peiyong Lin13effd12018-07-24 17:01:47 -07001780 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001781 ColorMode colorMode;
1782 Dataspace dataSpace;
1783 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001784 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001785 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001786 }
1787 }
1788
1789 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001790
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001791 for (const auto& [token, displayDevice] : mDisplays) {
1792 auto display = displayDevice->getCompositionDisplay();
1793 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001794 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001795 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1796 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1797 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001798 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001799 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001800 }
1801 }
David Sodman79bba0e2018-08-05 18:07:49 -07001802}
1803
Lloyd Pique32cbe282018-10-19 13:09:22 -07001804void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1805 bool repaintEverything) {
1806 auto display = displayDevice->getCompositionDisplay();
1807 const auto& displayState = display->getState();
1808
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809 // is debugging enabled
1810 if (CC_LIKELY(!mDebugRegion))
1811 return;
1812
Lloyd Pique32cbe282018-10-19 13:09:22 -07001813 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001814 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001815 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001816 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001817 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001818 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001819 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001821 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822 }
1823 }
1824
Lloyd Pique32cbe282018-10-19 13:09:22 -07001825 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001826
1827 if (mDebugRegion > 1) {
1828 usleep(mDebugRegion * 1000);
1829 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001830
Lloyd Pique32cbe282018-10-19 13:09:22 -07001831 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832}
1833
Adrian Roos1e1a1282017-11-01 19:05:31 +01001834void SurfaceFlinger::doTracing(const char* where) {
1835 ATRACE_CALL();
1836 ATRACE_NAME(where);
1837 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001838 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001839 }
1840}
1841
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001842void SurfaceFlinger::logLayerStats() {
1843 ATRACE_CALL();
1844 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001845 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001846 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001847 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001848 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001849 }
1850 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001851
1852 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001853 }
1854}
1855
David Sodman2b406362017-12-15 13:33:47 -08001856void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 ATRACE_CALL();
1859 ALOGV("preComposition");
1860
David Sodman2b406362017-12-15 13:33:47 -08001861 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1862
Mathias Agopiancd60f992012-08-16 16:28:27 -07001863 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001864 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001865 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866 needExtraInvalidate = true;
1867 }
Robert Carr2047fae2016-11-28 14:09:09 -08001868 });
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 if (needExtraInvalidate) {
1871 signalLayerUpdate();
1872 }
1873}
1874
Ana Krulece588e312018-09-18 12:32:24 -07001875void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1876 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001877 // Update queue of past composite+present times and determine the
1878 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001879 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001880 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001881 while (!getBE().mCompositePresentTimes.empty()) {
1882 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001883 // Cached values should have been updated before calling this method,
1884 // which helps avoid duplicate syscalls.
1885 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1886 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1887 break;
1888 }
1889 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001890 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001891 }
1892
1893 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001894 while (getBE().mCompositePresentTimes.size() > 16) {
1895 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896 }
1897
Ana Krulece588e312018-09-18 12:32:24 -07001898 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001899}
1900
Ana Krulece588e312018-09-18 12:32:24 -07001901void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1902 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 // Integer division and modulo round toward 0 not -inf, so we need to
1904 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001905 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1906 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1907 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908
Ana Krulec757f63a2019-01-25 10:46:18 -08001909 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001910 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001911 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001912 }
1913
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914 // Snap the latency to a value that removes scheduling jitter from the
1915 // composition and present times, which often have >1ms of jitter.
1916 // Reducing jitter is important if an app attempts to extrapolate
1917 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001918 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001920 nsecs_t bias = stats.vsyncPeriod / 2;
1921 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1922 nsecs_t snappedCompositeToPresentLatency =
1923 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924
David Sodman99974d22017-11-28 12:04:33 -08001925 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001926 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1927 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001928 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001929}
1930
Ady Abraham8164d482019-01-11 14:47:59 -08001931// debug patch for b/119477596 - add stack guards to catch stack
1932// corruptions and disable clang optimizations.
1933// The code below is temporary and planned to be removed once stack
1934// corruptions are found.
1935#pragma clang optimize off
1936class StackGuard {
1937public:
1938 StackGuard(const char* name, const char* func, int line) {
1939 guarders.reserve(MIN_CAPACITY);
1940 guarders.push_back({this, name, func, line});
1941 validate();
1942 }
1943 ~StackGuard() {
1944 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1945 if (i->guard == this) {
1946 guarders.erase(i);
1947 break;
1948 }
1949 }
1950 }
1951
1952 static void validate() {
1953 for (const auto& guard : guarders) {
1954 if (guard.guard->cookie != COOKIE_VALUE) {
1955 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1956 CallStack stack(LOG_TAG);
1957 abort();
1958 }
1959 }
1960 }
1961
1962private:
1963 uint64_t cookie = COOKIE_VALUE;
1964 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1965 static constexpr size_t MIN_CAPACITY = 16;
1966
1967 struct GuarderElement {
1968 StackGuard* guard;
1969 const char* name;
1970 const char* func;
1971 int line;
1972 };
1973
1974 static std::vector<GuarderElement> guarders;
1975};
1976std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1977
1978#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1979
1980#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08001981void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982{
Ady Abraham8164d482019-01-11 14:47:59 -08001983 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 ATRACE_CALL();
1985 ALOGV("postComposition");
1986
Brian Anderson3546a3f2016-07-14 11:51:14 -07001987 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001988 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08001989 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001990 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001991 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001992 }
Ady Abraham8164d482019-01-11 14:47:59 -08001993 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001994
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001995 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001996 const auto displayDevice = getDefaultDisplayDeviceLocked();
1997 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001998
David Sodman73beded2017-11-15 11:56:06 -08001999 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002000 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002001 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2002
Lloyd Pique32cbe282018-10-19 13:09:22 -07002003 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002004 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002005 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2006 ->getRenderSurface()
2007 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002008 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002009 } else {
2010 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2011 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012
Ady Abraham8164d482019-01-11 14:47:59 -08002013 ASSERT_ON_STACK_GUARD();
2014
David Sodman73beded2017-11-15 11:56:06 -08002015 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002016 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2017 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002018 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002019 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021
Ana Krulece588e312018-09-18 12:32:24 -07002022 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002023 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002024 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002025
Ady Abraham8164d482019-01-11 14:47:59 -08002026 ASSERT_ON_STACK_GUARD();
2027
David Sodman2b406362017-12-15 13:33:47 -08002028 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002029 // when we started doing work for this frame, but that should be okay
2030 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002031 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002032 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002033 DEFINE_STACK_GUARD(compositorTiming);
2034
Brian Andersond0010582017-03-07 13:20:31 -08002035 {
David Sodman99974d22017-11-28 12:04:33 -08002036 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002037 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002038 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002039
2040 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002041 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042
Robert Carr2047fae2016-11-28 14:09:09 -08002043 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 bool frameLatched =
2045 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2046 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002047 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002048 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002049 recordBufferingStats(layer->getName().string(),
2050 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002051 }
Ady Abraham8164d482019-01-11 14:47:59 -08002052 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002053 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002054
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002055 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002056 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002057 mScheduler->addPresentFence(presentFenceTime);
2058 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002059 }
2060
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002061 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002062 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2063 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002064 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002065 }
2066 }
2067
Ady Abraham8164d482019-01-11 14:47:59 -08002068 ASSERT_ON_STACK_GUARD();
2069
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002070 if (mAnimCompositionPending) {
2071 mAnimCompositionPending = false;
2072
Brian Anderson4e606e32017-03-16 15:34:57 -07002073 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002074 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002075 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002076
2077 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002078 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002079 // The HWC doesn't support present fences, so use the refresh
2080 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002081 const nsecs_t presentTime =
2082 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002083 DEFINE_STACK_GUARD(presentTime);
2084
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002085 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002086 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002087 }
2088 mAnimFrameTracker.advanceFrame();
2089 }
Dan Stozab90cf072015-03-05 11:05:59 -08002090
Ady Abraham8164d482019-01-11 14:47:59 -08002091 ASSERT_ON_STACK_GUARD();
2092
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002093 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002094 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002095 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002096 }
2097
Ady Abraham8164d482019-01-11 14:47:59 -08002098 ASSERT_ON_STACK_GUARD();
2099
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002100 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002101
Ady Abraham8164d482019-01-11 14:47:59 -08002102 ASSERT_ON_STACK_GUARD();
2103
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2105 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002106 return;
2107 }
2108
2109 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002110 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002111 if (mHasPoweredOff) {
2112 mHasPoweredOff = false;
2113 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002114 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002115 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002116 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002117 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002118 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2119 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002120 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002121 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002122 }
David Sodman4a36e932017-11-07 14:29:47 -08002123 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002124
2125 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002126 }
David Sodman4a36e932017-11-07 14:29:47 -08002127 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002128 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002129
2130 {
2131 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002132 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002133 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002134 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002135 if (refillCount > 0) {
2136 const size_t offset = mTexturePool.size();
2137 mTexturePool.resize(mTexturePoolSize);
2138 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2139 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2140 }
Ady Abraham8164d482019-01-11 14:47:59 -08002141 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002142 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002143
Marissa Wallfda30bb2018-10-12 11:34:28 -07002144 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002145 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002146
2147 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002148}
Ady Abraham8164d482019-01-11 14:47:59 -08002149#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150
Vishnu Nair4351ad52019-02-11 14:13:02 -08002151void SurfaceFlinger::computeLayerBounds() {
2152 for (const auto& pair : mDisplays) {
2153 const auto& displayDevice = pair.second;
2154 const auto display = displayDevice->getCompositionDisplay();
2155 for (const auto& layer : mDrawingState.layersSortedByZ) {
2156 // only consider the layers on the given layer stack
2157 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002158 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002159 }
2160
2161 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2162 }
2163 }
2164}
2165
Mathias Agopiancd60f992012-08-16 16:28:27 -07002166void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167 ATRACE_CALL();
2168 ALOGV("rebuildLayerStacks");
2169
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002170 // We need to clear these out now as these may be holding on to a
2171 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2172 // also holds a reference. When the set of visible layers is recomputed,
2173 // some layers may be destroyed if the only thing keeping them alive was
2174 // that list of visible layers associated with each display. The layer
2175 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2176 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2177 for (const auto& [token, display] : mDisplays) {
2178 getBE().mCompositionInfo[token].clear();
2179 }
2180
Mathias Agopiancd60f992012-08-16 16:28:27 -07002181 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002182 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002183 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002184 mVisibleRegionsDirty = false;
2185 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002186
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002187 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002188 const auto& displayDevice = pair.second;
2189 auto display = displayDevice->getCompositionDisplay();
2190 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002191 Region opaqueRegion;
2192 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002193 compositionengine::Output::OutputLayers layersSortedByZ;
2194 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002195 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002196 const ui::Transform& tr = displayState.transform;
2197 const Rect bounds = displayState.bounds;
2198 if (displayState.isEnabled) {
2199 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002200
Jeff Sharkey76488112017-02-27 14:15:18 -07002201 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002202 auto compositionLayer = layer->getCompositionLayer();
2203 if (compositionLayer == nullptr) {
2204 return;
2205 }
2206
Chia-I Wu83806892017-11-16 10:50:20 -08002207 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002208 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002209 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2210 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2211
Lloyd Piqueef36b002019-01-23 17:52:04 -08002212 if (display->belongsInOutput(layer->getLayerStack(),
2213 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002214 Region drawRegion(tr.transform(
2215 layer->visibleNonTransparentRegion));
2216 drawRegion.andSelf(bounds);
2217 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002218 layersSortedByZ.emplace_back(
2219 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2220 layerFE));
2221
2222 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002223 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002224 // Clear out the HWC layer if this layer was
2225 // previously visible, but no longer is
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002226 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(displayDevice);
Jeff Sharkey76488112017-02-27 14:15:18 -07002227 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002228 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002229 // WM changes display->layerStack upon sleep/awake.
2230 // Here we make sure we delete the HWC layers even if
2231 // WM changed their layer stack.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002232 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(displayDevice);
Chia-I Wu83806892017-11-16 10:50:20 -08002233 }
2234
2235 // If a layer is not going to get a release fence because
2236 // it is invisible, but it is also going to release its
2237 // old buffer, add it to the list of layers needing
2238 // fences.
2239 if (hwcLayerDestroyed) {
2240 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2241 mLayersWithQueuedFrames.cend(), layer);
2242 if (found != mLayersWithQueuedFrames.cend()) {
2243 layersNeedingFences.add(layer);
2244 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002245 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002246 });
2247 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002248
2249 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2250
2251 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002252 displayDevice->setLayersNeedingFences(layersNeedingFences);
2253
2254 Region undefinedRegion{bounds};
2255 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2256
2257 display->editState().undefinedRegion = undefinedRegion;
2258 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002259 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002260 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002261}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002262
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002263// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002264// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002265// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002266// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002267// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002268// The returned HDR data space is one of
2269// - Dataspace::UNKNOWN
2270// - Dataspace::BT2020_HLG
2271// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002272Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2273 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002274 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002275 *outHdrDataSpace = Dataspace::UNKNOWN;
2276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002278 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002279 case Dataspace::V0_SCRGB:
2280 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002281 case Dataspace::BT2020:
2282 case Dataspace::BT2020_ITU:
2283 case Dataspace::BT2020_LINEAR:
2284 case Dataspace::DISPLAY_BT2020:
2285 bestDataSpace = Dataspace::DISPLAY_BT2020;
2286 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002288 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002289 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002290 case Dataspace::BT2020_PQ:
2291 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002292 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002294 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002295 case Dataspace::BT2020_HLG:
2296 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002297 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298 // When there's mixed PQ content and HLG content, we set the HDR
2299 // data space to be BT2020_PQ and convert HLG to PQ.
2300 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2301 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002302 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303 break;
2304 default:
2305 break;
2306 }
Romain Guy54f154a2017-10-24 21:40:32 +01002307 }
2308
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002309 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002310}
2311
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002312// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002313void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2314 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2316 *outMode = ColorMode::NATIVE;
2317 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002320 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002321
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002324
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002325 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2326
Peiyong Lina3ea5592019-02-10 14:45:00 -08002327 switch (mForceColorMode) {
2328 case ColorMode::SRGB:
2329 bestDataSpace = Dataspace::V0_SRGB;
2330 break;
2331 case ColorMode::DISPLAY_P3:
2332 bestDataSpace = Dataspace::DISPLAY_P3;
2333 break;
2334 default:
2335 break;
2336 }
2337
Peiyong Lindfde5112018-06-05 10:58:41 -07002338 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002339 const bool isHdr =
2340 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002341 if (isHdr) {
2342 bestDataSpace = hdrDataSpace;
2343 }
2344
Chia-I Wu0d711262018-05-21 15:19:35 -07002345 RenderIntent intent;
2346 switch (mDisplayColorSetting) {
2347 case DisplayColorSetting::MANAGED:
2348 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002349 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002350 break;
2351 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002352 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002353 break;
2354 default: // vendor display color setting
2355 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2356 break;
2357 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002358
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002359 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002360}
2361
Lloyd Pique32cbe282018-10-19 13:09:22 -07002362void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2363 auto display = displayDevice->getCompositionDisplay();
2364 const auto& displayState = display->getState();
2365
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002366 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002367 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2368 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002369
David Sodmanfa9b2af2017-12-24 13:28:59 -08002370 // If nothing has changed (!dirty), don't recompose.
2371 // If something changed, but we don't currently have any visible layers,
2372 // and didn't when we last did a composition, then skip it this time.
2373 // The second rule does two things:
2374 // - When all layers are removed from a display, we'll emit one black
2375 // frame, then nothing more until we get new layers.
2376 // - When a display is created with a private layer stack, we won't
2377 // emit any black frames until a layer is added to the layer stack.
2378 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002379
Dominik Laskowski075d3172018-05-24 15:50:06 -07002380 const char flagPrefix[] = {'-', '+'};
2381 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002382 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2383 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2384 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2385 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002386
Lloyd Pique31cb2942018-10-19 17:23:03 -07002387 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002388
David Sodmanfa9b2af2017-12-24 13:28:59 -08002389 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002391 }
2392}
2393
Lloyd Pique32cbe282018-10-19 13:09:22 -07002394void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2395 auto display = displayDevice->getCompositionDisplay();
2396 const auto& displayState = display->getState();
2397
2398 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002399 return;
David Sodman2b406362017-12-15 13:33:47 -08002400 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002401
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002402 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002405}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002406
Lloyd Pique32cbe282018-10-19 13:09:22 -07002407void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002408 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 ALOGV("doComposition");
2410
Lloyd Pique32cbe282018-10-19 13:09:22 -07002411 auto display = displayDevice->getCompositionDisplay();
2412 const auto& displayState = display->getState();
2413
2414 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002415 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002416 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002417
David Sodmanfa9b2af2017-12-24 13:28:59 -08002418 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002419 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002420
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002422 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002423 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002425}
2426
David Sodmanfa9b2af2017-12-24 13:28:59 -08002427void SurfaceFlinger::postFrame()
2428{
2429 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 const auto display = getDefaultDisplayDeviceLocked();
2431 if (display && getHwComposer().isConnected(*display->getId())) {
2432 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002433 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2434 logFrameStats();
2435 }
2436 }
2437}
2438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002440 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002441 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002442
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 auto display = displayDevice->getCompositionDisplay();
2444 const auto& displayState = display->getState();
2445 const auto displayId = display->getId();
2446
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 if (displayId) {
2451 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002452 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002453 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002455 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002456
Chia-I Wu7b549592017-11-15 09:14:57 -08002457 // The layer buffer from the previous frame (if any) is released
2458 // by HWC only when the release fence from this frame (if any) is
2459 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002460 if (displayId && layer->hasHwcLayer(displayDevice)) {
2461 releaseFence =
2462 getHwComposer().getLayerReleaseFence(*displayId,
2463 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002464 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002465
2466 // If the layer was client composited in the previous frame, we
2467 // need to merge with the previous client target acquire fence.
2468 // Since we do not track that, always merge with the current
2469 // client target acquire fence when it is available, even though
2470 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002471 if (layer->getCompositionType(displayDevice) ==
2472 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002473 releaseFence =
2474 Fence::merge("LayerRelease", releaseFence,
2475 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002476 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002477
David Sodman15094112018-10-11 09:39:37 -07002478 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 }
Chia-I Wu83806892017-11-16 10:50:20 -08002480
2481 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002482 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002483 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002484 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002485 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002486 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002487 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002488 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002489 }
2490 }
2491
Dominik Laskowski075d3172018-05-24 15:50:06 -07002492 if (displayId) {
2493 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002494 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002495 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496}
2497
Mathias Agopian87baae12012-07-31 12:38:26 -07002498void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499{
Mathias Agopian841cde52012-03-01 15:44:37 -08002500 ATRACE_CALL();
2501
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002502 // here we keep a copy of the drawing state (that is the state that's
2503 // going to be overwritten by handleTransactionLocked()) outside of
2504 // mStateLock so that the side-effects of the State assignment
2505 // don't happen with mStateLock held (which can cause deadlocks).
2506 State drawingState(mDrawingState);
2507
Mathias Agopianca4d3602011-05-19 15:38:14 -07002508 Mutex::Autolock _l(mStateLock);
2509 const nsecs_t now = systemTime();
2510 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511
Mathias Agopianca4d3602011-05-19 15:38:14 -07002512 // Here we're guaranteed that some transaction flags are set
2513 // so we can call handleTransactionLocked() unconditionally.
2514 // We call getTransactionFlags(), which will also clear the flags,
2515 // with mStateLock held to guarantee that mCurrentState won't change
2516 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002517
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002518 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002519 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002520 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002521
Mathias Agopianca4d3602011-05-19 15:38:14 -07002522 mLastTransactionTime = systemTime() - now;
2523 mDebugInTransaction = 0;
2524 invalidateHwcGeometry();
2525 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002526}
2527
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2529 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002530 const std::optional<DisplayIdentificationInfo> info =
2531 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002532
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002534 continue;
2535 }
2536
Lloyd Piqueba04e622017-12-14 17:11:26 -08002537 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002538 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002539 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 mPhysicalDisplayTokens[info->id] = new BBinder();
2541 DisplayDeviceState state;
2542 state.displayId = info->id;
2543 state.isSecure = true; // All physical displays are currently considered secure.
2544 state.displayName = info->name;
2545 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2546 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002547 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002549 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2552 if (index >= 0) {
2553 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2554 mInterceptor->saveDisplayDeletion(state.sequenceId);
2555 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002556 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002558 }
2559
2560 processDisplayChangesLocked();
2561 }
2562
2563 mPendingHotplugEvents.clear();
2564}
2565
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002566void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002567 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2568 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002569}
2570
Lloyd Pique99d3da52018-01-22 17:48:03 -08002571sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002572 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002573 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 const sp<IGraphicBufferProducer>& producer) {
2575 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002576 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002578 creationArgs.isSecure = state.isSecure;
2579 creationArgs.displaySurface = dispSurface;
2580 creationArgs.hasWideColorGamut = false;
2581 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002582
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002583 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 creationArgs.isPrimary = isInternalDisplay;
2585
2586 if (useColorManagement && displayId) {
2587 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002588 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002589 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002590 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002591 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002592
Dominik Laskowski7e045462018-05-30 13:02:02 -07002593 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002595 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002596 }
tangrobin6753a022018-08-10 10:58:54 +08002597 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 if (displayId) {
2600 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002601 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002603 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002604
Lloyd Pique90c115d2018-09-18 21:39:42 -07002605 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002607 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609 // Make sure that composition can never be stalled by a virtual display
2610 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002611 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002612 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002613 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2614 }
2615
Dominik Laskowski075d3172018-05-24 15:50:06 -07002616 creationArgs.displayInstallOrientation =
2617 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002618
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002620 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621
Lloyd Pique90c115d2018-09-18 21:39:42 -07002622 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623
2624 if (maxFrameBufferAcquiredBuffers >= 3) {
2625 nativeWindowSurface->preallocateBuffers();
2626 }
2627
2628 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002629 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002630 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002631 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002632 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002634 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2635 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 if (!state.isVirtual()) {
2637 LOG_ALWAYS_FATAL_IF(!displayId);
2638 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002639 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002641 display->setLayerStack(state.layerStack);
2642 display->setProjection(state.orientation, state.viewport, state.frame);
2643 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002645 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646}
2647
Lloyd Pique347200f2017-12-14 17:00:15 -08002648void SurfaceFlinger::processDisplayChangesLocked() {
2649 // here we take advantage of Vector's copy-on-write semantics to
2650 // improve performance by skipping the transaction entirely when
2651 // know that the lists are identical
2652 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2653 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2654 if (!curr.isIdenticalTo(draw)) {
2655 mVisibleRegionsDirty = true;
2656 const size_t cc = curr.size();
2657 size_t dc = draw.size();
2658
2659 // find the displays that were removed
2660 // (ie: in drawing state but not in current state)
2661 // also handle displays that changed
2662 // (ie: displays that are in both lists)
2663 for (size_t i = 0; i < dc;) {
2664 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2665 if (j < 0) {
2666 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002667 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002668 // Save display ID before disconnecting.
2669 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002670 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002671
2672 if (!display->isVirtual()) {
2673 LOG_ALWAYS_FATAL_IF(!displayId);
2674 dispatchDisplayHotplugEvent(displayId->value, false);
2675 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002676 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002677
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002678 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002679 } else {
2680 // this display is in both lists. see if something changed.
2681 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002682 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002683 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2684 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2685 if (state_binder != draw_binder) {
2686 // changing the surface is like destroying and
2687 // recreating the DisplayDevice, so we just remove it
2688 // from the drawing state, so that it get re-added
2689 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002690 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002691 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002693 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002694 mDrawingState.displays.removeItemsAt(i);
2695 dc--;
2696 // at this point we must loop to the next item
2697 continue;
2698 }
2699
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002700 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 }
2704 if ((state.orientation != draw[i].orientation) ||
2705 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 }
2708 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002709 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 }
2711 }
2712 }
2713 ++i;
2714 }
2715
2716 // find displays that were added
2717 // (ie: in current state but not in drawing state)
2718 for (size_t i = 0; i < cc; i++) {
2719 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2720 const DisplayDeviceState& state(curr[i]);
2721
Lloyd Pique542307f2018-10-19 13:24:08 -07002722 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 sp<IGraphicBufferProducer> producer;
2724 sp<IGraphicBufferProducer> bqProducer;
2725 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002726 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002727
Dominik Laskowski075d3172018-05-24 15:50:06 -07002728 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002729 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 // Virtual displays without a surface are dormant:
2731 // they have external state (layer stack, projection,
2732 // etc.) but no internal state (i.e. a DisplayDevice).
2733 if (state.surface != nullptr) {
2734 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002735 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 int width = 0;
2737 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2738 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2739 int height = 0;
2740 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2741 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2742 int intFormat = 0;
2743 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2744 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002745 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 displayId =
2748 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 }
2750
2751 // TODO: Plumb requested format back up to consumer
2752
2753 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002754 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002755 bqProducer, bqConsumer,
2756 state.displayName);
2757
2758 dispSurface = vds;
2759 producer = vds;
2760 }
2761 } else {
2762 ALOGE_IF(state.surface != nullptr,
2763 "adding a supported display, but rendering "
2764 "surface is provided (%p), ignoring it",
2765 state.surface.get());
2766
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 displayId = state.displayId;
2768 LOG_ALWAYS_FATAL_IF(!displayId);
2769 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002770 producer = bqProducer;
2771 }
2772
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002773 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002775 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002776 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002777 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002778 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002779 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002780 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 }
2782 }
2783 }
2784 }
2785 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002786
2787 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002788}
2789
Mathias Agopian87baae12012-07-31 12:38:26 -07002790void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002791{
Dan Stoza7dde5992015-05-22 09:51:44 -07002792 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002793 mCurrentState.traverseInZOrder([](Layer* layer) {
2794 layer->notifyAvailableFrames();
2795 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002796
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797 /*
2798 * Traversal of the children
2799 * (perform the transaction for each of them if needed)
2800 */
2801
Mathias Agopian3559b072012-08-15 13:46:03 -07002802 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002803 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002805 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806
2807 const uint32_t flags = layer->doTransaction(0);
2808 if (flags & Layer::eVisibleRegion)
2809 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002810
2811 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002812 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002813 }
Robert Carr2047fae2016-11-28 14:09:09 -08002814 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
2816
2817 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002818 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819 */
2820
Mathias Agopiane57f2922012-08-09 16:29:12 -07002821 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002822 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002823 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002826 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002827 // The transform hint might have changed for some layers
2828 // (either because a display has changed, or because a layer
2829 // as changed).
2830 //
2831 // Walk through all the layers in currentLayers,
2832 // and update their transform hint.
2833 //
2834 // If a layer is visible only on a single display, then that
2835 // display is used to calculate the hint, otherwise we use the
2836 // default display.
2837 //
2838 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2839 // the hint is set before we acquire a buffer from the surface texture.
2840 //
2841 // NOTE: layer transactions have taken place already, so we use their
2842 // drawing state. However, SurfaceFlinger's own transaction has not
2843 // happened yet, so we must use the current state layer list
2844 // (soon to become the drawing state list).
2845 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002846 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002847 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002848 bool first = true;
2849 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002850 // NOTE: we rely on the fact that layers are sorted by
2851 // layerStack first (so we don't have to traverse the list
2852 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002854 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002855 currentlayerStack = layerStack;
2856 // figure out if this layerstack is mirrored
2857 // (more than one display) if so, pick the default display,
2858 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002859 hintDisplay = nullptr;
2860 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002861 if (display->getCompositionDisplay()
2862 ->belongsInOutput(layer->getLayerStack(),
2863 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 if (hintDisplay) {
2865 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002866 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002869 }
2870 }
2871 }
2872 }
Chet Haase91d25932013-04-11 15:24:55 -07002873
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002874 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002875 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2876 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002877
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002878 // could be null when this layer is using a layerStack
2879 // that is not visible on any display. Also can occur at
2880 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002881 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002882 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002883
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002885 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002886 if (hintDisplay) {
2887 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002888 }
Robert Carr2047fae2016-11-28 14:09:09 -08002889
2890 first = false;
2891 });
Mathias Agopian84300952012-11-21 16:02:13 -08002892 }
2893
2894
Mathias Agopian3559b072012-08-15 13:46:03 -07002895 /*
2896 * Perform our own transaction if needed
2897 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002898
2899 if (mLayersAdded) {
2900 mLayersAdded = false;
2901 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002902 mVisibleRegionsDirty = true;
2903 }
2904
2905 // some layers might have been removed, so
2906 // we need to update the regions they're exposing.
2907 if (mLayersRemoved) {
2908 mLayersRemoved = false;
2909 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002910 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002911 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002912 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002913 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002914 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002915 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002916 }
Robert Carr2047fae2016-11-28 14:09:09 -08002917 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918 }
2919
Vishnu Nairec0ab382019-02-13 15:32:56 -08002920 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002922}
2923
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002924void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002925 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002926 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002927 return;
2928 }
2929
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002930 if (mVisibleRegionsDirty || mInputInfoChanged) {
2931 mInputInfoChanged = false;
2932 updateInputWindowInfo();
2933 }
2934
2935 executeInputWindowCommands();
2936}
2937
2938void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002939 Vector<InputWindowInfo> inputHandles;
2940
2941 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2942 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002943 // When calculating the screen bounds we ignore the transparent region since it may
2944 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002945 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002946 }
2947 });
2948 mInputFlinger->setInputWindows(inputHandles);
2949}
2950
Vishnu Nairec0ab382019-02-13 15:32:56 -08002951void SurfaceFlinger::commitInputWindowCommands() {
2952 mInputWindowCommands.merge(mPendingInputWindowCommands);
2953 mPendingInputWindowCommands.clear();
2954}
2955
chaviwfbe5d9c2018-12-26 12:23:37 -08002956void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002957 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2958 if (transferTouchFocusCommand.fromToken != nullptr &&
2959 transferTouchFocusCommand.toToken != nullptr &&
2960 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2961 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2962 transferTouchFocusCommand.toToken);
2963 }
2964 }
2965
2966 mInputWindowCommands.clear();
2967}
2968
Riley Andrews03414a12014-07-01 14:22:59 -07002969void SurfaceFlinger::updateCursorAsync()
2970{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002971 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002972 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002973 continue;
2974 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002975
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002976 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2977 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002978 }
2979 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002980}
2981
chaviw61626f22018-11-15 16:26:27 -08002982void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2983 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002984 bool ignored = false;
2985 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
chaviw61626f22018-11-15 16:26:27 -08002986 }
2987 layer->releasePendingBuffer(systemTime());
2988}
2989
Mathias Agopian4fec8732012-06-29 14:12:52 -07002990void SurfaceFlinger::commitTransaction()
2991{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002992 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002993 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002994 for (const auto& l : mLayersPendingRemoval) {
2995 recordBufferingStats(l->getName().string(),
2996 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002997
2998 // We need to release the HWC layers when the Layer is removed
2999 // from the current state otherwise the HWC layer just continues
3000 // showing at its last configured state until we eventually
3001 // abandon the buffer queue.
3002 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003003 l->destroyHwcLayersForAllDisplays();
3004 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003005 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003006 }
3007 mLayersPendingRemoval.clear();
3008 }
3009
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003010 // If this transaction is part of a window animation then the next frame
3011 // we composite should be considered an animation as well.
3012 mAnimCompositionPending = mAnimTransactionPending;
3013
Mathias Agopian4fec8732012-06-29 14:12:52 -07003014 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003015 // clear the "changed" flags in current state
3016 mCurrentState.colorMatrixChanged = false;
3017
Robert Carr1f0a16a2016-10-24 16:27:39 -07003018 mDrawingState.traverseInZOrder([](Layer* layer) {
3019 layer->commitChildList();
3020 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003021 mTransactionPending = false;
3022 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003023 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024}
3025
Lloyd Pique32cbe282018-10-19 13:09:22 -07003026void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003027 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003028 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003029 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003030
Lloyd Pique32cbe282018-10-19 13:09:22 -07003031 auto display = displayDevice->getCompositionDisplay();
3032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033 Region aboveOpaqueLayers;
3034 Region aboveCoveredLayers;
3035 Region dirty;
3036
Mathias Agopian87baae12012-07-31 12:38:26 -07003037 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038
Robert Carr2047fae2016-11-28 14:09:09 -08003039 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003040 // start with the whole surface at its current location
3041 const Layer::State& s(layer->getDrawingState());
3042
Jesse Hall01e29052013-02-19 16:13:35 -08003043 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003044 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003045 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003046 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003047
Mathias Agopianab028732010-03-16 16:41:46 -07003048 /*
3049 * opaqueRegion: area of a surface that is fully opaque.
3050 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003051 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003052
3053 /*
3054 * visibleRegion: area of a surface that is visible on screen
3055 * and not fully transparent. This is essentially the layer's
3056 * footprint minus the opaque regions above it.
3057 * Areas covered by a translucent surface are considered visible.
3058 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003060
3061 /*
3062 * coveredRegion: area of a surface that is covered by all
3063 * visible regions above it (which includes the translucent areas).
3064 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003066
Jesse Halla8026d22012-09-25 13:25:04 -07003067 /*
3068 * transparentRegion: area of a surface that is hinted to be completely
3069 * transparent. This is only used to tell when the layer has no visible
3070 * non-transparent regions and can be removed from the layer list. It
3071 * does not affect the visibleRegion of this layer or any layers
3072 * beneath it. The hint may not be correct if apps don't respect the
3073 * SurfaceView restrictions (which, sadly, some don't).
3074 */
3075 Region transparentRegion;
3076
Mathias Agopianab028732010-03-16 16:41:46 -07003077
3078 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003079 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003080 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003081 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003084 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003085 if (!visibleRegion.isEmpty()) {
3086 // Remove the transparent area from the visible region
3087 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003088 if (tr.preserveRects()) {
3089 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003090 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003091 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003092 // transformation too complex, can't do the
3093 // transparent region optimization.
3094 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003095 }
Mathias Agopianab028732010-03-16 16:41:46 -07003096 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097
Mathias Agopianab028732010-03-16 16:41:46 -07003098 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003099 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003100 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003101 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003102 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003103 // the opaque region is the layer's footprint
3104 opaqueRegion = visibleRegion;
3105 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106 }
3107 }
3108
Robert Carre5f4f692018-01-12 13:12:28 -08003109 if (visibleRegion.isEmpty()) {
3110 layer->clearVisibilityRegions();
3111 return;
3112 }
3113
Mathias Agopianab028732010-03-16 16:41:46 -07003114 // Clip the covered region to the visible region
3115 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3116
3117 // Update aboveCoveredLayers for next (lower) layer
3118 aboveCoveredLayers.orSelf(visibleRegion);
3119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 // subtract the opaque region covered by the layers above us
3121 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122
3123 // compute this layer's dirty region
3124 if (layer->contentDirty) {
3125 // we need to invalidate the whole region
3126 dirty = visibleRegion;
3127 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003128 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 layer->contentDirty = false;
3130 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003131 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003132 * the exposed region consists of two components:
3133 * 1) what's VISIBLE now and was COVERED before
3134 * 2) what's EXPOSED now less what was EXPOSED before
3135 *
3136 * note that (1) is conservative, we start with the whole
3137 * visible region but only keep what used to be covered by
3138 * something -- which mean it may have been exposed.
3139 *
3140 * (2) handles areas that were not covered by anything but got
3141 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003142 */
Mathias Agopianab028732010-03-16 16:41:46 -07003143 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144 const Region oldVisibleRegion = layer->visibleRegion;
3145 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003146 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3147 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 }
3149 dirty.subtractSelf(aboveOpaqueLayers);
3150
3151 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003152 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153
Mathias Agopianab028732010-03-16 16:41:46 -07003154 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003156
Jesse Halla8026d22012-09-25 13:25:04 -07003157 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 layer->setVisibleRegion(visibleRegion);
3159 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003160 layer->setVisibleNonTransparentRegion(
3161 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003162 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163
Mathias Agopian87baae12012-07-31 12:38:26 -07003164 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165}
3166
Chia-I Wuab0c3192017-08-01 11:29:00 -07003167void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003168 for (const auto& [token, displayDevice] : mDisplays) {
3169 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003170 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003171 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003172 }
3173 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003174}
3175
Daniel Solomon42d04562019-01-20 21:03:19 -08003176void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3177 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3178 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3179 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3180 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3181 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3182 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3183 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3184 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3185 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3186 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3187 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3188 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3189}
3190
Dan Stoza6b9454d2014-11-07 16:00:59 -08003191bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003193 ALOGV("handlePageFlip");
3194
Brian Andersond6927fb2016-07-23 23:37:30 -07003195 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196
Mathias Agopian4fec8732012-06-29 14:12:52 -07003197 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003198 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003199 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003200
3201 // Store the set of layers that need updates. This set must not change as
3202 // buffers are being latched, as this could result in a deadlock.
3203 // Example: Two producers share the same command stream and:
3204 // 1.) Layer 0 is latched
3205 // 2.) Layer 0 gets a new frame
3206 // 2.) Layer 1 gets a new frame
3207 // 3.) Layer 1 is latched.
3208 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3209 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003210 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003211 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003212 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003213 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003214 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003215 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003216 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003217 } else {
3218 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003219 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003220 } else {
3221 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003222 }
Robert Carr2047fae2016-11-28 14:09:09 -08003223 });
3224
Lloyd Piquef2c79392018-12-20 16:23:33 -08003225 if (!mLayersWithQueuedFrames.empty()) {
3226 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3227 // writes to Layer current state. See also b/119481871
3228 Mutex::Autolock lock(mStateLock);
3229
3230 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003231 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3232 mLayersPendingRefresh.push_back(layer);
3233 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003234 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003235 if (layer->isBufferLatched()) {
3236 newDataLatched = true;
3237 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003238 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003239 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003240
Alec Mouri86770e52018-09-24 22:40:58 +00003241 // Clear the renderengine fence here...
3242 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3243 // clear instead of sp::clear.
3244 getBE().flushFence = Fence::NO_FENCE;
3245
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003246 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003247
3248 // If we will need to wake up at some time in the future to deal with a
3249 // queued frame that shouldn't be displayed during this vsync period, wake
3250 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003251 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003252 signalLayerUpdate();
3253 }
3254
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003255 // enter boot animation on first buffer latch
3256 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3257 ALOGI("Enter boot animation");
3258 mBootStage = BootStage::BOOTANIMATION;
3259 }
3260
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003262 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263}
3264
Mathias Agopianad456f92011-01-13 17:53:01 -08003265void SurfaceFlinger::invalidateHwcGeometry()
3266{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003267 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003268}
3269
Lloyd Pique32cbe282018-10-19 13:09:22 -07003270void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003271 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003272 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003273 // We only need to actually compose the display if:
3274 // 1) It is being handled by hardware composer, which may need this to
3275 // keep its virtual display state machine in sync, or
3276 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003277 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003278 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003279 return;
3280 }
3281
Dan Stoza9e56aa02015-11-02 13:00:03 -08003282 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003283 base::unique_fd readyFence;
3284 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003285
3286 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003287 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288}
3289
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003290bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3291 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003292 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003293 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003294
Lloyd Pique32cbe282018-10-19 13:09:22 -07003295 auto display = displayDevice->getCompositionDisplay();
3296 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003297 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003298
3299 const Region bounds(displayState.bounds);
3300 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003301 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003302 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003303
Peiyong Lind3788632018-09-18 16:01:31 -07003304 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003305 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003306
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003307 renderengine::DisplaySettings clientCompositionDisplay;
3308 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3309 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003310
Dan Stoza9e56aa02015-11-02 13:00:03 -08003311 if (hasClientComposition) {
3312 ALOGV("hasClientComposition");
3313
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003314 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003315
3316 if (buf == nullptr) {
3317 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3318 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003319 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003320 return false;
3321 }
3322
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003323 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3324 clientCompositionDisplay.clip = displayState.scissor;
3325 const ui::Transform& displayTransform = displayState.transform;
3326 mat4 m;
3327 m[0][0] = displayTransform[0][0];
3328 m[0][1] = displayTransform[0][1];
3329 m[0][3] = displayTransform[0][2];
3330 m[1][0] = displayTransform[1][0];
3331 m[1][1] = displayTransform[1][1];
3332 m[1][3] = displayTransform[1][2];
3333 m[3][0] = displayTransform[2][0];
3334 m[3][1] = displayTransform[2][1];
3335 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003336
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003337 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003338
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003339 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003340 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003341 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003342 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003343 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003344 clientCompositionDisplay.outputDataspace = outputDataspace;
3345 clientCompositionDisplay.maxLuminance =
3346 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003347
Lloyd Pique441d5042018-10-18 16:49:51 -07003348 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003349 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003350 getHwComposer()
3351 .hasDisplayCapability(displayId,
3352 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003353
Peiyong Lind3788632018-09-18 16:01:31 -07003354 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003355 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3356 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003357 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003358 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003359 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003360
Mathias Agopian85d751c2012-08-29 16:59:24 -07003361 /*
3362 * and then, render the layers targeted at the framebuffer
3363 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003364
Dan Stoza9e56aa02015-11-02 13:00:03 -08003365 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003366 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003367 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003368 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003369 const Region viewportRegion(displayState.viewport);
3370 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003371 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003372 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003373 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003374 switch (layer->getCompositionType(displayDevice)) {
3375 case Hwc2::IComposerClient::Composition::CURSOR:
3376 case Hwc2::IComposerClient::Composition::DEVICE:
3377 case Hwc2::IComposerClient::Composition::SIDEBAND:
3378 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003379 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003380 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003381 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003382 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003383 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003384 // never clear the very first layer since we're
3385 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003386 renderengine::LayerSettings layerSettings;
3387 Region dummyRegion;
3388 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3389 layerSettings);
3390
3391 if (prepared) {
3392 layerSettings.source.buffer.buffer = nullptr;
3393 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3394 layerSettings.alpha = half(0.0);
3395 layerSettings.disableBlending = true;
3396 clientCompositionLayers.push_back(layerSettings);
3397 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003398 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003399 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003400 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003401 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003402 renderengine::LayerSettings layerSettings;
3403 bool prepared =
3404 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3405 if (prepared) {
3406 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003407 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003408 break;
3409 }
3410 default:
3411 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003412 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003413 } else {
3414 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003415 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003416 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003417 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003418
Alec Mouri820c7402019-01-23 13:02:39 -08003419 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003420 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003421 clientCompositionDisplay.clearRegion = clearRegion;
3422 if (!debugRegion.isEmpty()) {
3423 Region::const_iterator it = debugRegion.begin();
3424 Region::const_iterator end = debugRegion.end();
3425 while (it != end) {
3426 const Rect& rect = *it++;
3427 renderengine::LayerSettings layerSettings;
3428 layerSettings.source.buffer.buffer = nullptr;
3429 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3430 layerSettings.geometry.boundaries = rect.toFloatRect();
3431 layerSettings.alpha = half(1.0);
3432 clientCompositionLayers.push_back(layerSettings);
3433 }
3434 }
3435 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3436 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003437 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003438 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003439}
3440
Chia-I Wu28e3a252018-09-07 12:05:02 -07003441void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003442 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003443 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003444}
3445
Dan Stoza7d89d062015-04-30 13:29:25 -07003446status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003447 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003448 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003449 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003450 const sp<Layer>& parent,
3451 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003452{
Dan Stoza7d89d062015-04-30 13:29:25 -07003453 // add this layer to the current state list
3454 {
3455 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003456 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003457 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3458 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003459 return NO_MEMORY;
3460 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003461 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003462 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003463 } else if (parent == nullptr) {
3464 lbc->onRemovedFromCurrentState();
3465 } else if (parent->isRemovedFromCurrentState()) {
3466 parent->addChild(lbc);
3467 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003468 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003469 parent->addChild(lbc);
3470 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003471
Yiwei Zhang243b3782018-05-15 17:40:04 -07003472 if (gbc != nullptr) {
3473 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3474 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3475 mMaxGraphicBufferProducerListSize,
3476 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3477 mGraphicBufferProducerList.size(),
3478 mMaxGraphicBufferProducerListSize, mNumLayers);
3479 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003480 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003481 }
3482
Mathias Agopian96f08192010-06-02 23:28:45 -07003483 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003484 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003485
Dan Stoza7d89d062015-04-30 13:29:25 -07003486 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003487}
3488
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003489uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003490 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003491}
3492
Mathias Agopian3f844832013-08-07 21:24:32 -07003493uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003494 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495}
3496
Mathias Agopian3f844832013-08-07 21:24:32 -07003497uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003498 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003499}
3500
3501uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003502 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003503 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003504 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003506 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003507 }
3508 return old;
3509}
3510
Marissa Wall713b63f2018-10-17 15:42:43 -07003511bool SurfaceFlinger::flushTransactionQueues() {
3512 Mutex::Autolock _l(mStateLock);
3513 auto it = mTransactionQueues.begin();
3514 while (it != mTransactionQueues.end()) {
3515 auto& [applyToken, transactionQueue] = *it;
3516
3517 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003518 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3519 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003520 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003521 break;
3522 }
Robert Carr14167e02019-02-13 13:50:55 -08003523 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003524 transactionQueue.pop();
3525 }
3526
3527 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3528 }
3529 return mTransactionQueues.empty();
3530}
3531
chaviwca27f252018-02-06 16:46:39 -08003532bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3533 for (const ComposerState& state : states) {
3534 // Here we need to check that the interface we're given is indeed
3535 // one of our own. A malicious client could give us a nullptr
3536 // IInterface, or one of its own or even one of our own but a
3537 // different type. All these situations would cause us to crash.
3538 if (state.client == nullptr) {
3539 return true;
3540 }
3541
3542 sp<IBinder> binder = IInterface::asBinder(state.client);
3543 if (binder == nullptr) {
3544 return true;
3545 }
3546
3547 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3548 return true;
3549 }
3550 }
3551 return false;
3552}
3553
Marissa Wall17b4e452018-12-26 16:32:34 -08003554bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3555 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003556 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003557 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3558 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3559 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3560 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3561 return false;
3562 }
3563
Marissa Wall713b63f2018-10-17 15:42:43 -07003564 for (const ComposerState& state : states) {
3565 const layer_state_t& s = state.state;
3566 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3567 continue;
3568 }
3569 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003570 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003571 }
3572 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003573 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003574}
3575
3576void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3577 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003578 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003579 const InputWindowCommands& inputWindowCommands,
3580 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003581 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003582
3583 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3584
Mathias Agopian698c0872011-06-28 19:09:31 -07003585 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003586
chaviwca27f252018-02-06 16:46:39 -08003587 if (containsAnyInvalidClientState(states)) {
3588 return;
3589 }
3590
Marissa Wall713b63f2018-10-17 15:42:43 -07003591 // If its TransactionQueue already has a pending TransactionState or if it is pending
3592 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003593 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003594 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3595 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003596 setTransactionFlags(eTransactionNeeded);
3597 return;
3598 }
3599
Robert Carr14167e02019-02-13 13:50:55 -08003600 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003601}
3602
3603void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003604 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003605 const InputWindowCommands& inputWindowCommands,
3606 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003607 uint32_t transactionFlags = 0;
3608
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003609 if (flags & eAnimation) {
3610 // For window updates that are part of an animation we must wait for
3611 // previous animation "frames" to be handled.
3612 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003613 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003614 if (CC_UNLIKELY(err != NO_ERROR)) {
3615 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003616 // caller after a few seconds.
3617 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3618 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003619 mAnimTransactionPending = false;
3620 break;
3621 }
3622 }
3623 }
3624
chaviwca27f252018-02-06 16:46:39 -08003625 for (const DisplayState& display : displays) {
3626 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003627 }
3628
Marissa Walle2ffb422018-10-12 11:33:52 -07003629 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003630 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003631 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003632 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003633 // If the state doesn't require a traversal and there are callbacks, send them now
3634 if (!(clientStateFlags & eTraversalNeeded)) {
3635 mTransactionCompletedThread.sendCallbacks();
3636 }
3637 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003638
chaviw273171b2018-12-26 11:46:30 -08003639 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3640
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003641 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3642 // anyway. This can be used as a flush mechanism for previous async transactions.
3643 // Empty animation transaction can be used to simulate back-pressure, so also force a
3644 // transaction for empty animation transactions.
3645 if (transactionFlags == 0 &&
3646 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003647 transactionFlags = eTransactionNeeded;
3648 }
3649
Mathias Agopian386aa982011-11-07 21:58:03 -08003650 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003651 if (mInterceptor->isEnabled()) {
3652 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003653 }
Irvel468051e2016-06-13 16:44:44 -07003654
Mathias Agopian386aa982011-11-07 21:58:03 -08003655 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003656 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3657 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003658 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003659
3660 // if this is a synchronous transaction, wait for it to take effect
3661 // before returning.
3662 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003663 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003664 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003665 if (flags & eAnimation) {
3666 mAnimTransactionPending = true;
3667 }
3668 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003669 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3670 if (CC_UNLIKELY(err != NO_ERROR)) {
3671 // just in case something goes wrong in SF, return to the
3672 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003673 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3674 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 break;
3676 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003677 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003678 }
3679}
3680
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003681uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3682 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3683 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003684
Mathias Agopiane57f2922012-08-09 16:29:12 -07003685 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003686 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3687
3688 const uint32_t what = s.what;
3689 if (what & DisplayState::eSurfaceChanged) {
3690 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3691 state.surface = s.surface;
3692 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003693 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003694 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003695 if (what & DisplayState::eLayerStackChanged) {
3696 if (state.layerStack != s.layerStack) {
3697 state.layerStack = s.layerStack;
3698 flags |= eDisplayTransactionNeeded;
3699 }
3700 }
3701 if (what & DisplayState::eDisplayProjectionChanged) {
3702 if (state.orientation != s.orientation) {
3703 state.orientation = s.orientation;
3704 flags |= eDisplayTransactionNeeded;
3705 }
3706 if (state.frame != s.frame) {
3707 state.frame = s.frame;
3708 flags |= eDisplayTransactionNeeded;
3709 }
3710 if (state.viewport != s.viewport) {
3711 state.viewport = s.viewport;
3712 flags |= eDisplayTransactionNeeded;
3713 }
3714 }
3715 if (what & DisplayState::eDisplaySizeChanged) {
3716 if (state.width != s.width) {
3717 state.width = s.width;
3718 flags |= eDisplayTransactionNeeded;
3719 }
3720 if (state.height != s.height) {
3721 state.height = s.height;
3722 flags |= eDisplayTransactionNeeded;
3723 }
3724 }
3725
Mathias Agopiane57f2922012-08-09 16:29:12 -07003726 return flags;
3727}
3728
Robert Carr14167e02019-02-13 13:50:55 -08003729bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003730 IPCThreadState* ipc = IPCThreadState::self();
3731 const int pid = ipc->getCallingPid();
3732 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003733 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003734 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003735 return false;
3736 }
3737 return true;
3738}
3739
Robert Carr14167e02019-02-13 13:50:55 -08003740uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3741 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003742 const layer_state_t& s = composerState.state;
3743 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3744
Mathias Agopian13127d82013-03-05 17:47:11 -08003745 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003746 if (layer == nullptr) {
3747 return 0;
3748 }
3749
chaviw8b3871a2017-11-01 17:41:01 -07003750 uint32_t flags = 0;
3751
Garfield Tan8a3083e2018-12-03 13:21:07 -08003752 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003753 bool geometryAppliesWithResize =
3754 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003755
3756 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3757 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003758 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003759 layer->pushPendingState();
3760 }
3761
chaviw8b3871a2017-11-01 17:41:01 -07003762 if (what & layer_state_t::ePositionChanged) {
3763 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3764 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 }
chaviw8b3871a2017-11-01 17:41:01 -07003766 }
3767 if (what & layer_state_t::eLayerChanged) {
3768 // NOTE: index needs to be calculated before we update the state
3769 const auto& p = layer->getParent();
3770 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003771 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003772 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773 mCurrentState.layersSortedByZ.removeAt(idx);
3774 mCurrentState.layersSortedByZ.add(layer);
3775 // we need traversal (state changed)
3776 // AND transaction (list changed)
3777 flags |= eTransactionNeeded|eTraversalNeeded;
3778 }
chaviw8b3871a2017-11-01 17:41:01 -07003779 } else {
3780 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003781 flags |= eTransactionNeeded|eTraversalNeeded;
3782 }
3783 }
chaviw8b3871a2017-11-01 17:41:01 -07003784 }
3785 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003786 // NOTE: index needs to be calculated before we update the state
3787 const auto& p = layer->getParent();
3788 if (p == nullptr) {
3789 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3790 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3791 mCurrentState.layersSortedByZ.removeAt(idx);
3792 mCurrentState.layersSortedByZ.add(layer);
3793 // we need traversal (state changed)
3794 // AND transaction (list changed)
3795 flags |= eTransactionNeeded|eTraversalNeeded;
3796 }
3797 } else {
3798 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3799 flags |= eTransactionNeeded|eTraversalNeeded;
3800 }
chaviw8b3871a2017-11-01 17:41:01 -07003801 }
3802 }
3803 if (what & layer_state_t::eSizeChanged) {
3804 if (layer->setSize(s.w, s.h)) {
3805 flags |= eTraversalNeeded;
3806 }
3807 }
3808 if (what & layer_state_t::eAlphaChanged) {
3809 if (layer->setAlpha(s.alpha))
3810 flags |= eTraversalNeeded;
3811 }
3812 if (what & layer_state_t::eColorChanged) {
3813 if (layer->setColor(s.color))
3814 flags |= eTraversalNeeded;
3815 }
Peiyong Lind3788632018-09-18 16:01:31 -07003816 if (what & layer_state_t::eColorTransformChanged) {
3817 if (layer->setColorTransform(s.colorTransform)) {
3818 flags |= eTraversalNeeded;
3819 }
3820 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003821 if (what & layer_state_t::eBackgroundColorChanged) {
3822 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3823 flags |= eTraversalNeeded;
3824 }
3825 }
chaviw8b3871a2017-11-01 17:41:01 -07003826 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003827 // TODO: b/109894387
3828 //
3829 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3830 // rotation. To see the problem observe that if we have a square parent, and a child
3831 // of the same size, then we rotate the child 45 degrees around it's center, the child
3832 // must now be cropped to a non rectangular 8 sided region.
3833 //
3834 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3835 // private API, and the WindowManager only uses rotation in one case, which is on a top
3836 // level layer in which cropping is not an issue.
3837 //
3838 // However given that abuse of rotation matrices could lead to surfaces extending outside
3839 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3840 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3841 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003842 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003843 flags |= eTraversalNeeded;
3844 }
3845 if (what & layer_state_t::eTransparentRegionChanged) {
3846 if (layer->setTransparentRegionHint(s.transparentRegion))
3847 flags |= eTraversalNeeded;
3848 }
3849 if (what & layer_state_t::eFlagsChanged) {
3850 if (layer->setFlags(s.flags, s.mask))
3851 flags |= eTraversalNeeded;
3852 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003853 if (what & layer_state_t::eCropChanged_legacy) {
3854 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003855 flags |= eTraversalNeeded;
3856 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003857 if (what & layer_state_t::eCornerRadiusChanged) {
3858 if (layer->setCornerRadius(s.cornerRadius))
3859 flags |= eTraversalNeeded;
3860 }
chaviw8b3871a2017-11-01 17:41:01 -07003861 if (what & layer_state_t::eLayerStackChanged) {
3862 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3863 // We only allow setting layer stacks for top level layers,
3864 // everything else inherits layer stack from its parent.
3865 if (layer->hasParent()) {
3866 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3867 layer->getName().string());
3868 } else if (idx < 0) {
3869 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3870 "that also does not appear in the top level layer list. Something"
3871 " has gone wrong.", layer->getName().string());
3872 } else if (layer->setLayerStack(s.layerStack)) {
3873 mCurrentState.layersSortedByZ.removeAt(idx);
3874 mCurrentState.layersSortedByZ.add(layer);
3875 // we need traversal (state changed)
3876 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003877 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003878 }
3879 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003880 if (what & layer_state_t::eDeferTransaction_legacy) {
3881 if (s.barrierHandle_legacy != nullptr) {
3882 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3883 } else if (s.barrierGbp_legacy != nullptr) {
3884 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003885 if (authenticateSurfaceTextureLocked(gbp)) {
3886 const auto& otherLayer =
3887 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003888 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003889 } else {
3890 ALOGE("Attempt to defer transaction to to an"
3891 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003892 }
3893 }
chaviw8b3871a2017-11-01 17:41:01 -07003894 // We don't trigger a traversal here because if no other state is
3895 // changed, we don't want this to cause any more work
3896 }
3897 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003898 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003899 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003900 if (!hadParent) {
3901 mCurrentState.layersSortedByZ.remove(layer);
3902 }
chaviw8b3871a2017-11-01 17:41:01 -07003903 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003904 }
chaviw8b3871a2017-11-01 17:41:01 -07003905 }
3906 if (what & layer_state_t::eReparentChildren) {
3907 if (layer->reparentChildren(s.reparentHandle)) {
3908 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003909 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003910 }
chaviw8b3871a2017-11-01 17:41:01 -07003911 if (what & layer_state_t::eDetachChildren) {
3912 layer->detachChildren();
3913 }
3914 if (what & layer_state_t::eOverrideScalingModeChanged) {
3915 layer->setOverrideScalingMode(s.overrideScalingMode);
3916 // We don't trigger a traversal here because if no other state is
3917 // changed, we don't want this to cause any more work
3918 }
Marissa Wall61c58622018-07-18 10:12:20 -07003919 if (what & layer_state_t::eTransformChanged) {
3920 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3921 }
3922 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3923 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3924 flags |= eTraversalNeeded;
3925 }
3926 if (what & layer_state_t::eCropChanged) {
3927 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3928 }
Marissa Wall861616d2018-10-22 12:52:23 -07003929 if (what & layer_state_t::eFrameChanged) {
3930 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3931 }
Marissa Wall61c58622018-07-18 10:12:20 -07003932 if (what & layer_state_t::eAcquireFenceChanged) {
3933 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3934 }
3935 if (what & layer_state_t::eDataspaceChanged) {
3936 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3937 }
3938 if (what & layer_state_t::eHdrMetadataChanged) {
3939 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3940 }
3941 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3942 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3943 }
3944 if (what & layer_state_t::eApiChanged) {
3945 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3946 }
3947 if (what & layer_state_t::eSidebandStreamChanged) {
3948 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3949 }
Robert Carr720e5062018-07-30 17:45:14 -07003950 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003951 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3952 layer->setInputInfo(s.inputInfo);
3953 flags |= eTraversalNeeded;
3954 } else {
3955 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3956 }
Robert Carr720e5062018-07-30 17:45:14 -07003957 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003958 if (what & layer_state_t::eMetadataChanged) {
3959 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3960 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003961 std::vector<sp<CallbackHandle>> callbackHandles;
3962 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3963 mTransactionCompletedThread.run();
3964 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3965 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3966 }
3967 }
Marissa Wall73411622019-01-25 10:45:41 -08003968
3969 if (what & layer_state_t::eBufferChanged) {
3970 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3971 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3972 s.buffer);
3973 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003974 if (what & layer_state_t::eCachedBufferChanged) {
3975 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003976 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3977 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003978 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3979 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003980 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3981 // Do not put anything that updates layer state or modifies flags after
3982 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003983 return flags;
3984}
3985
chaviw273171b2018-12-26 11:46:30 -08003986uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3987 uint32_t flags = 0;
3988 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3989 flags |= eTraversalNeeded;
3990 }
3991
Vishnu Nairec0ab382019-02-13 15:32:56 -08003992 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003993 return flags;
3994}
3995
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003996status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3997 uint32_t h, PixelFormat format, uint32_t flags,
3998 LayerMetadata metadata, sp<IBinder>* handle,
3999 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004000 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004001 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004002 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004003 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004004 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004005
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004006 status_t result = NO_ERROR;
4007
4008 sp<Layer> layer;
4009
Cody Northropbc755282017-03-31 12:00:08 -06004010 String8 uniqueName = getUniqueLayerName(name);
4011
Mathias Agopian3165cc22012-08-08 19:42:09 -07004012 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004013 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004014 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4015 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004016
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004017 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004018 case ISurfaceComposerClient::eFXSurfaceBufferState:
4019 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4020 break;
chaviw13fdc492017-06-27 12:40:18 -07004021 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004022 // check if buffer size is set for color layer.
4023 if (w > 0 || h > 0) {
4024 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4025 int(w), int(h));
4026 return BAD_VALUE;
4027 }
4028
chaviw13fdc492017-06-27 12:40:18 -07004029 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004030 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004031 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004032 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004033 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004034 // check if buffer size is set for container layer.
4035 if (w > 0 || h > 0) {
4036 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4037 int(w), int(h));
4038 return BAD_VALUE;
4039 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004040 result = createContainerLayer(client,
4041 uniqueName, w, h, flags,
4042 handle, &layer);
4043 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044 default:
4045 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004046 break;
4047 }
4048
Dan Stoza7d89d062015-04-30 13:29:25 -07004049 if (result != NO_ERROR) {
4050 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004051 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004052
Chia-I Wuab0c3192017-08-01 11:29:00 -07004053 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4054 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004055 if (metadata.has(METADATA_WINDOW_TYPE)) {
4056 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4057 if (windowType == 441731) {
4058 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4059 layer->setPrimaryDisplayOnly();
4060 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004061 }
4062
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004063 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004064
Robert Carrb89ea9d2018-12-10 13:01:14 -08004065 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4066 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4067 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004068 if (result != NO_ERROR) {
4069 return result;
4070 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004071 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004072
4073 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004074 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004075}
4076
Cody Northropbc755282017-03-31 12:00:08 -06004077String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4078{
4079 bool matchFound = true;
4080 uint32_t dupeCounter = 0;
4081
4082 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4083 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4084
Dan Stoza436ccf32018-06-21 12:10:12 -07004085 // Grab the state lock since we're accessing mCurrentState
4086 Mutex::Autolock lock(mStateLock);
4087
Cody Northropbc755282017-03-31 12:00:08 -06004088 // Loop over layers until we're sure there is no matching name
4089 while (matchFound) {
4090 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004091 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004092 if (layer->getName() == uniqueName) {
4093 matchFound = true;
4094 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4095 }
4096 });
4097 }
4098
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004099 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4100 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004101
4102 return uniqueName;
4103}
4104
Marissa Wallfd668622018-05-10 10:21:13 -07004105status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4106 uint32_t w, uint32_t h, uint32_t flags,
4107 PixelFormat& format, sp<IBinder>* handle,
4108 sp<IGraphicBufferProducer>* gbp,
4109 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004110 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004111 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004112 case PIXEL_FORMAT_TRANSPARENT:
4113 case PIXEL_FORMAT_TRANSLUCENT:
4114 format = PIXEL_FORMAT_RGBA_8888;
4115 break;
4116 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004117 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118 break;
4119 }
4120
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004121 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004122 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004123 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004124 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004125 *handle = layer->getHandle();
4126 *gbp = layer->getProducer();
4127 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004128 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004129
Marissa Wallfd668622018-05-10 10:21:13 -07004130 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004131 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004132}
4133
Marissa Wall61c58622018-07-18 10:12:20 -07004134status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4135 uint32_t w, uint32_t h, uint32_t flags,
4136 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004137 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004138 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004139 *handle = layer->getHandle();
4140 *outLayer = layer;
4141
4142 return NO_ERROR;
4143}
4144
chaviw13fdc492017-06-27 12:40:18 -07004145status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004146 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004147 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004148{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004149 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004150 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004151 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004152}
4153
Robert Carr6b3f6c52018-08-13 13:05:17 -07004154status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4155 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4156 sp<IBinder>* handle, sp<Layer>* outLayer)
4157{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004158 *outLayer =
4159 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004160 *handle = (*outLayer)->getHandle();
4161 return NO_ERROR;
4162}
4163
4164
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004165void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004166 mLayersPendingRemoval.add(layer);
4167 mLayersRemoved = true;
4168 setTransactionFlags(eTransactionNeeded);
4169}
4170
Robert Carr695d5282018-12-18 15:27:58 -08004171void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004172{
Robert Carr2e102c92018-10-23 12:11:15 -07004173 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004174 // If a layer has a parent, we allow it to out-live it's handle
4175 // with the idea that the parent holds a reference and will eventually
4176 // be cleaned up. However no one cleans up the top-level so we do so
4177 // here.
4178 if (layer->getParent() == nullptr) {
4179 mCurrentState.layersSortedByZ.remove(layer);
4180 }
4181 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004182 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004183}
4184
Mathias Agopianb60314a2012-04-10 22:09:54 -07004185// ---------------------------------------------------------------------------
4186
Andy McFadden13a082e2012-08-24 10:16:42 -07004187void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004188 const auto display = getDefaultDisplayDeviceLocked();
4189 if (!display) return;
4190
4191 const sp<IBinder> token = display->getDisplayToken().promote();
4192 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004193
Jesse Hall01e29052013-02-19 16:13:35 -08004194 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004195 Vector<ComposerState> state;
4196 Vector<DisplayState> displays;
4197 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004198 d.what = DisplayState::eDisplayProjectionChanged |
4199 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004200 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004201 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004202 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004203 d.frame.makeInvalid();
4204 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004205 d.width = 0;
4206 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004207 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004208 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004209
Dominik Laskowskie9774092018-12-11 10:04:24 -08004210 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004211
Dominik Laskowski83b88212018-12-11 13:34:06 -08004212 const nsecs_t vsyncPeriod = getVsyncPeriod();
4213 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004214
Brian Andersond0010582017-03-07 13:20:31 -08004215 // Use phase of 0 since phase is not known.
4216 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004217 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004218 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004219}
4220
4221void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004222 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004223 postMessageAsync(
4224 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004225}
4226
Dominik Laskowskie9774092018-12-11 10:04:24 -08004227void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004228 if (display->isVirtual()) {
4229 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004230 return;
4231 }
4232
Dominik Laskowski075d3172018-05-24 15:50:06 -07004233 const auto displayId = display->getId();
4234 LOG_ALWAYS_FATAL_IF(!displayId);
4235
Dominik Laskowski34157762018-10-31 13:07:19 -07004236 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237
4238 int currentMode = display->getPowerMode();
4239 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004240 return;
4241 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004243 display->setPowerMode(mode);
4244
Lloyd Pique4dccc412018-01-22 17:21:36 -08004245 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004246 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004247 }
4248
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004249 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004250 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004251 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004253 mScheduler->onScreenAcquired(mAppConnectionHandle);
4254 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004256
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004257 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004258 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004259 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004260
4261 struct sched_param param = {0};
4262 param.sched_priority = 1;
4263 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4264 ALOGW("Couldn't set SCHED_FIFO on display on");
4265 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004266 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004267 // Turn off the display
4268 struct sched_param param = {0};
4269 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4270 ALOGW("Couldn't set SCHED_OTHER on display off");
4271 }
4272
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004273 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004274 mScheduler->disableHardwareVsync(true);
4275 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004276 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004277
Dominik Laskowski075d3172018-05-24 15:50:06 -07004278 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004279 mVisibleRegionsDirty = true;
4280 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004281 } else if (mode == HWC_POWER_MODE_DOZE ||
4282 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004283 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004284 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004285 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004286 mScheduler->onScreenAcquired(mAppConnectionHandle);
4287 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004288 }
4289 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4290 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004292 mScheduler->disableHardwareVsync(true);
4293 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004294 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004295 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004296 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004297 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004298 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004299 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004301 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004302 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004303 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004304 // Update refresh rate stats.
4305 mRefreshRateStats->setPowerMode(mode);
4306 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004307 }
4308
Dominik Laskowski34157762018-10-31 13:07:19 -07004309 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004310}
4311
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004312void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004313 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004314 const auto display = getDisplayDevice(displayToken);
4315 if (!display) {
4316 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4317 displayToken.get());
4318 } else if (display->isVirtual()) {
4319 ALOGW("Attempt to set power mode %d for virtual display", mode);
4320 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004321 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004322 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004323 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004324}
4325
4326// ---------------------------------------------------------------------------
4327
Dominik Laskowskic2867142019-01-21 11:33:38 -08004328status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4329 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004330 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004331
Mathias Agopianbd115332013-04-18 16:41:04 -07004332 IPCThreadState* ipc = IPCThreadState::self();
4333 const int pid = ipc->getCallingPid();
4334 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004335
Mathias Agopianbd115332013-04-18 16:41:04 -07004336 if ((uid != AID_SHELL) &&
4337 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004338 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4339 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004340 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004341 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004342 // (this would indicate SF is stuck, but we want to be able to
4343 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004344 status_t err = mStateLock.timedLock(s2ns(1));
4345 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004346 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004347 StringAppendF(&result,
4348 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4349 "(no locks held)\n",
4350 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004351 }
4352
Dominik Laskowskic2867142019-01-21 11:33:38 -08004353 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004354
Dominik Laskowskic2867142019-01-21 11:33:38 -08004355 static const std::unordered_map<std::string, Dumper> dumpers = {
4356 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4357 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4358 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004359 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004360 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004361 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004362 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4363 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004364 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4365 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4366 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4367 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4368 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4369 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004370 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004371 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4372 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004373
Dominik Laskowskic2867142019-01-21 11:33:38 -08004374 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004375
Dominik Laskowskic2867142019-01-21 11:33:38 -08004376 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4377 (it->second)(args, asProto, result);
4378 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004379 if (asProto) {
4380 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4381 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4382 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004383 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004384 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004385 }
4386
Mathias Agopian9795c422009-08-26 16:36:26 -07004387 if (locked) {
4388 mStateLock.unlock();
4389 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004390 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004391 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 return NO_ERROR;
4393}
4394
Dominik Laskowskic2867142019-01-21 11:33:38 -08004395void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004396 mCurrentState.traverseInZOrder(
4397 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004398}
4399
Dominik Laskowskic2867142019-01-21 11:33:38 -08004400void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004401 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004402
Dominik Laskowskic2867142019-01-21 11:33:38 -08004403 if (args.size() > 1) {
4404 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004405 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004406 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004407 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004408 }
Robert Carr2047fae2016-11-28 14:09:09 -08004409 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004410 } else {
4411 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412 }
4413}
4414
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004416 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004418 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004419 }
Robert Carr2047fae2016-11-28 14:09:09 -08004420 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004421
Svetoslavd85084b2014-03-20 10:28:31 -07004422 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004423}
4424
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4426 mTimeStats->parseArgs(asProto, args, result);
4427}
4428
Jamie Gennis6547ff42013-07-16 20:12:42 -07004429// This should only be called from the main thread. Otherwise it would need
4430// the lock and should use mCurrentState rather than mDrawingState.
4431void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004432 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004433 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004434 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004435
4436 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4437}
4438
Yiwei Zhang5434a782018-12-05 18:06:32 -08004439void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004440 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004441
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004442 if (isLayerTripleBufferingDisabled())
4443 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4446 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4447 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4448 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4449 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4450 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004451 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004452}
4453
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004454void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004455 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004456 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004457 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004458 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004459
Ana Krulecc2870422019-01-29 19:00:58 -08004460 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n\n", mUse90Hz ? "on" : "off");
4461 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004462}
4463
Yiwei Zhang5434a782018-12-05 18:06:32 -08004464void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4465 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004466 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4467 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004468 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004469 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004470 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004471 }
David Sodman4a36e932017-11-07 14:29:47 -08004472 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004473 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004474 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4476 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004477}
4478
Dan Stozae77c7662016-05-13 11:37:28 -07004479void SurfaceFlinger::recordBufferingStats(const char* layerName,
4480 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004481 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4482 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004483 for (const auto& segment : history) {
4484 if (!segment.usedThirdBuffer) {
4485 stats.twoBufferTime += segment.totalTime;
4486 }
4487 if (segment.occupancyAverage < 1.0f) {
4488 stats.doubleBufferedTime += segment.totalTime;
4489 } else if (segment.occupancyAverage < 2.0f) {
4490 stats.tripleBufferedTime += segment.totalTime;
4491 }
4492 ++stats.numSegments;
4493 stats.totalTime += segment.totalTime;
4494 }
4495}
4496
Yiwei Zhang5434a782018-12-05 18:06:32 -08004497void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4498 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004499
4500 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4501 const size_t count = currentLayers.size();
4502 for (size_t i=0 ; i<count ; i++) {
4503 currentLayers[i]->dumpFrameEvents(result);
4504 }
4505}
4506
Yiwei Zhang5434a782018-12-05 18:06:32 -08004507void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004508 result.append("Buffering stats:\n");
4509 result.append(" [Layer name] <Active time> <Two buffer> "
4510 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004511 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004512 typedef std::tuple<std::string, float, float, float> BufferTuple;
4513 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004514 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004515 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004516 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004517 if (stats.numSegments == 0) {
4518 continue;
4519 }
4520 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4521 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4522 stats.totalTime;
4523 float doubleBufferRatio = static_cast<float>(
4524 stats.doubleBufferedTime) / stats.totalTime;
4525 float tripleBufferRatio = static_cast<float>(
4526 stats.tripleBufferedTime) / stats.totalTime;
4527 sorted.insert({activeTime, {name, twoBufferRatio,
4528 doubleBufferRatio, tripleBufferRatio}});
4529 }
4530 for (const auto& sortedPair : sorted) {
4531 float activeTime = sortedPair.first;
4532 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004533 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4534 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004535 }
4536 result.append("\n");
4537}
4538
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004540 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004541 const auto displayId = display->getId();
4542 if (!displayId) {
4543 continue;
4544 }
4545 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004546 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004547 continue;
4548 }
4549
Yiwei Zhang5434a782018-12-05 18:06:32 -08004550 StringAppendF(&result,
4551 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4552 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004553 uint8_t port;
4554 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004555 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004556 result.append("no identification data\n");
4557 continue;
4558 }
4559
4560 if (!isEdid(data)) {
4561 result.append("unknown identification data: ");
4562 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004564 }
4565 result.append("\n");
4566 continue;
4567 }
4568
4569 const auto edid = parseEdid(data);
4570 if (!edid) {
4571 result.append("invalid EDID: ");
4572 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004574 }
4575 result.append("\n");
4576 continue;
4577 }
4578
Yiwei Zhang5434a782018-12-05 18:06:32 -08004579 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580 result.append(edid->displayName.data(), edid->displayName.length());
4581 result.append("\"\n");
4582 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004583}
4584
Yiwei Zhang5434a782018-12-05 18:06:32 -08004585void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4586 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4587 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4588 StringAppendF(&result, "DisplayColorSetting: %s\n",
4589 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004590
4591 // TODO: print out if wide-color mode is active or not
4592
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004593 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004594 const auto displayId = display->getId();
4595 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004596 continue;
4597 }
4598
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004600 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004601 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004603 }
4604
Lloyd Pique32cbe282018-10-19 13:09:22 -07004605 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606 StringAppendF(&result, " Current color mode: %s (%d)\n",
4607 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004608 }
4609 result.append("\n");
4610}
4611
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004612LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004613 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004614 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4615 const State& state = useDrawing ? mDrawingState : mCurrentState;
4616 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004617 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004618 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004619 });
4620
4621 return layersProto;
4622}
4623
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004624LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4625 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004626 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004627
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004628 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004629 resolution->set_w(displayDevice->getWidth());
4630 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004631
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004632 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004633 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004634
Lloyd Pique32cbe282018-10-19 13:09:22 -07004635 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4636 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4637 layersProto.set_global_transform(displayState.orientation);
4638
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004639 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004640 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004641 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004642 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004643 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004644 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004645 }
4646 });
4647
4648 return layersProto;
4649}
4650
Dominik Laskowskic2867142019-01-21 11:33:38 -08004651void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4652 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004653 Colorizer colorizer(colorize);
4654
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004655 // figure out if we're stuck somewhere
4656 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004657 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004658 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4659
4660 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004661 * Dump library configuration.
4662 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004663
4664 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004665 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004666 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004667 appendSfConfigString(result);
4668 appendUiConfigString(result);
4669 appendGuiConfigString(result);
4670 result.append("\n");
4671
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004672 result.append("\nDisplay identification data:\n");
4673 dumpDisplayIdentificationData(result);
4674
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004675 result.append("\nWide-Color information:\n");
4676 dumpWideColorInfo(result);
4677
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004679 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004681 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004682 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004683
Andy McFadden41d67d72014-04-25 16:58:34 -07004684 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004685 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004686 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004687 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004688 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004689
Dan Stozab90cf072015-03-05 11:05:59 -08004690 dumpStaticScreenStats(result);
4691 result.append("\n");
4692
Yiwei Zhang5434a782018-12-05 18:06:32 -08004693 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004694
Dan Stozae77c7662016-05-13 11:37:28 -07004695 dumpBufferingStats(result);
4696
Andy McFadden4803b742012-09-24 19:07:20 -07004697 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004698 * Dump the visible layer list
4699 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4702 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4703 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004704 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004705
Chia-I Wu2f884132018-09-13 15:17:58 -07004706 {
4707 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4708 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004709 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004710 result.append("\n");
4711 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004712
4713 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004714 * Dump Display state
4715 */
4716
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004720 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004721 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004722 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004723 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004724
4725 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726 * Dump SurfaceFlinger global state
4727 */
4728
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004729 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004730 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004731 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004732
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004733 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004734
Dominik Laskowski075d3172018-05-24 15:50:06 -07004735 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004736 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4737 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4739 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004740 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004741 StringAppendF(&result,
4742 " transaction-flags : %08x\n"
4743 " gpu_to_cpu_unsupported : %d\n",
4744 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004745
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004746 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004747 displayId && getHwComposer().isConnected(*displayId)) {
4748 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004749 StringAppendF(&result,
4750 " refresh-rate : %f fps\n"
4751 " x-dpi : %f\n"
4752 " y-dpi : %f\n",
4753 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4754 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004755 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
Yiwei Zhang5434a782018-12-05 18:06:32 -08004757 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758
Dan Stozae22aec72016-08-01 13:20:59 -07004759 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004760 * Tracing state
4761 */
4762 mTracing.dump(result);
4763 result.append("\n");
4764
4765 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004766 * HWC layer minidump
4767 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004768 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004769 const auto displayId = display->getId();
4770 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004771 continue;
4772 }
4773
Yiwei Zhang5434a782018-12-05 18:06:32 -08004774 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004775 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004776 const sp<DisplayDevice> displayDevice = display;
4777 mCurrentState.traverseInZOrder(
4778 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004779 result.append("\n");
4780 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781
4782 /*
4783 * Dump HWComposer state
4784 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004785 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004786 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004787 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004788 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004790 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004791
4792 /*
4793 * Dump gralloc state
4794 */
4795 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4796 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004797
4798 /*
4799 * Dump VrFlinger state if in use.
4800 */
4801 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4802 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004804 result.append("\n");
4805 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004806
4807 /**
4808 * Scheduler dump state.
4809 */
Ana Krulecc2870422019-01-29 19:00:58 -08004810 result.append("\nScheduler state:\n");
4811 result.append(mScheduler->doDump() + "\n");
4812 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004813}
4814
Dominik Laskowski075d3172018-05-24 15:50:06 -07004815const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004816 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004817 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004818 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004819 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004820 }
4821 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004822
Dominik Laskowski34157762018-10-31 13:07:19 -07004823 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004824 static const Vector<sp<Layer>> empty;
4825 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004826}
4827
Chia-I Wu28f320b2018-05-03 11:02:56 -07004828void SurfaceFlinger::updateColorMatrixLocked() {
4829 mat4 colorMatrix;
4830 if (mGlobalSaturationFactor != 1.0f) {
4831 // Rec.709 luma coefficients
4832 float3 luminance{0.213f, 0.715f, 0.072f};
4833 luminance *= 1.0f - mGlobalSaturationFactor;
4834 mat4 saturationMatrix = mat4(
4835 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4836 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4837 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4838 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4839 );
4840 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4841 } else {
4842 colorMatrix = mClientColorMatrix * mDaltonizer();
4843 }
4844
4845 if (mCurrentState.colorMatrix != colorMatrix) {
4846 mCurrentState.colorMatrix = colorMatrix;
4847 mCurrentState.colorMatrixChanged = true;
4848 setTransactionFlags(eTransactionNeeded);
4849 }
4850}
4851
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004852status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853#pragma clang diagnostic push
4854#pragma clang diagnostic error "-Wswitch-enum"
4855 switch (static_cast<ISurfaceComposerTag>(code)) {
4856 // These methods should at minimum make sure that the client requested
4857 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004858 case BOOT_FINISHED:
4859 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004860 case CREATE_DISPLAY:
4861 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004862 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004863 case GET_ACTIVE_COLOR_MODE:
4864 case GET_ANIMATION_FRAME_STATS:
4865 case GET_HDR_CAPABILITIES:
4866 case SET_ACTIVE_CONFIG:
4867 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004868 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004869 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004870 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004871 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4872 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004873 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4874 IPCThreadState* ipc = IPCThreadState::self();
4875 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4876 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004877 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004878 }
Robert Carr1db73f62016-12-21 12:58:51 -08004879 return OK;
4880 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004882 IPCThreadState* ipc = IPCThreadState::self();
4883 const int pid = ipc->getCallingPid();
4884 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4886 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004887 return PERMISSION_DENIED;
4888 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004889 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004890 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004891 // Used by apps to hook Choreographer to SurfaceFlinger.
4892 case CREATE_DISPLAY_EVENT_CONNECTION:
4893 // The following calls are currently used by clients that do not
4894 // request necessary permissions. However, they do not expose any secret
4895 // information, so it is OK to pass them.
4896 case AUTHENTICATE_SURFACE:
4897 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004898 case GET_PHYSICAL_DISPLAY_IDS:
4899 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004901 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004902 case GET_DISPLAY_CONFIGS:
4903 case GET_DISPLAY_STATS:
4904 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4905 // Calling setTransactionState is safe, because you need to have been
4906 // granted a reference to Client* and Handle* to do anything with it.
4907 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004908 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004909 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004910 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004911 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08004912 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004913 return OK;
4914 }
4915 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004916 case CAPTURE_SCREEN:
4917 case ADD_REGION_SAMPLING_LISTENER:
4918 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004920 IPCThreadState* ipc = IPCThreadState::self();
4921 const int pid = ipc->getCallingPid();
4922 const int uid = ipc->getCallingUid();
4923 if ((uid != AID_GRAPHICS) &&
4924 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4925 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4926 return PERMISSION_DENIED;
4927 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004928 return OK;
4929 }
4930 // The following codes are deprecated and should never be allowed to access SF.
4931 case CONNECT_DISPLAY_UNUSED:
4932 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4933 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4934 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004935 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004936 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937
4938 // These codes are used for the IBinder protocol to either interrogate the recipient
4939 // side of the transaction for its canonical interface descriptor or to dump its state.
4940 // We let them pass by default.
4941 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4942 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4943 code == IBinder::SYSPROPS_TRANSACTION) {
4944 return OK;
4945 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004946 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004948 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004949 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4950 return OK;
4951 }
4952 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4953 return PERMISSION_DENIED;
4954#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004955}
4956
Ana Krulec13be8ad2018-08-21 02:43:56 +00004957status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4958 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004959 status_t credentialCheck = CheckTransactCodeCredentials(code);
4960 if (credentialCheck != OK) {
4961 return credentialCheck;
4962 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004963
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4965 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004966 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004967 IPCThreadState* ipc = IPCThreadState::self();
4968 const int uid = ipc->getCallingUid();
4969 if (CC_UNLIKELY(uid != AID_SYSTEM
4970 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004971 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004972 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004973 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004974 return PERMISSION_DENIED;
4975 }
4976 int n;
4977 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004978 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004979 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 return NO_ERROR;
4981 case 1002: // SHOW_UPDATES
4982 n = data.readInt32();
4983 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004984 invalidateHwcGeometry();
4985 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004986 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004987 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004988 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004989 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004990 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004991 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004992 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004993 setTransactionFlags(
4994 eTransactionNeeded|
4995 eDisplayTransactionNeeded|
4996 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004997 return NO_ERROR;
4998 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004999 case 1006:{ // send empty update
5000 signalRefresh();
5001 return NO_ERROR;
5002 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005003 case 1008: // toggle use of hw composer
5004 n = data.readInt32();
5005 mDebugDisableHWC = n ? 1 : 0;
5006 invalidateHwcGeometry();
5007 repaintEverything();
5008 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005009 case 1009: // toggle use of transform hint
5010 n = data.readInt32();
5011 mDebugDisableTransformHint = n ? 1 : 0;
5012 invalidateHwcGeometry();
5013 repaintEverything();
5014 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005016 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005017 reply->writeInt32(0);
5018 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005019 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005020 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005021 return NO_ERROR;
5022 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005023 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005024 if (!display) {
5025 return NAME_NOT_FOUND;
5026 }
5027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005028 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005029 return NO_ERROR;
5030 }
5031 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005032 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005033 // daltonize
5034 n = data.readInt32();
5035 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005036 case 1:
5037 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5038 break;
5039 case 2:
5040 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5041 break;
5042 case 3:
5043 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5044 break;
5045 default:
5046 mDaltonizer.setType(ColorBlindnessType::None);
5047 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005048 }
5049 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005050 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005051 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005052 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005053 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005054
5055 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005056 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005057 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005058 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005059 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005060 // apply a color matrix
5061 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005062 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005063 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005064 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005065 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005066 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005067 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005068 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005069 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005070 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005072
5073 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5074 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005075 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005076 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5077 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5078 }
5079
Chia-I Wu28f320b2018-05-03 11:02:56 -07005080 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005081 return NO_ERROR;
5082 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005083 // This is an experimental interface
5084 // Needs to be shifted to proper binder interface when we productize
5085 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005086 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005087 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005088 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005089 return NO_ERROR;
5090 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005091 case 1017: {
5092 n = data.readInt32();
5093 mForceFullDamage = static_cast<bool>(n);
5094 return NO_ERROR;
5095 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005096 case 1018: { // Modify Choreographer's phase offset
5097 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005098 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005099 return NO_ERROR;
5100 }
5101 case 1019: { // Modify SurfaceFlinger's phase offset
5102 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005103 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005104 return NO_ERROR;
5105 }
Irvel468051e2016-06-13 16:44:44 -07005106 case 1020: { // Layer updates interceptor
5107 n = data.readInt32();
5108 if (n) {
5109 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005110 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005111 }
5112 else{
5113 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005114 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005115 }
5116 return NO_ERROR;
5117 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005118 case 1021: { // Disable HWC virtual displays
5119 n = data.readInt32();
5120 mUseHwcVirtualDisplays = !n;
5121 return NO_ERROR;
5122 }
Romain Guy0147a172017-06-01 13:53:56 -07005123 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005124 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005125 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005126
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005128 return NO_ERROR;
5129 }
Romain Guy54f154a2017-10-24 21:40:32 +01005130 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005131 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005132 invalidateHwcGeometry();
5133 repaintEverything();
5134 return NO_ERROR;
5135 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005136 // Deprecate, use 1030 to check whether the device is color managed.
5137 case 1024: {
5138 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005139 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005140 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005141 n = data.readInt32();
5142 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005143 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005144 mTracing.enable();
5145 doTracing("tracing.enable");
5146 reply->writeInt32(NO_ERROR);
5147 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005148 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005149 status_t err = mTracing.disable();
5150 reply->writeInt32(err);
5151 }
5152 return NO_ERROR;
5153 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005154 case 1026: { // Get layer tracing status
5155 reply->writeBool(mTracing.isEnabled());
5156 return NO_ERROR;
5157 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005158 // Is a DisplayColorSetting supported?
5159 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005160 const auto display = getDefaultDisplayDevice();
5161 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005162 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005163 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005164
5165 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5166 switch (setting) {
5167 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005168 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005169 break;
5170 case DisplayColorSetting::UNMANAGED:
5171 reply->writeBool(true);
5172 break;
5173 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005174 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005175 break;
5176 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005177 reply->writeBool(
5178 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005179 break;
5180 }
5181 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005182 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005183 // Is VrFlinger active?
5184 case 1028: {
5185 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005186 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005187 return NO_ERROR;
5188 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005189 // Is device color managed?
5190 case 1030: {
5191 reply->writeBool(useColorManagement);
5192 return NO_ERROR;
5193 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005194 // Override default composition data space
5195 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5196 // && adb shell stop zygote && adb shell start zygote
5197 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5198 // adb shell stop zygote && adb shell start zygote
5199 case 1031: {
5200 Mutex::Autolock _l(mStateLock);
5201 n = data.readInt32();
5202 if (n) {
5203 n = data.readInt32();
5204 if (n) {
5205 Dataspace dataspace = static_cast<Dataspace>(n);
5206 if (!validateCompositionDataspace(dataspace)) {
5207 return BAD_VALUE;
5208 }
5209 mDefaultCompositionDataspace = dataspace;
5210 }
5211 n = data.readInt32();
5212 if (n) {
5213 Dataspace dataspace = static_cast<Dataspace>(n);
5214 if (!validateCompositionDataspace(dataspace)) {
5215 return BAD_VALUE;
5216 }
5217 mWideColorGamutCompositionDataspace = dataspace;
5218 }
5219 } else {
5220 // restore composition data space.
5221 mDefaultCompositionDataspace = defaultCompositionDataspace;
5222 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5223 }
5224 return NO_ERROR;
5225 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005226 }
5227 }
5228 return err;
5229}
5230
Steven Thomas6d8110b2017-08-31 18:24:21 -07005231void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005232 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005233 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005234}
5235
Ana Krulec7d1d6832018-12-27 11:10:09 -08005236void SurfaceFlinger::repaintEverythingForHWC() {
5237 mRepaintEverything = true;
5238 mEventQueue->invalidateForHWC();
5239}
5240
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005241// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5242class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005243public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5245 ~WindowDisconnector() {
5246 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005247 }
5248
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005249private:
5250 ANativeWindow* mWindow;
5251 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005252};
5253
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005254status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005255 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5256 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005257 uint32_t reqWidth, uint32_t reqHeight,
5258 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005259 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005260 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005261
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005262 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005263
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005264 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5265
Chia-I Wu20261cb2018-08-23 12:55:44 -07005266 sp<DisplayDevice> display;
5267 {
5268 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005269
Chia-I Wu20261cb2018-08-23 12:55:44 -07005270 display = getDisplayDeviceLocked(displayToken);
5271 if (!display) return BAD_VALUE;
5272
Chia-I Wucb023152018-08-28 12:57:23 -07005273 // set the requested width/height to the logical display viewport size
5274 // by default
5275 if (reqWidth == 0 || reqHeight == 0) {
5276 reqWidth = uint32_t(display->getViewport().width());
5277 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005278 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005279 }
5280
Peiyong Lin0e003c92018-09-17 11:09:51 -07005281 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5282 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005283
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005284 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5285 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005286 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5287 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005288}
5289
5290status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005291 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5292 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005293 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005294 ATRACE_CALL();
5295
5296 class LayerRenderArea : public RenderArea {
5297 public:
Robert Carr578038f2018-03-09 12:25:24 -08005298 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005299 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5300 bool childrenOnly)
5301 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005302 mLayer(layer),
5303 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005304 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005305 mFlinger(flinger),
5306 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005307 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005308 Rect getBounds() const override {
5309 const Layer::State& layerState(mLayer->getDrawingState());
5310 return mLayer->getBufferSize(layerState);
5311 }
Marissa Wall61c58622018-07-18 10:12:20 -07005312 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005313 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005314 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005315 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005316 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005317 }
chaviwa76b2712017-09-20 12:02:26 -07005318 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005319 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005320 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005321 Rect getSourceCrop() const override {
5322 if (mCrop.isEmpty()) {
5323 return getBounds();
5324 } else {
5325 return mCrop;
5326 }
5327 }
Robert Carr578038f2018-03-09 12:25:24 -08005328 class ReparentForDrawing {
5329 public:
5330 const sp<Layer>& oldParent;
5331 const sp<Layer>& newParent;
5332
Vishnu Nair4351ad52019-02-11 14:13:02 -08005333 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5334 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005335 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005336 // Compute and cache the bounds for the new parent layer.
5337 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005338 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005339 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005340 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005341 };
5342
5343 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005344 const Rect sourceCrop = getSourceCrop();
5345 // no need to check rotation because there is none
5346 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5347 sourceCrop.height() != getReqHeight();
5348
Robert Carr578038f2018-03-09 12:25:24 -08005349 if (!mChildrenOnly) {
5350 mTransform = mLayer->getTransform().inverse();
5351 drawLayers();
5352 } else {
5353 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005354 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005355 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5356 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005357
Vishnu Nair4351ad52019-02-11 14:13:02 -08005358 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005359 drawLayers();
5360 }
5361 }
chaviwa76b2712017-09-20 12:02:26 -07005362
chaviwa76b2712017-09-20 12:02:26 -07005363 private:
chaviw7206d492017-11-10 16:16:12 -08005364 const sp<Layer> mLayer;
5365 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005366
5367 // In the "childrenOnly" case we reparent the children to a screenshot
5368 // layer which has no properties set and which does not draw.
5369 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005370 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005371 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005372
5373 SurfaceFlinger* mFlinger;
5374 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005375 };
5376
5377 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5378 auto parent = layerHandle->owner.promote();
5379
Robert Carr2e102c92018-10-23 12:11:15 -07005380 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005381 ALOGE("captureLayers called with a removed parent");
5382 return NAME_NOT_FOUND;
5383 }
5384
Robert Carr578038f2018-03-09 12:25:24 -08005385 const int uid = IPCThreadState::self()->getCallingUid();
5386 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005387 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005388 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5389 return PERMISSION_DENIED;
5390 }
5391
chaviw7206d492017-11-10 16:16:12 -08005392 Rect crop(sourceCrop);
5393 if (sourceCrop.width() <= 0) {
5394 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005395 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005396 }
5397
5398 if (sourceCrop.height() <= 0) {
5399 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005400 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005401 }
5402
5403 int32_t reqWidth = crop.width() * frameScale;
5404 int32_t reqHeight = crop.height() * frameScale;
5405
Chia-I Wu20261cb2018-08-23 12:55:44 -07005406 // really small crop or frameScale
5407 if (reqWidth <= 0) {
5408 reqWidth = 1;
5409 }
5410 if (reqHeight <= 0) {
5411 reqHeight = 1;
5412 }
5413
Peiyong Lin0e003c92018-09-17 11:09:51 -07005414 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005415
Robert Carr578038f2018-03-09 12:25:24 -08005416 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005417 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5418 if (!layer->isVisible()) {
5419 return;
Robert Carr578038f2018-03-09 12:25:24 -08005420 } else if (childrenOnly && layer == parent.get()) {
5421 return;
chaviwa76b2712017-09-20 12:02:26 -07005422 }
5423 visitor(layer);
5424 });
5425 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005426 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005427}
5428
5429status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5430 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005431 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005432 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005433 bool useIdentityTransform) {
5434 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005435
Peiyong Lin0e003c92018-09-17 11:09:51 -07005436 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005437 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5438 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005439 *outBuffer =
5440 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5441 static_cast<android_pixel_format>(reqPixelFormat), 1,
5442 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005443
5444 // This mutex protects syncFd and captureResult for communication of the return values from the
5445 // main thread back to this Binder thread
5446 std::mutex captureMutex;
5447 std::condition_variable captureCondition;
5448 std::unique_lock<std::mutex> captureLock(captureMutex);
5449 int syncFd = -1;
5450 std::optional<status_t> captureResult;
5451
Robert Carr03480e22018-01-04 16:02:06 -08005452 const int uid = IPCThreadState::self()->getCallingUid();
5453 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5454
Dominik Laskowski8c001672018-05-30 16:52:06 -07005455 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005456 // If there is a refresh pending, bug out early and tell the binder thread to try again
5457 // after the refresh.
5458 if (mRefreshPending) {
5459 ATRACE_NAME("Skipping screenshot for now");
5460 std::unique_lock<std::mutex> captureLock(captureMutex);
5461 captureResult = std::make_optional<status_t>(EAGAIN);
5462 captureCondition.notify_one();
5463 return;
5464 }
5465
5466 status_t result = NO_ERROR;
5467 int fd = -1;
5468 {
5469 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005470 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005471 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5472 useIdentityTransform, forSystem, &fd);
5473 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005474 }
5475
5476 {
5477 std::unique_lock<std::mutex> captureLock(captureMutex);
5478 syncFd = fd;
5479 captureResult = std::make_optional<status_t>(result);
5480 captureCondition.notify_one();
5481 }
5482 });
5483
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005484 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005485 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005486 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005487 while (*captureResult == EAGAIN) {
5488 captureResult.reset();
5489 result = postMessageAsync(message);
5490 if (result != NO_ERROR) {
5491 return result;
5492 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005493 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005494 }
5495 result = *captureResult;
5496 }
5497
5498 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005499 sync_wait(syncFd, -1);
5500 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005501 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005502
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005504}
5505
chaviwa76b2712017-09-20 12:02:26 -07005506void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005507 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005508 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5509 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005510 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005511
chaviwa76b2712017-09-20 12:02:26 -07005512 const auto reqWidth = renderArea.getReqWidth();
5513 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005514 const auto sourceCrop = renderArea.getSourceCrop();
5515 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005516
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005517 renderengine::DisplaySettings clientCompositionDisplay;
5518 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005519
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005520 // assume that bounds are never offset, and that they are the same as the
5521 // buffer bounds.
5522 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5523 ui::Transform transform = renderArea.getTransform();
5524 mat4 m;
5525 m[0][0] = transform[0][0];
5526 m[0][1] = transform[0][1];
5527 m[0][3] = transform[0][2];
5528 m[1][0] = transform[1][0];
5529 m[1][1] = transform[1][1];
5530 m[1][3] = transform[1][2];
5531 m[3][0] = transform[2][0];
5532 m[3][1] = transform[2][1];
5533 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005534
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005535 clientCompositionDisplay.globalTransform = m;
5536 mat4 rotMatrix;
5537 // Displacement for repositioning the clipping rectangle after rotating it
5538 // with the rotation hint.
5539 int displacementX = 0;
5540 int displacementY = 0;
5541 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5542 switch (rotation) {
5543 case ui::Transform::ROT_90:
5544 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5545 displacementX = reqWidth;
5546 break;
5547 case ui::Transform::ROT_180:
5548 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5549 displacementX = reqWidth;
5550 displacementY = reqHeight;
5551 break;
5552 case ui::Transform::ROT_270:
5553 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5554 displacementY = reqHeight;
5555 break;
5556 default:
5557 break;
5558 }
5559 // We need to transform the clipping window into the right spot.
5560 // First, rotate the clipping rectangle by the rotation hint to get the
5561 // right orientation
5562 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5563 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5564 const vec4 rotClipTL = rotMatrix * clipTL;
5565 const vec4 rotClipBR = rotMatrix * clipBR;
5566 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5567 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5568 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5569 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5570
5571 // Now reposition the clipping rectangle with the displacement vector
5572 // computed above.
5573 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5574
5575 clientCompositionDisplay.clip =
5576 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5577 newClipRight + displacementX, newClipBottom + displacementY);
5578
5579 // We need to perform the same transformation in layer space, so propagate
5580 // it to the global transform.
5581 mat4 clipTransform = displacementMat * rotMatrix;
5582 clientCompositionDisplay.globalTransform *= clipTransform;
5583 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5584 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005585
chaviw50da5042018-04-09 13:49:37 -07005586 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005587
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005588 renderengine::LayerSettings fillLayer;
5589 fillLayer.source.buffer.buffer = nullptr;
5590 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5591 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5592 fillLayer.alpha = half(alpha);
5593 clientCompositionLayers.push_back(fillLayer);
5594
5595 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005596 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005597 renderengine::LayerSettings layerSettings;
5598 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5599 layerSettings);
5600 if (prepared) {
5601 clientCompositionLayers.push_back(layerSettings);
5602 }
chaviwa76b2712017-09-20 12:02:26 -07005603 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005604
5605 clientCompositionDisplay.clearRegion = clearRegion;
5606 base::unique_fd drawFence;
5607 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5608 &drawFence);
5609
5610 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005611}
5612
chaviwa76b2712017-09-20 12:02:26 -07005613status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5614 TraverseLayersFunction traverseLayers,
5615 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005616 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005617 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005618 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005619 ATRACE_CALL();
5620
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005621 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005622
5623 traverseLayers([&](Layer* layer) {
5624 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5625 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005626
Robert Carr03480e22018-01-04 16:02:06 -08005627 // We allow the system server to take screenshots of secure layers for
5628 // use in situations like the Screen-rotation animation and place
5629 // the impetus on WindowManager to not persist them.
5630 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005631 ALOGW("FB is protected: PERMISSION_DENIED");
5632 return PERMISSION_DENIED;
5633 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005634 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005635 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005636}
5637
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005638// ---------------------------------------------------------------------------
5639
Dan Stoza412903f2017-04-27 13:42:17 -07005640void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5641 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005642}
5643
Dan Stoza412903f2017-04-27 13:42:17 -07005644void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5645 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005646}
5647
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005648void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005649 const LayerVector::Visitor& visitor) {
5650 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005651 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005652 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005653 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005654 continue;
5655 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005656 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005657 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005658 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005659 return;
5660 }
chaviwa76b2712017-09-20 12:02:26 -07005661 if (!layer->isVisible()) {
5662 return;
5663 }
5664 visitor(layer);
5665 });
5666 }
5667}
5668
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005669}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005670
Lloyd Pique074e8122018-07-26 12:57:23 -07005671
Mathias Agopian3f844832013-08-07 21:24:32 -07005672#if defined(__gl_h_)
5673#error "don't include gl/gl.h in this file"
5674#endif
5675
5676#if defined(__gl2_h_)
5677#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005678#endif