blob: 03c144b3a3dacf4affd0ebbfc59051b90222ec88 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080065#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070098#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070099#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/EventControlThread.h"
101#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700102#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700103#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700104#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800105#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700108
David Sodman7e4ae112018-02-09 15:02:28 -0800109#include "android-base/stringprintf.h"
110
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800112#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700113#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900115#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
chaviw1d044282017-09-27 12:19:28 -0700117#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900118#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700121
Jaesoo Lee43518572017-01-23 19:03:16 +0900122using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900124using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800125
Yiwei Zhang5434a782018-12-05 18:06:32 -0800126using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700127using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700128using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800129using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700130using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700131using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800133using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
134
Steven Thomasb02664d2017-07-26 18:48:28 -0700135namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700136
137#pragma clang diagnostic push
138#pragma clang diagnostic error "-Wswitch-enum"
139
140bool isWideColorMode(const ColorMode colorMode) {
141 switch (colorMode) {
142 case ColorMode::DISPLAY_P3:
143 case ColorMode::ADOBE_RGB:
144 case ColorMode::DCI_P3:
145 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700146 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700147 case ColorMode::BT2100_PQ:
148 case ColorMode::BT2100_HLG:
149 return true;
150 case ColorMode::NATIVE:
151 case ColorMode::STANDARD_BT601_625:
152 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
153 case ColorMode::STANDARD_BT601_525:
154 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
155 case ColorMode::STANDARD_BT709:
156 case ColorMode::SRGB:
157 return false;
158 }
159 return false;
160}
161
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700162ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
163 switch (rotation) {
164 case ISurfaceComposer::eRotateNone:
165 return ui::Transform::ROT_0;
166 case ISurfaceComposer::eRotate90:
167 return ui::Transform::ROT_90;
168 case ISurfaceComposer::eRotate180:
169 return ui::Transform::ROT_180;
170 case ISurfaceComposer::eRotate270:
171 return ui::Transform::ROT_270;
172 }
173 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
174 return ui::Transform::ROT_0;
175}
176
Peiyong Linfca547f2018-07-09 13:03:33 -0700177#pragma clang diagnostic pop
178
Steven Thomasb02664d2017-07-26 18:48:28 -0700179class ConditionalLock {
180public:
181 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
182 if (lock) {
183 mMutex.lock();
184 }
185 }
186 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
187private:
188 Mutex& mMutex;
189 bool mLocked;
190};
Peiyong Linfca547f2018-07-09 13:03:33 -0700191
Peiyong Lin9d846a52018-11-05 13:18:20 -0800192// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
193bool validateCompositionDataspace(Dataspace dataspace) {
194 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
195}
196
Steven Thomasb02664d2017-07-26 18:48:28 -0700197} // namespace anonymous
198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199// ---------------------------------------------------------------------------
200
Mathias Agopian99b49842011-06-27 16:05:52 -0700201const String16 sHardwareTest("android.permission.HARDWARE_TEST");
202const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
203const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
204const String16 sDump("android.permission.DUMP");
205
Daniel Solomon42d04562019-01-20 21:03:19 -0800206constexpr float kSrgbRedX = 0.4123f;
207constexpr float kSrgbRedY = 0.2126f;
208constexpr float kSrgbRedZ = 0.0193f;
209constexpr float kSrgbGreenX = 0.3576f;
210constexpr float kSrgbGreenY = 0.7152f;
211constexpr float kSrgbGreenZ = 0.1192f;
212constexpr float kSrgbBlueX = 0.1805f;
213constexpr float kSrgbBlueY = 0.0722f;
214constexpr float kSrgbBlueZ = 0.9506f;
215constexpr float kSrgbWhiteX = 0.9505f;
216constexpr float kSrgbWhiteY = 1.0000f;
217constexpr float kSrgbWhiteZ = 1.0891f;
218
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800219constexpr float kDefaultRefreshRate = 60.f;
220constexpr float kPerformanceRefreshRate = 90.f;
221
Mathias Agopian99b49842011-06-27 16:05:52 -0700222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600229bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700230int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700231bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700232bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700233Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
234ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
235Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700237
Kalle Raitaa099a242017-01-11 11:17:29 -0800238std::string getHwcServiceName() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.hwc_service_name", value, "default");
241 ALOGI("Using HWComposer service: '%s'", value);
242 return std::string(value);
243}
244
245bool useTrebleTestingOverride() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.treble_testing_override", value, "false");
248 ALOGI("Treble testing override: '%s'", value);
249 return std::string(value) == "true";
250}
251
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
253 switch(displayColorSetting) {
254 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700255 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700257 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700259 return std::string("Enhanced");
260 default:
261 return std::string("Unknown ") +
262 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800264}
265
David Sodmanbc815282017-11-05 18:57:52 -0800266SurfaceFlingerBE::SurfaceFlingerBE()
267 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800268 mFrameBuckets(),
269 mTotalTime(0),
270 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800271 mComposerSequenceId(0) {
272}
273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
275 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800276 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700277 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700278 mTransactionPending(false),
279 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700280 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700281 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800282 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800283 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800284 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800285 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800286 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800287 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700289 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700290 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700291 mDebugInTransaction(0),
292 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700293 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800294 mTimeStats(factory.createTimeStats()),
David Sodman2b406362017-12-15 13:33:47 -0800295 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800296 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700298 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700299 mMainThreadId(std::this_thread::get_id()),
300 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800301
Lloyd Pique90c115d2018-09-18 21:39:42 -0700302SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
303 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313
Steven Thomas050b2c82017-03-06 11:45:16 -0800314 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900315 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 mDefaultCompositionDataspace =
324 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
325 mWideColorGamutCompositionDataspace =
326 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
327 defaultCompositionDataspace = mDefaultCompositionDataspace;
328 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
329 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
330 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
331 wideColorGamutCompositionPixelFormat =
332 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700333
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900334 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
337 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
338 switch (tmpPrimaryDisplayOrientation) {
339 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800350 break;
351 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700352 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800353
Daniel Solomon42d04562019-01-20 21:03:19 -0800354 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
355 if (surfaceFlingerConfigsServiceV1_2) {
356 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
357 [&](auto tmpPrimaries) {
358 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
359 });
360 } else {
361 initDefaultDisplayNativePrimaries();
362 }
363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700373 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000374
375 // DDMS debugging deprecated (b/120782499)
376 property_get("debug.sf.ddms", value, "0");
377 int debugDdms = atoi(value);
378 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700379
380 property_get("debug.sf.disable_backpressure", value, "0");
381 mPropagateBackpressure = !atoi(value);
382 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700383
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800384 property_get("debug.sf.enable_hwc_vds", value, "0");
385 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800386 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800387
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800388 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800389 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800390 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700391
Yiwei Zhang243b3782018-05-15 17:40:04 -0700392 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700393 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
394 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
395
Ana Krulecc2870422019-01-29 19:00:58 -0800396 property_get("debug.sf.use_90Hz", value, "0");
397 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800398
Ana Krulecba13ab32019-02-20 14:14:12 -0800399 property_get("debug.sf.use_smart_90_for_video", value, "0");
400 mUseSmart90ForVideo = atoi(value);
401
Ana Krulec757f63a2019-01-25 10:46:18 -0800402 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
403 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700404
Romain Guy11d63f42017-07-20 12:47:14 -0700405 // We should be reading 'persist.sys.sf.color_saturation' here
406 // but since /data may be encrypted, we need to wait until after vold
407 // comes online to attempt to read the property. The property is
408 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800409
410 if (useTrebleTestingOverride()) {
411 // Without the override SurfaceFlinger cannot connect to HIDL
412 // services that are not listed in the manifests. Considered
413 // deriving the setting from the set service name, but it
414 // would be brittle if the name that's not 'default' is used
415 // for production purposes later on.
416 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800418}
419
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420void SurfaceFlinger::onFirstRef()
421{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800422 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800423}
424
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425SurfaceFlinger::~SurfaceFlinger()
426{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800427}
428
Dan Stozac7014012014-02-14 15:03:43 -0800429void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430{
431 // the window manager died on us. prepare its eulogy.
432
Andy McFadden13a082e2012-08-24 10:16:42 -0700433 // restore initial conditions (default device unblank, etc)
434 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435
436 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700437 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800438}
439
Robert Carr1db73f62016-12-21 12:58:51 -0800440static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700441 status_t err = client->initCheck();
442 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800443 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444 }
Robert Carr1db73f62016-12-21 12:58:51 -0800445 return nullptr;
446}
447
448sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
449 return initClient(new Client(this));
450}
451
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700452sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
453 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454{
455 class DisplayToken : public BBinder {
456 sp<SurfaceFlinger> flinger;
457 virtual ~DisplayToken() {
458 // no more references, this display must be terminated
459 Mutex::Autolock _l(flinger->mStateLock);
460 flinger->mCurrentState.displays.removeItem(this);
461 flinger->setTransactionFlags(eDisplayTransactionNeeded);
462 }
463 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700464 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 : flinger(flinger) {
466 }
467 };
468
469 sp<BBinder> token = new DisplayToken(this);
470
471 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 // Display ID is assigned when virtual display is allocated by HWC.
473 DisplayDeviceState state;
474 state.isSecure = secure;
475 state.displayName = displayName;
476 mCurrentState.displays.add(token, state);
477 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 return token;
479}
480
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 Mutex::Autolock _l(mStateLock);
483
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
485 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
489
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
491 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 ALOGE("destroyDisplay called for non-virtual display");
493 return;
494 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 mInterceptor->saveDisplayDeletion(state.sequenceId);
496 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 setTransactionFlags(eDisplayTransactionNeeded);
498}
499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
501 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700502
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800503 const auto internalDisplayId = getInternalDisplayIdLocked();
504 if (!internalDisplayId) {
505 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506 }
507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 std::vector<PhysicalDisplayId> displayIds;
509 displayIds.reserve(mPhysicalDisplayTokens.size());
510 displayIds.push_back(internalDisplayId->value);
511
512 for (const auto& [id, token] : mPhysicalDisplayTokens) {
513 if (id != *internalDisplayId) {
514 displayIds.push_back(id.value);
515 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700517
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800518 return displayIds;
519}
520
521sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
522 Mutex::Autolock lock(mStateLock);
523 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700524}
525
Ady Abraham37965d42018-11-01 13:43:32 -0700526status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
527 if (!outGetColorManagement) {
528 return BAD_VALUE;
529 }
530 *outGetColorManagement = useColorManagement;
531 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700532}
533
Lloyd Pique441d5042018-10-18 16:49:51 -0700534HWComposer& SurfaceFlinger::getHwComposer() const {
535 return mCompositionEngine->getHwComposer();
536}
537
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700538renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
539 return mCompositionEngine->getRenderEngine();
540}
541
Lloyd Pique70d91362018-10-18 16:02:55 -0700542compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
543 return *mCompositionEngine.get();
544}
545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546void SurfaceFlinger::bootFinished()
547{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700548 if (mStartPropertySetThread->join() != NO_ERROR) {
549 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800550 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551 const nsecs_t now = systemTime();
552 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000553 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
555 // wait patiently for the window manager death
556 const String16 name("window");
557 sp<IBinder> window(defaultServiceManager()->getService(name));
558 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700559 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 }
Robert Carr720e5062018-07-30 17:45:14 -0700561 sp<IBinder> input(defaultServiceManager()->getService(
562 String16("inputflinger")));
563 if (input == nullptr) {
564 ALOGE("Failed to link to input service");
565 } else {
566 mInputFlinger = interface_cast<IInputFlinger>(input);
567 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 if (mVrFlinger) {
570 mVrFlinger->OnBootFinished();
571 }
572
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700574 // formerly we would just kill the process, but we now ask it to exit so it
575 // can choose where to stop the animation.
576 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700577
578 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
579 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
580 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700581
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 readPersistentProperties();
584 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800585
586 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
587 // away and it should be controlled by flipping the switch in setting. The switch in
588 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
589 // The boot must be complete before we can set the active config.
590
591 if (mUse90Hz) {
592 mPhaseOffsets->setRefreshRateType(
593 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
594 setRefreshRateTo(RefreshRateType::PERFORMANCE);
595 } else {
596 mPhaseOffsets->setRefreshRateType(
597 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
598 setRefreshRateTo(RefreshRateType::DEFAULT);
599 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800600 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800601}
602
Dan Stoza436ccf32018-06-21 12:10:12 -0700603uint32_t SurfaceFlinger::getNewTexture() {
604 {
605 std::lock_guard lock(mTexturePoolMutex);
606 if (!mTexturePool.empty()) {
607 uint32_t name = mTexturePool.back();
608 mTexturePool.pop_back();
609 ATRACE_INT("TexturePoolSize", mTexturePool.size());
610 return name;
611 }
612
613 // The pool was too small, so increase it for the future
614 ++mTexturePoolSize;
615 }
616
617 // The pool was empty, so we need to get a new texture name directly using a
618 // blocking call to the main thread
619 uint32_t name = 0;
620 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
621 return name;
622}
623
Mathias Agopian3f844832013-08-07 21:24:32 -0700624void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700625 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700626}
627
Wei Wangf9b05ee2017-07-19 20:59:39 -0700628// Do not call property_set on main thread which will be blocked by init
629// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700630void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700631 ALOGI( "SurfaceFlinger's main thread ready to run. "
632 "Initializing graphics H/W...");
633
Ana Krulec757f63a2019-01-25 10:46:18 -0800634 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900635
Steven Thomasb02664d2017-07-26 18:48:28 -0700636 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700637 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800638 mScheduler =
639 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
640 auto resyncCallback =
641 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800642
Ana Krulecc2870422019-01-29 19:00:58 -0800643 mAppConnectionHandle =
644 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
645 resyncCallback,
646 impl::EventThread::InterceptVSyncsCallback());
647 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
648 resyncCallback, [this](nsecs_t timestamp) {
649 mInterceptor->saveVSyncEvent(timestamp);
650 });
651
652 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
653 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
654 mSfConnectionHandle.get());
655
Steven Thomasb02664d2017-07-26 18:48:28 -0700656 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700657 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700658 renderEngineFeature |= (useColorManagement ?
659 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700660 renderEngineFeature |= (useContextPriority ?
661 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700662
663 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700664 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700665 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700666 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700667
668 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
669 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700670 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
671 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800672 // Process any initial hotplug and resulting display changes.
673 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 const auto display = getDefaultDisplayDeviceLocked();
675 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700676 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700677 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800678
Steven Thomas050b2c82017-03-06 11:45:16 -0800679 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700680 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700681 // This callback is called from the vr flinger dispatch thread. We
682 // need to call signalTransaction(), which requires holding
683 // mStateLock when we're not on the main thread. Acquiring
684 // mStateLock from the vr flinger dispatch thread might trigger a
685 // deadlock in surface flinger (see b/66916578), so post a message
686 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700687 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700688 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
689 mVrFlingerRequestsDisplay = requestDisplay;
690 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700691 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
694 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 .value_or(0),
697 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (!mVrFlinger) {
699 ALOGE("Failed to start vrflinger");
700 }
701 }
702
Mathias Agopian92a979a2012-08-02 18:32:23 -0700703 // initialize our drawing state
704 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700705
Andy McFadden13a082e2012-08-24 10:16:42 -0700706 // set initial conditions (e.g. unblank default device)
707 initializeDisplays();
708
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700709 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700710
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700712
713 const bool presentFenceReliable =
714 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
715 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Kevin DuBois36233132019-02-19 14:08:55 -0800721 if (mUse90Hz) {
722 mScheduler->setExpiredIdleTimerCallback([this] {
723 Mutex::Autolock lock(mStateLock);
724 setRefreshRateTo(RefreshRateType::DEFAULT);
725 });
726 mScheduler->setResetIdleTimerCallback([this] {
727 Mutex::Autolock lock(mStateLock);
728 setRefreshRateTo(RefreshRateType::PERFORMANCE);
729 });
730 }
Ana Krulecc2870422019-01-29 19:00:58 -0800731 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
732 *display->getId()),
733 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800734
Dan Stoza9e56aa02015-11-02 13:00:03 -0800735 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700736}
737
Romain Guy11d63f42017-07-20 12:47:14 -0700738void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700739 Mutex::Autolock _l(mStateLock);
740
Romain Guy11d63f42017-07-20 12:47:14 -0700741 char value[PROPERTY_VALUE_MAX];
742
743 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800744 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700745 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100747
748 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700749 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800750
751 property_get("persist.sys.sf.color_mode", value, "0");
752 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700753}
754
Mathias Agopiana67e4182012-06-19 17:26:12 -0700755void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800756 // Start boot animation service by setting a property mailbox
757 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700758 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800759 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700760 if (mStartPropertySetThread->join() != NO_ERROR) {
761 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800762 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
Mathias Agopian875d8e12013-06-07 15:35:48 -0700769size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700770 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700771}
772
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800773// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800774
Jamie Gennis582270d2011-08-17 18:19:00 -0700775bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800777 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800778 return authenticateSurfaceTextureLocked(bufferProducer);
779}
780
781bool SurfaceFlinger::authenticateSurfaceTextureLocked(
782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800783 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800784 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800785}
786
Brian Anderson6b376712017-04-04 10:51:39 -0700787status_t SurfaceFlinger::getSupportedFrameTimestamps(
788 std::vector<FrameEvent>* outSupported) const {
789 *outSupported = {
790 FrameEvent::REQUESTED_PRESENT,
791 FrameEvent::ACQUIRE,
792 FrameEvent::LATCH,
793 FrameEvent::FIRST_REFRESH_START,
794 FrameEvent::LAST_REFRESH_START,
795 FrameEvent::GPU_COMPOSITION_DONE,
796 FrameEvent::DEQUEUE_READY,
797 FrameEvent::RELEASE,
798 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700799 ConditionalLock _l(mStateLock,
800 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700801 if (!getHwComposer().hasCapability(
802 HWC2::Capability::PresentFenceIsNotReliable)) {
803 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
804 }
805 return NO_ERROR;
806}
807
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800808status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
809 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700810 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 return BAD_VALUE;
812 }
813
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800814 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700815 if (!displayId) {
816 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700817 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 // TODO: Not sure if display density should handled by SF any longer
820 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700823 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800824 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700825 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826 }
827 return density;
828 }
829 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 return getDensityFromProperty("ro.sf.lcd_density"); }
834 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dominik Laskowski075d3172018-05-24 15:50:06 -0700838 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 DisplayInfo info = DisplayInfo();
840
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841 float xdpi = hwConfig->getDpiX();
842 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700844 info.w = hwConfig->getWidth();
845 info.h = hwConfig->getHeight();
846 // Default display viewport to display width and height
847 info.viewportW = info.w;
848 info.viewportH = info.h;
849
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800850 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 // The density of the device is provided by a build property
852 float density = Density::getBuildDensity() / 160.0f;
853 if (density == 0) {
854 // the build doesn't provide a density -- this is wrong!
855 // use xdpi instead
856 ALOGE("ro.sf.lcd_density must be defined as a build property");
857 density = xdpi / 160.0f;
858 }
859 if (Density::getEmuDensity()) {
860 // if "qemu.sf.lcd_density" is specified, it overrides everything
861 xdpi = ydpi = density = Density::getEmuDensity();
862 density /= 160.0f;
863 }
864 info.density = density;
865
866 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700867 const auto display = getDefaultDisplayDeviceLocked();
868 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700869
870 // This is for screenrecord
871 const Rect viewport = display->getViewport();
872 if (viewport.isValid()) {
873 info.viewportW = uint32_t(viewport.getWidth());
874 info.viewportH = uint32_t(viewport.getHeight());
875 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700876 } else {
877 // TODO: where should this value come from?
878 static const int TV_DENSITY = 213;
879 info.density = TV_DENSITY / 160.0f;
880 info.orientation = 0;
881 }
882
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 info.xdpi = xdpi;
884 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800886 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887
Andy McFadden91b2ca82014-06-13 14:04:23 -0700888 // This is how far in advance a buffer must be queued for
889 // presentation at a given time. If you want a buffer to appear
890 // on the screen at time N, you must submit the buffer before
891 // (N - presentationDeadline).
892 //
893 // Normally it's one full refresh period (to give SF a chance to
894 // latch the buffer), but this can be reduced by configuring a
895 // DispSync offset. Any additional delays introduced by the hardware
896 // composer or panel must be accounted for here.
897 //
898 // We add an additional 1ms to allow for processing time and
899 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800900 info.presentationDeadline =
901 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
903 // All non-virtual displays are currently considered secure.
904 info.secure = true;
905
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800906 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700907 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800908 std::swap(info.w, info.h);
909 }
910
Michael Wright28f24d02016-07-12 13:30:53 -0700911 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700912 }
913
Dan Stoza7f7da322014-05-02 15:26:25 -0700914 return NO_ERROR;
915}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700916
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700917status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
918 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700919 return BAD_VALUE;
920 }
921
Ana Krulecc2870422019-01-29 19:00:58 -0800922 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700923 return NO_ERROR;
924}
925
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700926int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
927 const auto display = getDisplayDevice(displayToken);
928 if (!display) {
929 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800930 return BAD_VALUE;
931 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700932
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700933 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700934}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700935
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
937 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800938
Ana Krulec7d1d6832018-12-27 11:10:09 -0800939 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940 // Lock is acquired by setRefreshRateTo.
941 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800942 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
943 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
944 return;
945 }
946
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 // Lock is acquired by setRefreshRateTo.
948 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800949 if (!display) {
950 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
951 displayToken.get());
952 return;
953 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700954 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800955 ALOGW("Attempt to set active config %d for virtual display", mode);
956 return;
957 }
958 int currentDisplayPowerMode = display->getPowerMode();
959 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
960 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700961 return;
962 }
963
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800964 // Don't check against the current mode yet. Worst case we set the desired
965 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800966 std::lock_guard<std::mutex> lock(mActiveConfigLock);
967 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
968
969 if (!mDesiredActiveConfigChanged) {
970 // This is the first time we set the desired
971 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
972
973 // This will trigger HWC refresh without resetting the idle timer.
974 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800976 mDesiredActiveConfigChanged = true;
977 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978}
979
980status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
981 ATRACE_CALL();
982 postMessageSync(new LambdaMessage(
983 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
984 return NO_ERROR;
985}
986
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987void SurfaceFlinger::setActiveConfigInternal() {
988 ATRACE_CALL();
989
990 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800991 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992
993 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
994 display->setActiveConfig(mUpcomingActiveConfig.configId);
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
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
1001 // we may be in the process of changing the active state
1002 if (mWaitForNextInvalidate) {
1003 mWaitForNextInvalidate = false;
1004
1005 repaintEverythingForHWC();
1006 // We do not want to give another frame to HWC while we are transitioning.
1007 return true;
1008 }
1009
1010 if (mCheckPendingFence) {
1011 if (mPreviousPresentFence != Fence::NO_FENCE &&
1012 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1013 // fence has not signaled yet. wait for the next invalidate
1014 repaintEverythingForHWC();
1015 return true;
1016 }
1017
1018 // We received the present fence from the HWC, so we assume it successfully updated
1019 // the config, hence we update SF.
1020 mCheckPendingFence = false;
1021 setActiveConfigInternal();
1022 }
1023
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024 // Store the local variable to release the lock.
1025 ActiveConfigInfo desiredActiveConfig;
1026 {
1027 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (!mDesiredActiveConfigChanged) {
1029 return false;
1030 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 desiredActiveConfig = mDesiredActiveConfig;
1032 }
1033
1034 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1036 // display is not valid or we are already in the requested mode
1037 // on both cases there is nothing left to do
1038 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1039 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1040 mDesiredActiveConfigChanged = false;
1041 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1042 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044
1045 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1046 mUpcomingActiveConfig = desiredActiveConfig;
1047 const auto displayId = display->getId();
1048 LOG_ALWAYS_FATAL_IF(!displayId);
1049
1050 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1051 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1052
1053 // we need to submit an empty frame to HWC to start the process
1054 mWaitForNextInvalidate = true;
1055 mCheckPendingFence = true;
1056
1057 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001058}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001059
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1061 Vector<ColorMode>* outColorModes) {
1062 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001063 return BAD_VALUE;
1064 }
1065
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001068 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1069
1070 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1071 if (!displayId) {
1072 return NAME_NOT_FOUND;
1073 }
1074
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001076 }
Michael Wright28f24d02016-07-12 13:30:53 -07001077 outColorModes->clear();
1078 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1079
1080 return NO_ERROR;
1081}
1082
Daniel Solomon42d04562019-01-20 21:03:19 -08001083status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1084 ui::DisplayPrimaries &primaries) {
1085 if (!displayToken) {
1086 return BAD_VALUE;
1087 }
1088
1089 // Currently we only support this API for a single internal display.
1090 if (getInternalDisplayToken() != displayToken) {
1091 return BAD_VALUE;
1092 }
1093
1094 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1099 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001100 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001102 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001103}
1104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001106 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 Vector<ColorMode> modes;
1108 getDisplayColorModes(displayToken, &modes);
1109 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1110 if (mode < ColorMode::NATIVE || !exists) {
1111 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1112 decodeColorMode(mode).c_str(), mode, displayToken.get());
1113 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 const auto display = getDisplayDevice(displayToken);
1116 if (!display) {
1117 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1118 decodeColorMode(mode).c_str(), mode, displayToken.get());
1119 } else if (display->isVirtual()) {
1120 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1121 decodeColorMode(mode).c_str(), mode);
1122 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001123 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1124 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125 }
1126 }));
1127
Michael Wright28f24d02016-07-12 13:30:53 -07001128 return NO_ERROR;
1129}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001130
Svetoslavd85084b2014-03-20 10:28:31 -07001131status_t SurfaceFlinger::clearAnimationFrameStats() {
1132 Mutex::Autolock _l(mStateLock);
1133 mAnimFrameTracker.clearStats();
1134 return NO_ERROR;
1135}
1136
1137status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1138 Mutex::Autolock _l(mStateLock);
1139 mAnimFrameTracker.getStats(outStats);
1140 return NO_ERROR;
1141}
1142
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1144 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001145 Mutex::Autolock _l(mStateLock);
1146
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 const auto display = getDisplayDeviceLocked(displayToken);
1148 if (!display) {
1149 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001150 return BAD_VALUE;
1151 }
1152
Peiyong Linfb069302018-04-25 14:34:31 -07001153 // At this point the DisplayDeivce should already be set up,
1154 // meaning the luminance information is already queried from
1155 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001157 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1158 capabilities.getDesiredMaxLuminance(),
1159 capabilities.getDesiredMaxAverageLuminance(),
1160 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001161
1162 return NO_ERROR;
1163}
1164
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001165status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1166 ui::PixelFormat* outFormat,
1167 ui::Dataspace* outDataspace,
1168 uint8_t* outComponentMask) const {
1169 if (!outFormat || !outDataspace || !outComponentMask) {
1170 return BAD_VALUE;
1171 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001172 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001173 if (!display || !display->getId()) {
1174 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1175 return BAD_VALUE;
1176 }
1177 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1178 outDataspace, outComponentMask);
1179}
1180
Kevin DuBois74e53772018-11-19 10:52:38 -08001181status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1182 bool enable, uint8_t componentMask,
1183 uint64_t maxFrames) const {
1184 const auto display = getDisplayDevice(displayToken);
1185 if (!display || !display->getId()) {
1186 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1187 return BAD_VALUE;
1188 }
1189
1190 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1191 componentMask, maxFrames);
1192}
1193
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001194status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1195 uint64_t maxFrames, uint64_t timestamp,
1196 DisplayedFrameStats* outStats) const {
1197 const auto display = getDisplayDevice(displayToken);
1198 if (!display || !display->getId()) {
1199 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1200 return BAD_VALUE;
1201 }
1202
1203 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1204 outStats);
1205}
1206
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001207status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1208 if (!outSupported) {
1209 return BAD_VALUE;
1210 }
1211 *outSupported = getRenderEngine().supportsProtectedContent();
1212 return NO_ERROR;
1213}
1214
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001215status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1216 bool* outIsWideColorDisplay) const {
1217 if (!displayToken || !outIsWideColorDisplay) {
1218 return BAD_VALUE;
1219 }
1220 Mutex::Autolock _l(mStateLock);
1221 const auto display = getDisplayDeviceLocked(displayToken);
1222 if (!display) {
1223 return BAD_VALUE;
1224 }
1225 *outIsWideColorDisplay = display->hasWideColorGamut();
1226 return NO_ERROR;
1227}
1228
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001230 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001231 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 if (mInjectVSyncs == enable) {
1234 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001235 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236
Ana Krulecc2870422019-01-29 19:00:58 -08001237 auto resyncCallback =
1238 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001239
Ana Krulec98b5b242018-08-10 15:03:23 -07001240 // TODO(akrulec): Part of the Injector should be refactored, so that it
1241 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 if (enable) {
1243 ALOGV("VSync Injections enabled");
1244 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001245 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001246 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001247 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001248 impl::EventThread::InterceptVSyncsCallback(),
1249 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001251 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 } else {
1253 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001254 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1255 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 }
1257
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001259 }));
1260
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001261 return NO_ERROR;
1262}
1263
1264status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001265 Mutex::Autolock _l(mStateLock);
1266
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001267 if (!mInjectVSyncs) {
1268 ALOGE("VSync Injections not enabled");
1269 return BAD_VALUE;
1270 }
1271 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1272 ALOGV("Injecting VSync inside SurfaceFlinger");
1273 mVSyncInjector->onInjectSyncEvent(when);
1274 }
1275 return NO_ERROR;
1276}
1277
Lloyd Pique755e3192018-01-31 16:46:15 -08001278status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1279 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001280 // Try to acquire a lock for 1s, fail gracefully
1281 const status_t err = mStateLock.timedLock(s2ns(1));
1282 const bool locked = (err == NO_ERROR);
1283 if (!locked) {
1284 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1285 return TIMED_OUT;
1286 }
1287
1288 outLayers->clear();
1289 mCurrentState.traverseInZOrder([&](Layer* layer) {
1290 outLayers->push_back(layer->getLayerDebugInfo());
1291 });
1292
1293 mStateLock.unlock();
1294 return NO_ERROR;
1295}
1296
Peiyong Linc6780972018-10-28 15:24:08 -07001297status_t SurfaceFlinger::getCompositionPreference(
1298 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1299 Dataspace* outWideColorGamutDataspace,
1300 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001301 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001302 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001303 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001304 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001305 return NO_ERROR;
1306}
1307
Dan Stoza84ab9372018-12-17 15:27:57 -08001308status_t SurfaceFlinger::addRegionSamplingListener(
1309 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1310 const sp<IRegionSamplingListener>& /*listener*/) {
1311 return NO_ERROR;
1312}
1313
1314status_t SurfaceFlinger::removeRegionSamplingListener(
1315 const sp<IRegionSamplingListener>& /*listener*/) {
1316 return NO_ERROR;
1317}
1318
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001319// ----------------------------------------------------------------------------
1320
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001321sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1322 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001323 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001324 Mutex::Autolock lock(mStateLock);
1325 return getVsyncPeriod();
1326 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001327
Ana Krulecc2870422019-01-29 19:00:58 -08001328 const auto& handle =
1329 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001330
Ana Krulecc2870422019-01-29 19:00:58 -08001331 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001332}
1333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001334// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001335
1336void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001337 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338}
1339
1340void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001341 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001342}
1343
1344void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001345 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001346}
1347
1348void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001349 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001350 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001351}
1352
1353status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001354 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001355 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001356}
1357
1358status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001359 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001360 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001361 if (res == NO_ERROR) {
1362 msg->wait();
1363 }
1364 return res;
1365}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001366
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001367void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001368 do {
1369 waitForEvent();
1370 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001371}
1372
Dominik Laskowski83b88212018-12-11 13:34:06 -08001373nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001374 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001375 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1376 return 0;
1377 }
1378
1379 const auto config = getHwComposer().getActiveConfig(*displayId);
1380 return config ? config->getVsyncPeriod() : 0;
1381}
1382
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001383void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1384 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001385 ATRACE_NAME("SF onVsync");
1386
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
1391 }
1392
Dominik Laskowski075d3172018-05-24 15:50:06 -07001393 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001394 return;
1395 }
1396
Dominik Laskowski075d3172018-05-24 15:50:06 -07001397 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 // For now, we don't do anything with external display vsyncs.
1399 return;
1400 }
1401
Ana Krulecc2870422019-01-29 19:00:58 -08001402 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001403}
1404
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001406 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1407 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408}
1409
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001410void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1411 mPhaseOffsets->setRefreshRateType(refreshRate);
1412
1413 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1414 mVsyncModulator.setPhaseOffsets(early, gl, late);
1415
1416 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001417 return;
1418 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001419
Ana Krulec7d1d6832018-12-27 11:10:09 -08001420 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1421 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1422 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1423 // refresh cycle.
1424
1425 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001426 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001427 if (currentVsyncPeriod == 0) {
1428 return;
1429 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001430
Ana Krulec7d1d6832018-12-27 11:10:09 -08001431 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1432 // floating numbers.
1433 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001434 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1435 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001436 if (std::abs(currentFps - newFps) <= 1) {
1437 return;
1438 }
1439
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001440 const auto displayId = getInternalDisplayIdLocked();
1441 LOG_ALWAYS_FATAL_IF(!displayId);
1442
1443 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001444 for (int i = 0; i < configs.size(); i++) {
1445 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1446 if (vsyncPeriod == 0) {
1447 continue;
1448 }
1449 const float fps = 1e9 / vsyncPeriod;
1450 // TODO(b/113612090): There should be a better way at determining which config
1451 // has the right refresh rate.
1452 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001453 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454 }
1455 }
1456}
1457
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001458void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001459 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001461 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462
Lloyd Piqueba04e622017-12-14 17:11:26 -08001463 // Ignore events that do not have the right sequenceId.
1464 if (sequenceId != getBE().mComposerSequenceId) {
1465 return;
1466 }
1467
Steven Thomasb02664d2017-07-26 18:48:28 -07001468 // Only lock if we're not on the main thread. This function is normally
1469 // called on a hwbinder thread, but for the primary display it's called on
1470 // the main thread with the state lock already held, so don't attempt to
1471 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001472 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001473
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001474 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001475
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001476 if (std::this_thread::get_id() == mMainThreadId) {
1477 // Process all pending hot plug events immediately if we are on the main thread.
1478 processDisplayHotplugEventsLocked();
1479 }
1480
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001482}
1483
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001484void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001485 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001486 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001489 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001490}
1491
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001492void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001493 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001494 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001495 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 getHwComposer().setVsyncEnabled(*displayId,
1497 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1498 }
Mathias Agopian86303202012-07-24 22:46:10 -07001499}
1500
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001502void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001503 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504 // Clear the drawing state so that the logic inside of
1505 // handleTransactionLocked will fire. It will determine the delta between
1506 // mCurrentState and mDrawingState and re-apply all changes when we make the
1507 // transition.
1508 mDrawingState.displays.clear();
1509 mDisplays.clear();
1510}
1511
Steven Thomas050b2c82017-03-06 11:45:16 -08001512void SurfaceFlinger::updateVrFlinger() {
1513 if (!mVrFlinger)
1514 return;
1515 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001516 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001517 return;
1518 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519
Lloyd Pique441d5042018-10-18 16:49:51 -07001520 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001521 ALOGE("Vr flinger is only supported for remote hardware composer"
1522 " service connections. Ignoring request to transition to vr"
1523 " flinger.");
1524 mVrFlingerRequestsDisplay = false;
1525 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001526 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001528 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001529
Steven Thomas0123ac62018-07-12 11:32:34 -07001530 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001531 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001532
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001533 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001534
1535 // Clear out all the output layers from the composition engine for all
1536 // displays before destroying the hardware composer interface. This ensures
1537 // any HWC layers are destroyed through that interface before it becomes
1538 // invalid.
1539 for (const auto& [token, displayDevice] : mDisplays) {
1540 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1541 compositionengine::Output::OutputLayers());
1542 }
1543
Steven Thomas0123ac62018-07-12 11:32:34 -07001544 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1545 // called below. Clear the reference now so we don't accidentally use it
1546 // later.
1547 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001550 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001551 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001552
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001554 // Delete the current instance before creating the new one
1555 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1556 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1557 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1558 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559
Lloyd Pique441d5042018-10-18 16:49:51 -07001560 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001561 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001562
1563 if (vrFlingerRequestsDisplay) {
1564 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001565 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001566
1567 mVisibleRegionsDirty = true;
1568 invalidateHwcGeometry();
1569
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001570 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001571 display = getDefaultDisplayDeviceLocked();
1572 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001573 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001576 const nsecs_t vsyncPeriod = getVsyncPeriod();
1577 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001578
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001579 // The present fences returned from vr_hwc are not an accurate
1580 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001581 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001582
Steven Thomasb02664d2017-07-26 18:48:28 -07001583 // Use phase of 0 since phase is not known.
1584 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001585 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001586 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001587
Ana Krulecc2870422019-01-29 19:00:58 -08001588 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001589
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001590 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592}
1593
Mathias Agopian4fec8732012-06-29 14:12:52 -07001594void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001595 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001596 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001597 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001598 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001599 break;
1600 }
1601
Ana Krulecba13ab32019-02-20 14:14:12 -08001602 if (mUse90Hz && mUseSmart90ForVideo) {
1603 // This call is made each time SF wakes up and creates a new frame. It is part
1604 // of video detection feature.
1605 mScheduler->incrementFrameCounter();
1606 }
Ana Krulecc2870422019-01-29 19:00:58 -08001607
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001608 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1609 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001610 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001611 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001612 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001613 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001614 if (mPropagateBackpressure) {
1615 signalLayerUpdate();
1616 break;
1617 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001618 }
Dan Stoza50182882016-07-08 12:02:20 -07001619
Steven Thomas050b2c82017-03-06 11:45:16 -08001620 // Now that we're going to make it to the handleMessageTransaction()
1621 // call below it's safe to call updateVrFlinger(), which will
1622 // potentially trigger a display handoff.
1623 updateVrFlinger();
1624
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625 bool refreshNeeded = handleMessageTransaction();
1626 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001627
1628 updateCursorAsync();
1629 updateInputFlinger();
1630
Dan Stoza58784442014-12-02 16:58:17 -08001631 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001632 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001633 // Signal a refresh if a transaction modified the window state,
1634 // a new buffer was latched, or if HWC has requested a full
1635 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001636 signalRefresh();
1637 }
1638 break;
1639 }
1640 case MessageQueue::REFRESH: {
1641 handleMessageRefresh();
1642 break;
1643 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001644 }
1645}
1646
Dan Stoza6b9454d2014-11-07 16:00:59 -08001647bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001648 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001649
1650 // Apply any ready transactions in the queues if there are still transactions that have not been
1651 // applied, wake up during the next vsync period and check again
1652 bool transactionNeeded = false;
1653 if (!flushTransactionQueues()) {
1654 transactionNeeded = true;
1655 }
1656
Mathias Agopian4fec8732012-06-29 14:12:52 -07001657 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001658 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001659 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001660
1661 if (transactionNeeded) {
1662 setTransactionFlags(eTransactionNeeded);
1663 }
1664
1665 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001666}
1667
Mathias Agopian4fec8732012-06-29 14:12:52 -07001668void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001670
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001671 mRefreshPending = false;
1672
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001673 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001674 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001675 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001676 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001677 for (const auto& [token, display] : mDisplays) {
1678 beginFrame(display);
1679 prepareFrame(display);
1680 doDebugFlashRegions(display, repaintEverything);
1681 doComposition(display, repaintEverything);
1682 }
1683
Adrian Roos1e1a1282017-11-01 19:05:31 +01001684 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001685 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001686
1687 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001688 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001689
Dan Stozabfbffeb2016-07-21 14:49:33 -07001690 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001691 for (const auto& [token, displayDevice] : mDisplays) {
1692 auto display = displayDevice->getCompositionDisplay();
1693 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001694 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001695 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001696 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001697
Jorim Jaggi90535212018-05-23 23:44:06 +02001698 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001699
David Sodman7e4ae112018-02-09 15:02:28 -08001700 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001701
1702 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001704
David Sodmanfa9b2af2017-12-24 13:28:59 -08001705
1706bool SurfaceFlinger::handleMessageInvalidate() {
1707 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001708 bool refreshNeeded = handlePageFlip();
1709
Vishnu Nair4351ad52019-02-11 14:13:02 -08001710 if (mVisibleRegionsDirty) {
1711 computeLayerBounds();
1712 }
1713
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001714 for (auto& layer : mLayersPendingRefresh) {
1715 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001716 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001717 invalidateLayerStack(layer, visibleReg);
1718 }
1719 mLayersPendingRefresh.clear();
1720 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001721}
1722
David Sodman79bba0e2018-08-05 18:07:49 -07001723void SurfaceFlinger::calculateWorkingSet() {
1724 ATRACE_CALL();
1725 ALOGV(__FUNCTION__);
1726
David Sodman79bba0e2018-08-05 18:07:49 -07001727 // build the h/w work list
1728 if (CC_UNLIKELY(mGeometryInvalid)) {
1729 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001730 for (const auto& [token, displayDevice] : mDisplays) {
1731 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001732 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001733 if (!displayId) {
1734 continue;
1735 }
David Sodman79bba0e2018-08-05 18:07:49 -07001736
Lloyd Pique32cbe282018-10-19 13:09:22 -07001737 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738 for (size_t i = 0; i < currentLayers.size(); i++) {
1739 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001740
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001741 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001742 layer->forceClientComposition(displayDevice);
1743 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001744 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001745
Lloyd Pique32cbe282018-10-19 13:09:22 -07001746 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001747 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001748 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001749 }
David Sodman79bba0e2018-08-05 18:07:49 -07001750 }
1751 }
1752 }
1753
1754 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001755 for (const auto& [token, displayDevice] : mDisplays) {
1756 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001757 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001758 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001759 continue;
1760 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001761 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001762
1763 if (mDrawingState.colorMatrixChanged) {
1764 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001765 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001766 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001767 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001768 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001769 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1770 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001771 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001772 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001773 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1774 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001775 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001776 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001777 }
1778
Peiyong Lind3788632018-09-18 16:01:31 -07001779 // TODO(b/111562338) remove when composer 2.3 is shipped.
1780 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001781 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001782 }
1783
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001784 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001785 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001786 }
1787
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001788 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001789 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001790 layer->setCompositionType(displayDevice,
1791 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001792 continue;
1793 }
1794
Lloyd Pique32cbe282018-10-19 13:09:22 -07001795 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001796 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001797 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001798 }
1799
Peiyong Lin13effd12018-07-24 17:01:47 -07001800 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001801 ColorMode colorMode;
1802 Dataspace dataSpace;
1803 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001804 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001806 }
1807 }
1808
1809 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001810
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001811 for (const auto& [token, displayDevice] : mDisplays) {
1812 auto display = displayDevice->getCompositionDisplay();
1813 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001814 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001815 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1816 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1817 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001818 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001819 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001820 }
1821 }
David Sodman79bba0e2018-08-05 18:07:49 -07001822}
1823
Lloyd Pique32cbe282018-10-19 13:09:22 -07001824void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1825 bool repaintEverything) {
1826 auto display = displayDevice->getCompositionDisplay();
1827 const auto& displayState = display->getState();
1828
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829 // is debugging enabled
1830 if (CC_LIKELY(!mDebugRegion))
1831 return;
1832
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001835 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001837 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001838 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001839 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001840
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001841 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001842 }
1843 }
1844
Lloyd Pique32cbe282018-10-19 13:09:22 -07001845 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001846
1847 if (mDebugRegion > 1) {
1848 usleep(mDebugRegion * 1000);
1849 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001850
Lloyd Pique32cbe282018-10-19 13:09:22 -07001851 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001852}
1853
Adrian Roos1e1a1282017-11-01 19:05:31 +01001854void SurfaceFlinger::doTracing(const char* where) {
1855 ATRACE_CALL();
1856 ATRACE_NAME(where);
1857 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001858 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001859 }
1860}
1861
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001862void SurfaceFlinger::logLayerStats() {
1863 ATRACE_CALL();
1864 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001865 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001866 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001867 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001868 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001869 }
1870 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001871
1872 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001873 }
1874}
1875
David Sodman2b406362017-12-15 13:33:47 -08001876void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001878 ATRACE_CALL();
1879 ALOGV("preComposition");
1880
David Sodman2b406362017-12-15 13:33:47 -08001881 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1882
Mathias Agopiancd60f992012-08-16 16:28:27 -07001883 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001884 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001885 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001886 needExtraInvalidate = true;
1887 }
Robert Carr2047fae2016-11-28 14:09:09 -08001888 });
1889
Mathias Agopiancd60f992012-08-16 16:28:27 -07001890 if (needExtraInvalidate) {
1891 signalLayerUpdate();
1892 }
1893}
1894
Ana Krulece588e312018-09-18 12:32:24 -07001895void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1896 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001897 // Update queue of past composite+present times and determine the
1898 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001899 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001900 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001901 while (!getBE().mCompositePresentTimes.empty()) {
1902 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 // Cached values should have been updated before calling this method,
1904 // which helps avoid duplicate syscalls.
1905 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1906 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1907 break;
1908 }
1909 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001910 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 }
1912
1913 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001914 while (getBE().mCompositePresentTimes.size() > 16) {
1915 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916 }
1917
Ana Krulece588e312018-09-18 12:32:24 -07001918 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001919}
1920
Ana Krulece588e312018-09-18 12:32:24 -07001921void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1922 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001923 // Integer division and modulo round toward 0 not -inf, so we need to
1924 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001925 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1926 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1927 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928
Ana Krulec757f63a2019-01-25 10:46:18 -08001929 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001930 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001931 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001932 }
1933
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 // Snap the latency to a value that removes scheduling jitter from the
1935 // composition and present times, which often have >1ms of jitter.
1936 // Reducing jitter is important if an app attempts to extrapolate
1937 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001938 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001940 nsecs_t bias = stats.vsyncPeriod / 2;
1941 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1942 nsecs_t snappedCompositeToPresentLatency =
1943 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944
David Sodman99974d22017-11-28 12:04:33 -08001945 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001946 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1947 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001948 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949}
1950
Ady Abraham8164d482019-01-11 14:47:59 -08001951// debug patch for b/119477596 - add stack guards to catch stack
1952// corruptions and disable clang optimizations.
1953// The code below is temporary and planned to be removed once stack
1954// corruptions are found.
1955#pragma clang optimize off
1956class StackGuard {
1957public:
1958 StackGuard(const char* name, const char* func, int line) {
1959 guarders.reserve(MIN_CAPACITY);
1960 guarders.push_back({this, name, func, line});
1961 validate();
1962 }
1963 ~StackGuard() {
1964 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1965 if (i->guard == this) {
1966 guarders.erase(i);
1967 break;
1968 }
1969 }
1970 }
1971
1972 static void validate() {
1973 for (const auto& guard : guarders) {
1974 if (guard.guard->cookie != COOKIE_VALUE) {
1975 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1976 CallStack stack(LOG_TAG);
1977 abort();
1978 }
1979 }
1980 }
1981
1982private:
1983 uint64_t cookie = COOKIE_VALUE;
1984 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
1985 static constexpr size_t MIN_CAPACITY = 16;
1986
1987 struct GuarderElement {
1988 StackGuard* guard;
1989 const char* name;
1990 const char* func;
1991 int line;
1992 };
1993
1994 static std::vector<GuarderElement> guarders;
1995};
1996std::vector<StackGuard::GuarderElement> StackGuard::guarders;
1997
1998#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
1999
2000#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002001void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002{
Ady Abraham8164d482019-01-11 14:47:59 -08002003 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 ATRACE_CALL();
2005 ALOGV("postComposition");
2006
Brian Anderson3546a3f2016-07-14 11:51:14 -07002007 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002008 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002009 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002010 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002011 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002012 }
Ady Abraham8164d482019-01-11 14:47:59 -08002013 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002014
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002015 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002016 const auto displayDevice = getDefaultDisplayDeviceLocked();
2017 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018
David Sodman73beded2017-11-15 11:56:06 -08002019 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002020 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002021 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2022
Lloyd Pique32cbe282018-10-19 13:09:22 -07002023 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002024 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002025 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2026 ->getRenderSurface()
2027 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002028 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002029 } else {
2030 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2031 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002032
Ady Abraham8164d482019-01-11 14:47:59 -08002033 ASSERT_ON_STACK_GUARD();
2034
David Sodman73beded2017-11-15 11:56:06 -08002035 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002036 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2037 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002038 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002039 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002040 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
Ana Krulece588e312018-09-18 12:32:24 -07002042 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002043 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002044 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002045
Ady Abraham8164d482019-01-11 14:47:59 -08002046 ASSERT_ON_STACK_GUARD();
2047
David Sodman2b406362017-12-15 13:33:47 -08002048 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002049 // when we started doing work for this frame, but that should be okay
2050 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002051 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002052 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002053 DEFINE_STACK_GUARD(compositorTiming);
2054
Brian Andersond0010582017-03-07 13:20:31 -08002055 {
David Sodman99974d22017-11-28 12:04:33 -08002056 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002057 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002058 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002059
2060 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002061 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062
Robert Carr2047fae2016-11-28 14:09:09 -08002063 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002064 bool frameLatched =
2065 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2066 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002067 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002068 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002069 recordBufferingStats(layer->getName().string(),
2070 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002071 }
Ady Abraham8164d482019-01-11 14:47:59 -08002072 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002073 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002074
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002075 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002076 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002077 mScheduler->addPresentFence(presentFenceTime);
2078 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002079 }
2080
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002081 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002082 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2083 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002084 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002085 }
2086 }
2087
Ady Abraham8164d482019-01-11 14:47:59 -08002088 ASSERT_ON_STACK_GUARD();
2089
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002090 if (mAnimCompositionPending) {
2091 mAnimCompositionPending = false;
2092
Brian Anderson4e606e32017-03-16 15:34:57 -07002093 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002094 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002095 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002096
2097 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002098 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002099 // The HWC doesn't support present fences, so use the refresh
2100 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 const nsecs_t presentTime =
2102 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002103 DEFINE_STACK_GUARD(presentTime);
2104
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002105 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002106 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002107 }
2108 mAnimFrameTracker.advanceFrame();
2109 }
Dan Stozab90cf072015-03-05 11:05:59 -08002110
Ady Abraham8164d482019-01-11 14:47:59 -08002111 ASSERT_ON_STACK_GUARD();
2112
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002113 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002114 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002115 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002116 }
2117
Ady Abraham8164d482019-01-11 14:47:59 -08002118 ASSERT_ON_STACK_GUARD();
2119
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002120 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002121
Ady Abraham8164d482019-01-11 14:47:59 -08002122 ASSERT_ON_STACK_GUARD();
2123
Lloyd Pique32cbe282018-10-19 13:09:22 -07002124 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2125 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002126 return;
2127 }
2128
2129 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002130 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002131 if (mHasPoweredOff) {
2132 mHasPoweredOff = false;
2133 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002134 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002135 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002136 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002137 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002138 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2139 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002140 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002141 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002142 }
David Sodman4a36e932017-11-07 14:29:47 -08002143 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002144
2145 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002146 }
David Sodman4a36e932017-11-07 14:29:47 -08002147 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002148 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002149
2150 {
2151 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002152 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002153 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002154 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002155 if (refillCount > 0) {
2156 const size_t offset = mTexturePool.size();
2157 mTexturePool.resize(mTexturePoolSize);
2158 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2159 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2160 }
Ady Abraham8164d482019-01-11 14:47:59 -08002161 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002162 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002163
Marissa Wallfda30bb2018-10-12 11:34:28 -07002164 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002165 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002166
2167 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002168}
Ady Abraham8164d482019-01-11 14:47:59 -08002169#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002170
Vishnu Nair4351ad52019-02-11 14:13:02 -08002171void SurfaceFlinger::computeLayerBounds() {
2172 for (const auto& pair : mDisplays) {
2173 const auto& displayDevice = pair.second;
2174 const auto display = displayDevice->getCompositionDisplay();
2175 for (const auto& layer : mDrawingState.layersSortedByZ) {
2176 // only consider the layers on the given layer stack
2177 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002178 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002179 }
2180
2181 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2182 }
2183 }
2184}
2185
Mathias Agopiancd60f992012-08-16 16:28:27 -07002186void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 ATRACE_CALL();
2188 ALOGV("rebuildLayerStacks");
2189
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002190 // We need to clear these out now as these may be holding on to a
2191 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2192 // also holds a reference. When the set of visible layers is recomputed,
2193 // some layers may be destroyed if the only thing keeping them alive was
2194 // that list of visible layers associated with each display. The layer
2195 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2196 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2197 for (const auto& [token, display] : mDisplays) {
2198 getBE().mCompositionInfo[token].clear();
2199 }
2200
Mathias Agopiancd60f992012-08-16 16:28:27 -07002201 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002202 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002203 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 mVisibleRegionsDirty = false;
2205 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002206
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002207 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002208 const auto& displayDevice = pair.second;
2209 auto display = displayDevice->getCompositionDisplay();
2210 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 Region opaqueRegion;
2212 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002213 compositionengine::Output::OutputLayers layersSortedByZ;
2214 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002215 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002216 const ui::Transform& tr = displayState.transform;
2217 const Rect bounds = displayState.bounds;
2218 if (displayState.isEnabled) {
2219 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002220
Jeff Sharkey76488112017-02-27 14:15:18 -07002221 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002222 auto compositionLayer = layer->getCompositionLayer();
2223 if (compositionLayer == nullptr) {
2224 return;
2225 }
2226
Lloyd Pique32cbe282018-10-19 13:09:22 -07002227 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002228 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2229 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2230
Lloyd Pique07e33212018-12-18 16:33:37 -08002231 bool needsOutputLayer = false;
2232
Lloyd Piqueef36b002019-01-23 17:52:04 -08002233 if (display->belongsInOutput(layer->getLayerStack(),
2234 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002235 Region drawRegion(tr.transform(
2236 layer->visibleNonTransparentRegion));
2237 drawRegion.andSelf(bounds);
2238 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002239 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 }
Chia-I Wu83806892017-11-16 10:50:20 -08002241 }
2242
Lloyd Pique07e33212018-12-18 16:33:37 -08002243 if (needsOutputLayer) {
2244 layersSortedByZ.emplace_back(
2245 display->getOrCreateOutputLayer(displayId, compositionLayer,
2246 layerFE));
2247 deprecated_layersSortedByZ.add(layer);
2248
2249 auto& outputLayerState = layersSortedByZ.back()->editState();
2250 outputLayerState.visibleRegion =
2251 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2252 } else if (displayId) {
2253 // For layers that are being removed from a HWC display,
2254 // and that have queued frames, add them to a a list of
2255 // released layers so we can properly set a fence.
2256 bool hasExistingOutputLayer =
2257 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2258 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2259 mLayersWithQueuedFrames.cend(),
2260 layer) != mLayersWithQueuedFrames.cend();
2261
2262 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002263 layersNeedingFences.add(layer);
2264 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002265 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002266 });
2267 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002268
2269 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2270
2271 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002272 displayDevice->setLayersNeedingFences(layersNeedingFences);
2273
2274 Region undefinedRegion{bounds};
2275 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2276
2277 display->editState().undefinedRegion = undefinedRegion;
2278 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002279 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002280 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002281}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002282
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002284// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002285// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002287// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288// The returned HDR data space is one of
2289// - Dataspace::UNKNOWN
2290// - Dataspace::BT2020_HLG
2291// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002292Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2293 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002294 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002295 *outHdrDataSpace = Dataspace::UNKNOWN;
2296
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002298 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002299 case Dataspace::V0_SCRGB:
2300 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002301 case Dataspace::BT2020:
2302 case Dataspace::BT2020_ITU:
2303 case Dataspace::BT2020_LINEAR:
2304 case Dataspace::DISPLAY_BT2020:
2305 bestDataSpace = Dataspace::DISPLAY_BT2020;
2306 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002308 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002309 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002310 case Dataspace::BT2020_PQ:
2311 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002312 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002314 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002315 case Dataspace::BT2020_HLG:
2316 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002317 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318 // When there's mixed PQ content and HLG content, we set the HDR
2319 // data space to be BT2020_PQ and convert HLG to PQ.
2320 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2321 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002322 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323 break;
2324 default:
2325 break;
2326 }
Romain Guy54f154a2017-10-24 21:40:32 +01002327 }
2328
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002330}
2331
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2334 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2336 *outMode = ColorMode::NATIVE;
2337 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002339 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002340 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002341
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002342 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002344
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002345 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2346
Peiyong Lina3ea5592019-02-10 14:45:00 -08002347 switch (mForceColorMode) {
2348 case ColorMode::SRGB:
2349 bestDataSpace = Dataspace::V0_SRGB;
2350 break;
2351 case ColorMode::DISPLAY_P3:
2352 bestDataSpace = Dataspace::DISPLAY_P3;
2353 break;
2354 default:
2355 break;
2356 }
2357
Peiyong Lindfde5112018-06-05 10:58:41 -07002358 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002359 const bool isHdr =
2360 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002361 if (isHdr) {
2362 bestDataSpace = hdrDataSpace;
2363 }
2364
Chia-I Wu0d711262018-05-21 15:19:35 -07002365 RenderIntent intent;
2366 switch (mDisplayColorSetting) {
2367 case DisplayColorSetting::MANAGED:
2368 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002369 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002370 break;
2371 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002372 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002373 break;
2374 default: // vendor display color setting
2375 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2376 break;
2377 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002378
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002379 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002380}
2381
Lloyd Pique32cbe282018-10-19 13:09:22 -07002382void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2383 auto display = displayDevice->getCompositionDisplay();
2384 const auto& displayState = display->getState();
2385
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002386 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002387 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2388 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002389
David Sodmanfa9b2af2017-12-24 13:28:59 -08002390 // If nothing has changed (!dirty), don't recompose.
2391 // If something changed, but we don't currently have any visible layers,
2392 // and didn't when we last did a composition, then skip it this time.
2393 // The second rule does two things:
2394 // - When all layers are removed from a display, we'll emit one black
2395 // frame, then nothing more until we get new layers.
2396 // - When a display is created with a private layer stack, we won't
2397 // emit any black frames until a layer is added to the layer stack.
2398 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002399
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 const char flagPrefix[] = {'-', '+'};
2401 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002402 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2403 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2404 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2405 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002406
Lloyd Pique31cb2942018-10-19 17:23:03 -07002407 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002408
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002411 }
2412}
2413
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2415 auto display = displayDevice->getCompositionDisplay();
2416 const auto& displayState = display->getState();
2417
2418 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002419 return;
David Sodman2b406362017-12-15 13:33:47 -08002420 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002421
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002422 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002424 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002425}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002426
Lloyd Pique32cbe282018-10-19 13:09:22 -07002427void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002428 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002429 ALOGV("doComposition");
2430
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 auto display = displayDevice->getCompositionDisplay();
2432 const auto& displayState = display->getState();
2433
2434 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002435 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002436 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002437
David Sodmanfa9b2af2017-12-24 13:28:59 -08002438 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002440
Lloyd Pique32cbe282018-10-19 13:09:22 -07002441 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002442 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002443 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002445}
2446
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447void SurfaceFlinger::postFrame()
2448{
2449 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 const auto display = getDefaultDisplayDeviceLocked();
2451 if (display && getHwComposer().isConnected(*display->getId())) {
2452 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002453 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2454 logFrameStats();
2455 }
2456 }
2457}
2458
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002460 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002461 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002462
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 auto display = displayDevice->getCompositionDisplay();
2464 const auto& displayState = display->getState();
2465 const auto displayId = display->getId();
2466
David Sodmanfa9b2af2017-12-24 13:28:59 -08002467 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002468
Lloyd Pique32cbe282018-10-19 13:09:22 -07002469 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002470 if (displayId) {
2471 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002472 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002473 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002475 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002476
Chia-I Wu7b549592017-11-15 09:14:57 -08002477 // The layer buffer from the previous frame (if any) is released
2478 // by HWC only when the release fence from this frame (if any) is
2479 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002480 if (displayId && layer->hasHwcLayer(displayDevice)) {
2481 releaseFence =
2482 getHwComposer().getLayerReleaseFence(*displayId,
2483 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002484 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002485
2486 // If the layer was client composited in the previous frame, we
2487 // need to merge with the previous client target acquire fence.
2488 // Since we do not track that, always merge with the current
2489 // client target acquire fence when it is available, even though
2490 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002491 if (layer->getCompositionType(displayDevice) ==
2492 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002493 releaseFence =
2494 Fence::merge("LayerRelease", releaseFence,
2495 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002496 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002497
David Sodman15094112018-10-11 09:39:37 -07002498 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 }
Chia-I Wu83806892017-11-16 10:50:20 -08002500
2501 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002503 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002504 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002506 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002507 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002508 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002509 }
2510 }
2511
Dominik Laskowski075d3172018-05-24 15:50:06 -07002512 if (displayId) {
2513 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002514 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002515 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516}
2517
Mathias Agopian87baae12012-07-31 12:38:26 -07002518void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519{
Mathias Agopian841cde52012-03-01 15:44:37 -08002520 ATRACE_CALL();
2521
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002522 // here we keep a copy of the drawing state (that is the state that's
2523 // going to be overwritten by handleTransactionLocked()) outside of
2524 // mStateLock so that the side-effects of the State assignment
2525 // don't happen with mStateLock held (which can cause deadlocks).
2526 State drawingState(mDrawingState);
2527
Mathias Agopianca4d3602011-05-19 15:38:14 -07002528 Mutex::Autolock _l(mStateLock);
2529 const nsecs_t now = systemTime();
2530 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531
Mathias Agopianca4d3602011-05-19 15:38:14 -07002532 // Here we're guaranteed that some transaction flags are set
2533 // so we can call handleTransactionLocked() unconditionally.
2534 // We call getTransactionFlags(), which will also clear the flags,
2535 // with mStateLock held to guarantee that mCurrentState won't change
2536 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002537
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002538 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002539 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002540 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002541
Mathias Agopianca4d3602011-05-19 15:38:14 -07002542 mLastTransactionTime = systemTime() - now;
2543 mDebugInTransaction = 0;
2544 invalidateHwcGeometry();
2545 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002546}
2547
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2549 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 const std::optional<DisplayIdentificationInfo> info =
2551 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554 continue;
2555 }
2556
Lloyd Piqueba04e622017-12-14 17:11:26 -08002557 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002559 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002560 mPhysicalDisplayTokens[info->id] = new BBinder();
2561 DisplayDeviceState state;
2562 state.displayId = info->id;
2563 state.isSecure = true; // All physical displays are currently considered secure.
2564 state.displayName = info->name;
2565 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2566 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002567 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002568 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002569 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002570
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2572 if (index >= 0) {
2573 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2574 mInterceptor->saveDisplayDeletion(state.sequenceId);
2575 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002576 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002578 }
2579
2580 processDisplayChangesLocked();
2581 }
2582
2583 mPendingHotplugEvents.clear();
2584}
2585
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002586void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002587 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2588 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002589}
2590
Lloyd Pique99d3da52018-01-22 17:48:03 -08002591sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002592 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002593 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 const sp<IGraphicBufferProducer>& producer) {
2595 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002596 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002598 creationArgs.isSecure = state.isSecure;
2599 creationArgs.displaySurface = dispSurface;
2600 creationArgs.hasWideColorGamut = false;
2601 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002602
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002603 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 creationArgs.isPrimary = isInternalDisplay;
2605
2606 if (useColorManagement && displayId) {
2607 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002609 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002610 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002612
Dominik Laskowski7e045462018-05-30 13:02:02 -07002613 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002614 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002615 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 }
tangrobin6753a022018-08-10 10:58:54 +08002617 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002618
Dominik Laskowski075d3172018-05-24 15:50:06 -07002619 if (displayId) {
2620 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002621 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002623 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624
Lloyd Pique90c115d2018-09-18 21:39:42 -07002625 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002627 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002628
Lloyd Pique99d3da52018-01-22 17:48:03 -08002629 // Make sure that composition can never be stalled by a virtual display
2630 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002631 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002632 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2634 }
2635
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 creationArgs.displayInstallOrientation =
2637 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002638
Lloyd Pique99d3da52018-01-22 17:48:03 -08002639 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002640 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641
Lloyd Pique90c115d2018-09-18 21:39:42 -07002642 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643
2644 if (maxFrameBufferAcquiredBuffers >= 3) {
2645 nativeWindowSurface->preallocateBuffers();
2646 }
2647
2648 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002649 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002650 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002652 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002654 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2655 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002656 if (!state.isVirtual()) {
2657 LOG_ALWAYS_FATAL_IF(!displayId);
2658 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002659 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002660
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002661 display->setLayerStack(state.layerStack);
2662 display->setProjection(state.orientation, state.viewport, state.frame);
2663 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002665 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666}
2667
Lloyd Pique347200f2017-12-14 17:00:15 -08002668void SurfaceFlinger::processDisplayChangesLocked() {
2669 // here we take advantage of Vector's copy-on-write semantics to
2670 // improve performance by skipping the transaction entirely when
2671 // know that the lists are identical
2672 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2673 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2674 if (!curr.isIdenticalTo(draw)) {
2675 mVisibleRegionsDirty = true;
2676 const size_t cc = curr.size();
2677 size_t dc = draw.size();
2678
2679 // find the displays that were removed
2680 // (ie: in drawing state but not in current state)
2681 // also handle displays that changed
2682 // (ie: displays that are in both lists)
2683 for (size_t i = 0; i < dc;) {
2684 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2685 if (j < 0) {
2686 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002687 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002688 // Save display ID before disconnecting.
2689 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002690 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002691
2692 if (!display->isVirtual()) {
2693 LOG_ALWAYS_FATAL_IF(!displayId);
2694 dispatchDisplayHotplugEvent(displayId->value, false);
2695 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002697
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002698 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002699 } else {
2700 // this display is in both lists. see if something changed.
2701 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2704 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2705 if (state_binder != draw_binder) {
2706 // changing the surface is like destroying and
2707 // recreating the DisplayDevice, so we just remove it
2708 // from the drawing state, so that it get re-added
2709 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002711 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002713 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 mDrawingState.displays.removeItemsAt(i);
2715 dc--;
2716 // at this point we must loop to the next item
2717 continue;
2718 }
2719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002720 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 }
2724 if ((state.orientation != draw[i].orientation) ||
2725 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002726 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002727 }
2728 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 }
2731 }
2732 }
2733 ++i;
2734 }
2735
2736 // find displays that were added
2737 // (ie: in current state but not in drawing state)
2738 for (size_t i = 0; i < cc; i++) {
2739 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2740 const DisplayDeviceState& state(curr[i]);
2741
Lloyd Pique542307f2018-10-19 13:24:08 -07002742 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002743 sp<IGraphicBufferProducer> producer;
2744 sp<IGraphicBufferProducer> bqProducer;
2745 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002746 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002747
Dominik Laskowski075d3172018-05-24 15:50:06 -07002748 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002749 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 // Virtual displays without a surface are dormant:
2751 // they have external state (layer stack, projection,
2752 // etc.) but no internal state (i.e. a DisplayDevice).
2753 if (state.surface != nullptr) {
2754 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002755 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002756 int width = 0;
2757 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2758 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2759 int height = 0;
2760 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2761 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2762 int intFormat = 0;
2763 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2764 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002765 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002766
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 displayId =
2768 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002769 }
2770
2771 // TODO: Plumb requested format back up to consumer
2772
2773 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002774 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 bqProducer, bqConsumer,
2776 state.displayName);
2777
2778 dispSurface = vds;
2779 producer = vds;
2780 }
2781 } else {
2782 ALOGE_IF(state.surface != nullptr,
2783 "adding a supported display, but rendering "
2784 "surface is provided (%p), ignoring it",
2785 state.surface.get());
2786
Dominik Laskowski075d3172018-05-24 15:50:06 -07002787 displayId = state.displayId;
2788 LOG_ALWAYS_FATAL_IF(!displayId);
2789 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002790 producer = bqProducer;
2791 }
2792
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002793 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002795 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002796 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002797 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002798 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002799 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002800 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002801 }
2802 }
2803 }
2804 }
2805 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002806
2807 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002808}
2809
Mathias Agopian87baae12012-07-31 12:38:26 -07002810void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002811{
Dan Stoza7dde5992015-05-22 09:51:44 -07002812 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002813 mCurrentState.traverseInZOrder([](Layer* layer) {
2814 layer->notifyAvailableFrames();
2815 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002816
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 /*
2818 * Traversal of the children
2819 * (perform the transaction for each of them if needed)
2820 */
2821
Mathias Agopian3559b072012-08-15 13:46:03 -07002822 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002823 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002825 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826
2827 const uint32_t flags = layer->doTransaction(0);
2828 if (flags & Layer::eVisibleRegion)
2829 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002830
2831 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002832 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002833 }
Robert Carr2047fae2016-11-28 14:09:09 -08002834 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 }
2836
2837 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002838 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002839 */
2840
Mathias Agopiane57f2922012-08-09 16:29:12 -07002841 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002842 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002843 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002844 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002846 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002847 // The transform hint might have changed for some layers
2848 // (either because a display has changed, or because a layer
2849 // as changed).
2850 //
2851 // Walk through all the layers in currentLayers,
2852 // and update their transform hint.
2853 //
2854 // If a layer is visible only on a single display, then that
2855 // display is used to calculate the hint, otherwise we use the
2856 // default display.
2857 //
2858 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2859 // the hint is set before we acquire a buffer from the surface texture.
2860 //
2861 // NOTE: layer transactions have taken place already, so we use their
2862 // drawing state. However, SurfaceFlinger's own transaction has not
2863 // happened yet, so we must use the current state layer list
2864 // (soon to become the drawing state list).
2865 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002866 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002867 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002868 bool first = true;
2869 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002870 // NOTE: we rely on the fact that layers are sorted by
2871 // layerStack first (so we don't have to traverse the list
2872 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002873 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002874 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002875 currentlayerStack = layerStack;
2876 // figure out if this layerstack is mirrored
2877 // (more than one display) if so, pick the default display,
2878 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002879 hintDisplay = nullptr;
2880 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002881 if (display->getCompositionDisplay()
2882 ->belongsInOutput(layer->getLayerStack(),
2883 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002884 if (hintDisplay) {
2885 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002886 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002887 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002889 }
2890 }
2891 }
2892 }
Chet Haase91d25932013-04-11 15:24:55 -07002893
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002894 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002895 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2896 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002897
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002898 // could be null when this layer is using a layerStack
2899 // that is not visible on any display. Also can occur at
2900 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002901 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002902 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002903
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002904 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002905 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002906 if (hintDisplay) {
2907 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002908 }
Robert Carr2047fae2016-11-28 14:09:09 -08002909
2910 first = false;
2911 });
Mathias Agopian84300952012-11-21 16:02:13 -08002912 }
2913
2914
Mathias Agopian3559b072012-08-15 13:46:03 -07002915 /*
2916 * Perform our own transaction if needed
2917 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918
2919 if (mLayersAdded) {
2920 mLayersAdded = false;
2921 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002922 mVisibleRegionsDirty = true;
2923 }
2924
2925 // some layers might have been removed, so
2926 // we need to update the regions they're exposing.
2927 if (mLayersRemoved) {
2928 mLayersRemoved = false;
2929 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002932 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002933 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002934 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002935 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002936 }
Robert Carr2047fae2016-11-28 14:09:09 -08002937 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938 }
2939
Vishnu Nairec0ab382019-02-13 15:32:56 -08002940 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002941 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002942}
2943
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002944void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002945 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002946 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002947 return;
2948 }
2949
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002950 if (mVisibleRegionsDirty || mInputInfoChanged) {
2951 mInputInfoChanged = false;
2952 updateInputWindowInfo();
2953 }
2954
2955 executeInputWindowCommands();
2956}
2957
2958void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002959 Vector<InputWindowInfo> inputHandles;
2960
2961 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2962 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002963 // When calculating the screen bounds we ignore the transparent region since it may
2964 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002965 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002966 }
2967 });
2968 mInputFlinger->setInputWindows(inputHandles);
2969}
2970
Vishnu Nairec0ab382019-02-13 15:32:56 -08002971void SurfaceFlinger::commitInputWindowCommands() {
2972 mInputWindowCommands.merge(mPendingInputWindowCommands);
2973 mPendingInputWindowCommands.clear();
2974}
2975
chaviwfbe5d9c2018-12-26 12:23:37 -08002976void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002977 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2978 if (transferTouchFocusCommand.fromToken != nullptr &&
2979 transferTouchFocusCommand.toToken != nullptr &&
2980 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2981 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2982 transferTouchFocusCommand.toToken);
2983 }
2984 }
2985
2986 mInputWindowCommands.clear();
2987}
2988
Riley Andrews03414a12014-07-01 14:22:59 -07002989void SurfaceFlinger::updateCursorAsync()
2990{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002991 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002992 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002993 continue;
2994 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002996 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2997 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002998 }
2999 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000}
3001
chaviw61626f22018-11-15 16:26:27 -08003002void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3003 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003004 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003005 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003006 }
3007 layer->releasePendingBuffer(systemTime());
3008}
3009
Mathias Agopian4fec8732012-06-29 14:12:52 -07003010void SurfaceFlinger::commitTransaction()
3011{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003012 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003013 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003014 for (const auto& l : mLayersPendingRemoval) {
3015 recordBufferingStats(l->getName().string(),
3016 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003017
Lloyd Pique07e33212018-12-18 16:33:37 -08003018 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003019 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003020 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003021 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003022 }
3023 mLayersPendingRemoval.clear();
3024 }
3025
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003026 // If this transaction is part of a window animation then the next frame
3027 // we composite should be considered an animation as well.
3028 mAnimCompositionPending = mAnimTransactionPending;
3029
Mathias Agopian4fec8732012-06-29 14:12:52 -07003030 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003031 // clear the "changed" flags in current state
3032 mCurrentState.colorMatrixChanged = false;
3033
Robert Carr1f0a16a2016-10-24 16:27:39 -07003034 mDrawingState.traverseInZOrder([](Layer* layer) {
3035 layer->commitChildList();
3036 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003037 mTransactionPending = false;
3038 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040}
3041
Lloyd Pique32cbe282018-10-19 13:09:22 -07003042void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003043 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003044 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003045 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003046
Lloyd Pique32cbe282018-10-19 13:09:22 -07003047 auto display = displayDevice->getCompositionDisplay();
3048
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 Region aboveOpaqueLayers;
3050 Region aboveCoveredLayers;
3051 Region dirty;
3052
Mathias Agopian87baae12012-07-31 12:38:26 -07003053 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054
Robert Carr2047fae2016-11-28 14:09:09 -08003055 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003056 // start with the whole surface at its current location
3057 const Layer::State& s(layer->getDrawingState());
3058
Jesse Hall01e29052013-02-19 16:13:35 -08003059 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003060 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003061 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003062 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003063
Mathias Agopianab028732010-03-16 16:41:46 -07003064 /*
3065 * opaqueRegion: area of a surface that is fully opaque.
3066 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003068
3069 /*
3070 * visibleRegion: area of a surface that is visible on screen
3071 * and not fully transparent. This is essentially the layer's
3072 * footprint minus the opaque regions above it.
3073 * Areas covered by a translucent surface are considered visible.
3074 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003076
3077 /*
3078 * coveredRegion: area of a surface that is covered by all
3079 * visible regions above it (which includes the translucent areas).
3080 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003082
Jesse Halla8026d22012-09-25 13:25:04 -07003083 /*
3084 * transparentRegion: area of a surface that is hinted to be completely
3085 * transparent. This is only used to tell when the layer has no visible
3086 * non-transparent regions and can be removed from the layer list. It
3087 * does not affect the visibleRegion of this layer or any layers
3088 * beneath it. The hint may not be correct if apps don't respect the
3089 * SurfaceView restrictions (which, sadly, some don't).
3090 */
3091 Region transparentRegion;
3092
Mathias Agopianab028732010-03-16 16:41:46 -07003093
3094 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003095 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003096 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003097 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003098
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003100 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003101 if (!visibleRegion.isEmpty()) {
3102 // Remove the transparent area from the visible region
3103 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003104 if (tr.preserveRects()) {
3105 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003106 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003107 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003108 // transformation too complex, can't do the
3109 // transparent region optimization.
3110 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003111 }
Mathias Agopianab028732010-03-16 16:41:46 -07003112 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113
Mathias Agopianab028732010-03-16 16:41:46 -07003114 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003115 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003116 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003117 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003118 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003119 // the opaque region is the layer's footprint
3120 opaqueRegion = visibleRegion;
3121 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122 }
3123 }
3124
Robert Carre5f4f692018-01-12 13:12:28 -08003125 if (visibleRegion.isEmpty()) {
3126 layer->clearVisibilityRegions();
3127 return;
3128 }
3129
Mathias Agopianab028732010-03-16 16:41:46 -07003130 // Clip the covered region to the visible region
3131 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3132
3133 // Update aboveCoveredLayers for next (lower) layer
3134 aboveCoveredLayers.orSelf(visibleRegion);
3135
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003136 // subtract the opaque region covered by the layers above us
3137 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138
3139 // compute this layer's dirty region
3140 if (layer->contentDirty) {
3141 // we need to invalidate the whole region
3142 dirty = visibleRegion;
3143 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003144 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 layer->contentDirty = false;
3146 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003147 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003148 * the exposed region consists of two components:
3149 * 1) what's VISIBLE now and was COVERED before
3150 * 2) what's EXPOSED now less what was EXPOSED before
3151 *
3152 * note that (1) is conservative, we start with the whole
3153 * visible region but only keep what used to be covered by
3154 * something -- which mean it may have been exposed.
3155 *
3156 * (2) handles areas that were not covered by anything but got
3157 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003158 */
Mathias Agopianab028732010-03-16 16:41:46 -07003159 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003160 const Region oldVisibleRegion = layer->visibleRegion;
3161 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003162 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3163 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 }
3165 dirty.subtractSelf(aboveOpaqueLayers);
3166
3167 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003168 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169
Mathias Agopianab028732010-03-16 16:41:46 -07003170 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003172
Jesse Halla8026d22012-09-25 13:25:04 -07003173 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174 layer->setVisibleRegion(visibleRegion);
3175 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003176 layer->setVisibleNonTransparentRegion(
3177 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003178 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179
Mathias Agopian87baae12012-07-31 12:38:26 -07003180 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181}
3182
Chia-I Wuab0c3192017-08-01 11:29:00 -07003183void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003184 for (const auto& [token, displayDevice] : mDisplays) {
3185 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003186 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003187 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003188 }
3189 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003190}
3191
Daniel Solomon42d04562019-01-20 21:03:19 -08003192void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3193 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3194 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3195 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3196 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3197 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3198 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3199 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3200 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3201 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3202 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3203 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3204 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3205}
3206
Dan Stoza6b9454d2014-11-07 16:00:59 -08003207bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003209 ALOGV("handlePageFlip");
3210
Brian Andersond6927fb2016-07-23 23:37:30 -07003211 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212
Mathias Agopian4fec8732012-06-29 14:12:52 -07003213 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003214 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003215 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003216
3217 // Store the set of layers that need updates. This set must not change as
3218 // buffers are being latched, as this could result in a deadlock.
3219 // Example: Two producers share the same command stream and:
3220 // 1.) Layer 0 is latched
3221 // 2.) Layer 0 gets a new frame
3222 // 2.) Layer 1 gets a new frame
3223 // 3.) Layer 1 is latched.
3224 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3225 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003227 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003228 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003229 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003230 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003231 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003232 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003233 } else {
3234 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003235 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003236 } else {
3237 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003238 }
Robert Carr2047fae2016-11-28 14:09:09 -08003239 });
3240
Lloyd Piquef2c79392018-12-20 16:23:33 -08003241 if (!mLayersWithQueuedFrames.empty()) {
3242 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3243 // writes to Layer current state. See also b/119481871
3244 Mutex::Autolock lock(mStateLock);
3245
3246 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003247 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003248 mLayersPendingRefresh.push_back(layer);
3249 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003250 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003251 if (layer->isBufferLatched()) {
3252 newDataLatched = true;
3253 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003254 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003255 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003256
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003257 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003258
3259 // If we will need to wake up at some time in the future to deal with a
3260 // queued frame that shouldn't be displayed during this vsync period, wake
3261 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003262 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263 signalLayerUpdate();
3264 }
3265
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003266 // enter boot animation on first buffer latch
3267 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3268 ALOGI("Enter boot animation");
3269 mBootStage = BootStage::BOOTANIMATION;
3270 }
3271
Dan Stoza6b9454d2014-11-07 16:00:59 -08003272 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003273 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274}
3275
Mathias Agopianad456f92011-01-13 17:53:01 -08003276void SurfaceFlinger::invalidateHwcGeometry()
3277{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003278 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003279}
3280
Lloyd Pique32cbe282018-10-19 13:09:22 -07003281void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003282 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003283 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003284 // We only need to actually compose the display if:
3285 // 1) It is being handled by hardware composer, which may need this to
3286 // keep its virtual display state machine in sync, or
3287 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003288 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003289 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003290 return;
3291 }
3292
Dan Stoza9e56aa02015-11-02 13:00:03 -08003293 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003294 base::unique_fd readyFence;
3295 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003296
3297 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003298 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299}
3300
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003301bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3302 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003303 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003305
Lloyd Pique32cbe282018-10-19 13:09:22 -07003306 auto display = displayDevice->getCompositionDisplay();
3307 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003308 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003309
3310 const Region bounds(displayState.bounds);
3311 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003312 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003313 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003314
Peiyong Lind3788632018-09-18 16:01:31 -07003315 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003316 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003317
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003318 renderengine::DisplaySettings clientCompositionDisplay;
3319 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3320 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003321
Dan Stoza9e56aa02015-11-02 13:00:03 -08003322 if (hasClientComposition) {
3323 ALOGV("hasClientComposition");
3324
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003325 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003326
3327 if (buf == nullptr) {
3328 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3329 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003330 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003331 return false;
3332 }
3333
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003334 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3335 clientCompositionDisplay.clip = displayState.scissor;
3336 const ui::Transform& displayTransform = displayState.transform;
3337 mat4 m;
3338 m[0][0] = displayTransform[0][0];
3339 m[0][1] = displayTransform[0][1];
3340 m[0][3] = displayTransform[0][2];
3341 m[1][0] = displayTransform[1][0];
3342 m[1][1] = displayTransform[1][1];
3343 m[1][3] = displayTransform[1][2];
3344 m[3][0] = displayTransform[2][0];
3345 m[3][1] = displayTransform[2][1];
3346 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003347
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003348 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003349
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003350 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003351 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003352 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003353 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003354 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003355 clientCompositionDisplay.outputDataspace = outputDataspace;
3356 clientCompositionDisplay.maxLuminance =
3357 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003358
Lloyd Pique441d5042018-10-18 16:49:51 -07003359 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003360 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003361 getHwComposer()
3362 .hasDisplayCapability(displayId,
3363 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003364
Peiyong Lind3788632018-09-18 16:01:31 -07003365 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003366 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3367 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003368 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003369 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003370 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003371
Mathias Agopian85d751c2012-08-29 16:59:24 -07003372 /*
3373 * and then, render the layers targeted at the framebuffer
3374 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003375
Dan Stoza9e56aa02015-11-02 13:00:03 -08003376 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003377 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003378 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003379 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003380 const Region viewportRegion(displayState.viewport);
3381 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003382 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003383 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003384 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003385 switch (layer->getCompositionType(displayDevice)) {
3386 case Hwc2::IComposerClient::Composition::CURSOR:
3387 case Hwc2::IComposerClient::Composition::DEVICE:
3388 case Hwc2::IComposerClient::Composition::SIDEBAND:
3389 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003390 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003391 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003392 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003393 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003394 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003395 // never clear the very first layer since we're
3396 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003397 renderengine::LayerSettings layerSettings;
3398 Region dummyRegion;
3399 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3400 layerSettings);
3401
3402 if (prepared) {
3403 layerSettings.source.buffer.buffer = nullptr;
3404 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3405 layerSettings.alpha = half(0.0);
3406 layerSettings.disableBlending = true;
3407 clientCompositionLayers.push_back(layerSettings);
3408 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003409 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003410 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003411 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003412 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003413 renderengine::LayerSettings layerSettings;
3414 bool prepared =
3415 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3416 if (prepared) {
3417 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003418 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003419 break;
3420 }
3421 default:
3422 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003423 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003424 } else {
3425 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003426 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003427 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003428 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003429
Alec Mouri820c7402019-01-23 13:02:39 -08003430 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003431 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003432 clientCompositionDisplay.clearRegion = clearRegion;
3433 if (!debugRegion.isEmpty()) {
3434 Region::const_iterator it = debugRegion.begin();
3435 Region::const_iterator end = debugRegion.end();
3436 while (it != end) {
3437 const Rect& rect = *it++;
3438 renderengine::LayerSettings layerSettings;
3439 layerSettings.source.buffer.buffer = nullptr;
3440 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3441 layerSettings.geometry.boundaries = rect.toFloatRect();
3442 layerSettings.alpha = half(1.0);
3443 clientCompositionLayers.push_back(layerSettings);
3444 }
3445 }
3446 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3447 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003448 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003449 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450}
3451
Chia-I Wu28e3a252018-09-07 12:05:02 -07003452void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003453 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003454 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003455}
3456
Dan Stoza7d89d062015-04-30 13:29:25 -07003457status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003458 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003459 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003460 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003461 const sp<Layer>& parent,
3462 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003463{
Dan Stoza7d89d062015-04-30 13:29:25 -07003464 // add this layer to the current state list
3465 {
3466 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003467 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003468 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3469 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003470 return NO_MEMORY;
3471 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003472 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003473 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003474 } else if (parent == nullptr) {
3475 lbc->onRemovedFromCurrentState();
3476 } else if (parent->isRemovedFromCurrentState()) {
3477 parent->addChild(lbc);
3478 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003479 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003480 parent->addChild(lbc);
3481 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003482
Yiwei Zhang243b3782018-05-15 17:40:04 -07003483 if (gbc != nullptr) {
3484 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3485 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3486 mMaxGraphicBufferProducerListSize,
3487 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3488 mGraphicBufferProducerList.size(),
3489 mMaxGraphicBufferProducerListSize, mNumLayers);
3490 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003491 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003492 }
3493
Mathias Agopian96f08192010-06-02 23:28:45 -07003494 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003495 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003496
Dan Stoza7d89d062015-04-30 13:29:25 -07003497 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003498}
3499
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003500uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003501 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003502}
3503
Mathias Agopian3f844832013-08-07 21:24:32 -07003504uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003505 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506}
3507
Mathias Agopian3f844832013-08-07 21:24:32 -07003508uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003509 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003510}
3511
3512uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003513 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003514 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003515 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003516 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003517 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518 }
3519 return old;
3520}
3521
Marissa Wall713b63f2018-10-17 15:42:43 -07003522bool SurfaceFlinger::flushTransactionQueues() {
3523 Mutex::Autolock _l(mStateLock);
3524 auto it = mTransactionQueues.begin();
3525 while (it != mTransactionQueues.end()) {
3526 auto& [applyToken, transactionQueue] = *it;
3527
3528 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003529 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3530 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003531 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003532 break;
3533 }
Robert Carr14167e02019-02-13 13:50:55 -08003534 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003535 transactionQueue.pop();
3536 }
3537
3538 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3539 }
3540 return mTransactionQueues.empty();
3541}
3542
chaviwca27f252018-02-06 16:46:39 -08003543bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3544 for (const ComposerState& state : states) {
3545 // Here we need to check that the interface we're given is indeed
3546 // one of our own. A malicious client could give us a nullptr
3547 // IInterface, or one of its own or even one of our own but a
3548 // different type. All these situations would cause us to crash.
3549 if (state.client == nullptr) {
3550 return true;
3551 }
3552
3553 sp<IBinder> binder = IInterface::asBinder(state.client);
3554 if (binder == nullptr) {
3555 return true;
3556 }
3557
3558 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3559 return true;
3560 }
3561 }
3562 return false;
3563}
3564
Marissa Wall17b4e452018-12-26 16:32:34 -08003565bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3566 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003567 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003568 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3569 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3570 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3571 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3572 return false;
3573 }
3574
Marissa Wall713b63f2018-10-17 15:42:43 -07003575 for (const ComposerState& state : states) {
3576 const layer_state_t& s = state.state;
3577 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3578 continue;
3579 }
3580 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003581 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003582 }
3583 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003584 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003585}
3586
3587void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3588 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003589 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003590 const InputWindowCommands& inputWindowCommands,
3591 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003592 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003593
3594 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3595
Mathias Agopian698c0872011-06-28 19:09:31 -07003596 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003597
chaviwca27f252018-02-06 16:46:39 -08003598 if (containsAnyInvalidClientState(states)) {
3599 return;
3600 }
3601
Marissa Wall713b63f2018-10-17 15:42:43 -07003602 // If its TransactionQueue already has a pending TransactionState or if it is pending
3603 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003604 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003605 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3606 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003607 setTransactionFlags(eTransactionNeeded);
3608 return;
3609 }
3610
Robert Carr14167e02019-02-13 13:50:55 -08003611 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003612}
3613
3614void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003615 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003616 const InputWindowCommands& inputWindowCommands,
3617 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 uint32_t transactionFlags = 0;
3619
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003620 if (flags & eAnimation) {
3621 // For window updates that are part of an animation we must wait for
3622 // previous animation "frames" to be handled.
3623 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003624 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003625 if (CC_UNLIKELY(err != NO_ERROR)) {
3626 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003627 // caller after a few seconds.
3628 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3629 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003630 mAnimTransactionPending = false;
3631 break;
3632 }
3633 }
3634 }
3635
chaviwca27f252018-02-06 16:46:39 -08003636 for (const DisplayState& display : displays) {
3637 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003638 }
3639
Marissa Walle2ffb422018-10-12 11:33:52 -07003640 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003641 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003642 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003643 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003644 // If the state doesn't require a traversal and there are callbacks, send them now
3645 if (!(clientStateFlags & eTraversalNeeded)) {
3646 mTransactionCompletedThread.sendCallbacks();
3647 }
3648 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003649
chaviw273171b2018-12-26 11:46:30 -08003650 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3651
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003652 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3653 // anyway. This can be used as a flush mechanism for previous async transactions.
3654 // Empty animation transaction can be used to simulate back-pressure, so also force a
3655 // transaction for empty animation transactions.
3656 if (transactionFlags == 0 &&
3657 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003658 transactionFlags = eTransactionNeeded;
3659 }
3660
Mathias Agopian386aa982011-11-07 21:58:03 -08003661 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003662 if (mInterceptor->isEnabled()) {
3663 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003664 }
Irvel468051e2016-06-13 16:44:44 -07003665
Mathias Agopian386aa982011-11-07 21:58:03 -08003666 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003667 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3668 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003669 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003670
3671 // if this is a synchronous transaction, wait for it to take effect
3672 // before returning.
3673 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003674 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003675 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003676 if (flags & eAnimation) {
3677 mAnimTransactionPending = true;
3678 }
3679 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003680 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3681 if (CC_UNLIKELY(err != NO_ERROR)) {
3682 // just in case something goes wrong in SF, return to the
3683 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003684 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3685 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003686 break;
3687 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003689 }
3690}
3691
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003692uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3693 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3694 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003695
Mathias Agopiane57f2922012-08-09 16:29:12 -07003696 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003697 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3698
3699 const uint32_t what = s.what;
3700 if (what & DisplayState::eSurfaceChanged) {
3701 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3702 state.surface = s.surface;
3703 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003704 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003705 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003706 if (what & DisplayState::eLayerStackChanged) {
3707 if (state.layerStack != s.layerStack) {
3708 state.layerStack = s.layerStack;
3709 flags |= eDisplayTransactionNeeded;
3710 }
3711 }
3712 if (what & DisplayState::eDisplayProjectionChanged) {
3713 if (state.orientation != s.orientation) {
3714 state.orientation = s.orientation;
3715 flags |= eDisplayTransactionNeeded;
3716 }
3717 if (state.frame != s.frame) {
3718 state.frame = s.frame;
3719 flags |= eDisplayTransactionNeeded;
3720 }
3721 if (state.viewport != s.viewport) {
3722 state.viewport = s.viewport;
3723 flags |= eDisplayTransactionNeeded;
3724 }
3725 }
3726 if (what & DisplayState::eDisplaySizeChanged) {
3727 if (state.width != s.width) {
3728 state.width = s.width;
3729 flags |= eDisplayTransactionNeeded;
3730 }
3731 if (state.height != s.height) {
3732 state.height = s.height;
3733 flags |= eDisplayTransactionNeeded;
3734 }
3735 }
3736
Mathias Agopiane57f2922012-08-09 16:29:12 -07003737 return flags;
3738}
3739
Robert Carr14167e02019-02-13 13:50:55 -08003740bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003741 IPCThreadState* ipc = IPCThreadState::self();
3742 const int pid = ipc->getCallingPid();
3743 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003744 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003745 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003746 return false;
3747 }
3748 return true;
3749}
3750
Robert Carr14167e02019-02-13 13:50:55 -08003751uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3752 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003753 const layer_state_t& s = composerState.state;
3754 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3755
Mathias Agopian13127d82013-03-05 17:47:11 -08003756 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003757 if (layer == nullptr) {
3758 return 0;
3759 }
3760
chaviw8b3871a2017-11-01 17:41:01 -07003761 uint32_t flags = 0;
3762
Garfield Tan8a3083e2018-12-03 13:21:07 -08003763 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003764 bool geometryAppliesWithResize =
3765 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003766
3767 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3768 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003769 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003770 layer->pushPendingState();
3771 }
3772
chaviw8b3871a2017-11-01 17:41:01 -07003773 if (what & layer_state_t::ePositionChanged) {
3774 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3775 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003776 }
chaviw8b3871a2017-11-01 17:41:01 -07003777 }
3778 if (what & layer_state_t::eLayerChanged) {
3779 // NOTE: index needs to be calculated before we update the state
3780 const auto& p = layer->getParent();
3781 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003782 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003783 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003784 mCurrentState.layersSortedByZ.removeAt(idx);
3785 mCurrentState.layersSortedByZ.add(layer);
3786 // we need traversal (state changed)
3787 // AND transaction (list changed)
3788 flags |= eTransactionNeeded|eTraversalNeeded;
3789 }
chaviw8b3871a2017-11-01 17:41:01 -07003790 } else {
3791 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003792 flags |= eTransactionNeeded|eTraversalNeeded;
3793 }
3794 }
chaviw8b3871a2017-11-01 17:41:01 -07003795 }
3796 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003797 // NOTE: index needs to be calculated before we update the state
3798 const auto& p = layer->getParent();
3799 if (p == nullptr) {
3800 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3801 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3802 mCurrentState.layersSortedByZ.removeAt(idx);
3803 mCurrentState.layersSortedByZ.add(layer);
3804 // we need traversal (state changed)
3805 // AND transaction (list changed)
3806 flags |= eTransactionNeeded|eTraversalNeeded;
3807 }
3808 } else {
3809 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3810 flags |= eTransactionNeeded|eTraversalNeeded;
3811 }
chaviw8b3871a2017-11-01 17:41:01 -07003812 }
3813 }
3814 if (what & layer_state_t::eSizeChanged) {
3815 if (layer->setSize(s.w, s.h)) {
3816 flags |= eTraversalNeeded;
3817 }
3818 }
3819 if (what & layer_state_t::eAlphaChanged) {
3820 if (layer->setAlpha(s.alpha))
3821 flags |= eTraversalNeeded;
3822 }
3823 if (what & layer_state_t::eColorChanged) {
3824 if (layer->setColor(s.color))
3825 flags |= eTraversalNeeded;
3826 }
Peiyong Lind3788632018-09-18 16:01:31 -07003827 if (what & layer_state_t::eColorTransformChanged) {
3828 if (layer->setColorTransform(s.colorTransform)) {
3829 flags |= eTraversalNeeded;
3830 }
3831 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003832 if (what & layer_state_t::eBackgroundColorChanged) {
3833 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3834 flags |= eTraversalNeeded;
3835 }
3836 }
chaviw8b3871a2017-11-01 17:41:01 -07003837 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003838 // TODO: b/109894387
3839 //
3840 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3841 // rotation. To see the problem observe that if we have a square parent, and a child
3842 // of the same size, then we rotate the child 45 degrees around it's center, the child
3843 // must now be cropped to a non rectangular 8 sided region.
3844 //
3845 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3846 // private API, and the WindowManager only uses rotation in one case, which is on a top
3847 // level layer in which cropping is not an issue.
3848 //
3849 // However given that abuse of rotation matrices could lead to surfaces extending outside
3850 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3851 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3852 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003853 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003854 flags |= eTraversalNeeded;
3855 }
3856 if (what & layer_state_t::eTransparentRegionChanged) {
3857 if (layer->setTransparentRegionHint(s.transparentRegion))
3858 flags |= eTraversalNeeded;
3859 }
3860 if (what & layer_state_t::eFlagsChanged) {
3861 if (layer->setFlags(s.flags, s.mask))
3862 flags |= eTraversalNeeded;
3863 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003864 if (what & layer_state_t::eCropChanged_legacy) {
3865 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003866 flags |= eTraversalNeeded;
3867 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003868 if (what & layer_state_t::eCornerRadiusChanged) {
3869 if (layer->setCornerRadius(s.cornerRadius))
3870 flags |= eTraversalNeeded;
3871 }
chaviw8b3871a2017-11-01 17:41:01 -07003872 if (what & layer_state_t::eLayerStackChanged) {
3873 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3874 // We only allow setting layer stacks for top level layers,
3875 // everything else inherits layer stack from its parent.
3876 if (layer->hasParent()) {
3877 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3878 layer->getName().string());
3879 } else if (idx < 0) {
3880 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3881 "that also does not appear in the top level layer list. Something"
3882 " has gone wrong.", layer->getName().string());
3883 } else if (layer->setLayerStack(s.layerStack)) {
3884 mCurrentState.layersSortedByZ.removeAt(idx);
3885 mCurrentState.layersSortedByZ.add(layer);
3886 // we need traversal (state changed)
3887 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003888 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003889 }
3890 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003891 if (what & layer_state_t::eDeferTransaction_legacy) {
3892 if (s.barrierHandle_legacy != nullptr) {
3893 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3894 } else if (s.barrierGbp_legacy != nullptr) {
3895 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003896 if (authenticateSurfaceTextureLocked(gbp)) {
3897 const auto& otherLayer =
3898 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003899 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003900 } else {
3901 ALOGE("Attempt to defer transaction to to an"
3902 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003903 }
3904 }
chaviw8b3871a2017-11-01 17:41:01 -07003905 // We don't trigger a traversal here because if no other state is
3906 // changed, we don't want this to cause any more work
3907 }
3908 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003909 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003910 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003911 if (!hadParent) {
3912 mCurrentState.layersSortedByZ.remove(layer);
3913 }
chaviw8b3871a2017-11-01 17:41:01 -07003914 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003915 }
chaviw8b3871a2017-11-01 17:41:01 -07003916 }
3917 if (what & layer_state_t::eReparentChildren) {
3918 if (layer->reparentChildren(s.reparentHandle)) {
3919 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003920 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 }
chaviw8b3871a2017-11-01 17:41:01 -07003922 if (what & layer_state_t::eDetachChildren) {
3923 layer->detachChildren();
3924 }
3925 if (what & layer_state_t::eOverrideScalingModeChanged) {
3926 layer->setOverrideScalingMode(s.overrideScalingMode);
3927 // We don't trigger a traversal here because if no other state is
3928 // changed, we don't want this to cause any more work
3929 }
Marissa Wall61c58622018-07-18 10:12:20 -07003930 if (what & layer_state_t::eTransformChanged) {
3931 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3932 }
3933 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3934 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3935 flags |= eTraversalNeeded;
3936 }
3937 if (what & layer_state_t::eCropChanged) {
3938 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3939 }
Marissa Wall861616d2018-10-22 12:52:23 -07003940 if (what & layer_state_t::eFrameChanged) {
3941 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3942 }
Marissa Wall61c58622018-07-18 10:12:20 -07003943 if (what & layer_state_t::eAcquireFenceChanged) {
3944 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3945 }
3946 if (what & layer_state_t::eDataspaceChanged) {
3947 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3948 }
3949 if (what & layer_state_t::eHdrMetadataChanged) {
3950 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3951 }
3952 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3953 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3954 }
3955 if (what & layer_state_t::eApiChanged) {
3956 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3957 }
3958 if (what & layer_state_t::eSidebandStreamChanged) {
3959 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3960 }
Robert Carr720e5062018-07-30 17:45:14 -07003961 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003962 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3963 layer->setInputInfo(s.inputInfo);
3964 flags |= eTraversalNeeded;
3965 } else {
3966 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3967 }
Robert Carr720e5062018-07-30 17:45:14 -07003968 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003969 if (what & layer_state_t::eMetadataChanged) {
3970 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3971 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003972 std::vector<sp<CallbackHandle>> callbackHandles;
3973 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3974 mTransactionCompletedThread.run();
3975 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3976 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3977 }
3978 }
Marissa Wall73411622019-01-25 10:45:41 -08003979
3980 if (what & layer_state_t::eBufferChanged) {
3981 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
3982 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
3983 s.buffer);
3984 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003985 if (what & layer_state_t::eCachedBufferChanged) {
3986 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08003987 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
3988 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08003989 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
3990 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003991 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3992 // Do not put anything that updates layer state or modifies flags after
3993 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003994 return flags;
3995}
3996
chaviw273171b2018-12-26 11:46:30 -08003997uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3998 uint32_t flags = 0;
3999 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4000 flags |= eTraversalNeeded;
4001 }
4002
chaviwa911b102019-02-14 10:18:33 -08004003 if (inputWindowCommands.syncInputWindows) {
4004 flags |= eTraversalNeeded;
4005 }
4006
Vishnu Nairec0ab382019-02-13 15:32:56 -08004007 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004008 return flags;
4009}
4010
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004011status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4012 uint32_t h, PixelFormat format, uint32_t flags,
4013 LayerMetadata metadata, sp<IBinder>* handle,
4014 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004015 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004016 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004017 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004018 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004019 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004020
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004021 status_t result = NO_ERROR;
4022
4023 sp<Layer> layer;
4024
Cody Northropbc755282017-03-31 12:00:08 -06004025 String8 uniqueName = getUniqueLayerName(name);
4026
Mathias Agopian3165cc22012-08-08 19:42:09 -07004027 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004028 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004029 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4030 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004032 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004033 case ISurfaceComposerClient::eFXSurfaceBufferState:
4034 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4035 break;
chaviw13fdc492017-06-27 12:40:18 -07004036 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004037 // check if buffer size is set for color layer.
4038 if (w > 0 || h > 0) {
4039 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4040 int(w), int(h));
4041 return BAD_VALUE;
4042 }
4043
chaviw13fdc492017-06-27 12:40:18 -07004044 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004045 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004046 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004047 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004048 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004049 // check if buffer size is set for container layer.
4050 if (w > 0 || h > 0) {
4051 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4052 int(w), int(h));
4053 return BAD_VALUE;
4054 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004055 result = createContainerLayer(client,
4056 uniqueName, w, h, flags,
4057 handle, &layer);
4058 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004059 default:
4060 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 break;
4062 }
4063
Dan Stoza7d89d062015-04-30 13:29:25 -07004064 if (result != NO_ERROR) {
4065 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004067
Chia-I Wuab0c3192017-08-01 11:29:00 -07004068 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4069 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004070 if (metadata.has(METADATA_WINDOW_TYPE)) {
4071 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4072 if (windowType == 441731) {
4073 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4074 layer->setPrimaryDisplayOnly();
4075 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004076 }
4077
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004078 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004079
Robert Carrb89ea9d2018-12-10 13:01:14 -08004080 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4081 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4082 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004083 if (result != NO_ERROR) {
4084 return result;
4085 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004086 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004087
4088 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090}
4091
Cody Northropbc755282017-03-31 12:00:08 -06004092String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4093{
4094 bool matchFound = true;
4095 uint32_t dupeCounter = 0;
4096
4097 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4098 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4099
Dan Stoza436ccf32018-06-21 12:10:12 -07004100 // Grab the state lock since we're accessing mCurrentState
4101 Mutex::Autolock lock(mStateLock);
4102
Cody Northropbc755282017-03-31 12:00:08 -06004103 // Loop over layers until we're sure there is no matching name
4104 while (matchFound) {
4105 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004106 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004107 if (layer->getName() == uniqueName) {
4108 matchFound = true;
4109 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4110 }
4111 });
4112 }
4113
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004114 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4115 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004116
4117 return uniqueName;
4118}
4119
Marissa Wallfd668622018-05-10 10:21:13 -07004120status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4121 uint32_t w, uint32_t h, uint32_t flags,
4122 PixelFormat& format, sp<IBinder>* handle,
4123 sp<IGraphicBufferProducer>* gbp,
4124 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004125 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004126 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004127 case PIXEL_FORMAT_TRANSPARENT:
4128 case PIXEL_FORMAT_TRANSLUCENT:
4129 format = PIXEL_FORMAT_RGBA_8888;
4130 break;
4131 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004132 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004133 break;
4134 }
4135
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004136 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004137 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004138 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004139 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004140 *handle = layer->getHandle();
4141 *gbp = layer->getProducer();
4142 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004143 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004144
Marissa Wallfd668622018-05-10 10:21:13 -07004145 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004146 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004147}
4148
Marissa Wall61c58622018-07-18 10:12:20 -07004149status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4150 uint32_t w, uint32_t h, uint32_t flags,
4151 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004152 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004153 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004154 *handle = layer->getHandle();
4155 *outLayer = layer;
4156
4157 return NO_ERROR;
4158}
4159
chaviw13fdc492017-06-27 12:40:18 -07004160status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004161 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004162 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004163{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004164 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004165 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004166 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004167}
4168
Robert Carr6b3f6c52018-08-13 13:05:17 -07004169status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4170 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4171 sp<IBinder>* handle, sp<Layer>* outLayer)
4172{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004173 *outLayer =
4174 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004175 *handle = (*outLayer)->getHandle();
4176 return NO_ERROR;
4177}
4178
4179
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004180void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004181 mLayersPendingRemoval.add(layer);
4182 mLayersRemoved = true;
4183 setTransactionFlags(eTransactionNeeded);
4184}
4185
Robert Carr695d5282018-12-18 15:27:58 -08004186void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004187{
Robert Carr2e102c92018-10-23 12:11:15 -07004188 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004189 // If a layer has a parent, we allow it to out-live it's handle
4190 // with the idea that the parent holds a reference and will eventually
4191 // be cleaned up. However no one cleans up the top-level so we do so
4192 // here.
4193 if (layer->getParent() == nullptr) {
4194 mCurrentState.layersSortedByZ.remove(layer);
4195 }
4196 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004197 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004198}
4199
Mathias Agopianb60314a2012-04-10 22:09:54 -07004200// ---------------------------------------------------------------------------
4201
Andy McFadden13a082e2012-08-24 10:16:42 -07004202void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004203 const auto display = getDefaultDisplayDeviceLocked();
4204 if (!display) return;
4205
4206 const sp<IBinder> token = display->getDisplayToken().promote();
4207 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004208
Jesse Hall01e29052013-02-19 16:13:35 -08004209 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004210 Vector<ComposerState> state;
4211 Vector<DisplayState> displays;
4212 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004213 d.what = DisplayState::eDisplayProjectionChanged |
4214 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004215 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004216 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004217 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004218 d.frame.makeInvalid();
4219 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004220 d.width = 0;
4221 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004222 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004223 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004224
Dominik Laskowskie9774092018-12-11 10:04:24 -08004225 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004226
Dominik Laskowski83b88212018-12-11 13:34:06 -08004227 const nsecs_t vsyncPeriod = getVsyncPeriod();
4228 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004229
Brian Andersond0010582017-03-07 13:20:31 -08004230 // Use phase of 0 since phase is not known.
4231 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004232 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004233 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004234}
4235
4236void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004237 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004238 postMessageAsync(
4239 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004240}
4241
Dominik Laskowskie9774092018-12-11 10:04:24 -08004242void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004243 if (display->isVirtual()) {
4244 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004245 return;
4246 }
4247
Dominik Laskowski075d3172018-05-24 15:50:06 -07004248 const auto displayId = display->getId();
4249 LOG_ALWAYS_FATAL_IF(!displayId);
4250
Dominik Laskowski34157762018-10-31 13:07:19 -07004251 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004252
4253 int currentMode = display->getPowerMode();
4254 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004255 return;
4256 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004257
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004258 display->setPowerMode(mode);
4259
Lloyd Pique4dccc412018-01-22 17:21:36 -08004260 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004261 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004262 }
4263
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004264 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004265 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004266 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004267 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004268 mScheduler->onScreenAcquired(mAppConnectionHandle);
4269 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004270 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004271
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004272 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004273 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004274 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004275
4276 struct sched_param param = {0};
4277 param.sched_priority = 1;
4278 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4279 ALOGW("Couldn't set SCHED_FIFO on display on");
4280 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004281 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004282 // Turn off the display
4283 struct sched_param param = {0};
4284 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4285 ALOGW("Couldn't set SCHED_OTHER on display off");
4286 }
4287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004288 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004289 mScheduler->disableHardwareVsync(true);
4290 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004291 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004292
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004294 mVisibleRegionsDirty = true;
4295 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004296 } else if (mode == HWC_POWER_MODE_DOZE ||
4297 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004298 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004299 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004301 mScheduler->onScreenAcquired(mAppConnectionHandle);
4302 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004303 }
4304 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4305 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004306 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004307 mScheduler->disableHardwareVsync(true);
4308 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004309 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004310 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004311 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004312 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004313 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004314 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004315
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004316 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004317 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004318 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004319 // Update refresh rate stats.
4320 mRefreshRateStats->setPowerMode(mode);
4321 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004322 }
4323
Dominik Laskowski34157762018-10-31 13:07:19 -07004324 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004325}
4326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004327void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004328 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004329 const auto display = getDisplayDevice(displayToken);
4330 if (!display) {
4331 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4332 displayToken.get());
4333 } else if (display->isVirtual()) {
4334 ALOGW("Attempt to set power mode %d for virtual display", mode);
4335 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004336 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004337 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004338 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004339}
4340
4341// ---------------------------------------------------------------------------
4342
Dominik Laskowskic2867142019-01-21 11:33:38 -08004343status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4344 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004346
Mathias Agopianbd115332013-04-18 16:41:04 -07004347 IPCThreadState* ipc = IPCThreadState::self();
4348 const int pid = ipc->getCallingPid();
4349 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004350
Mathias Agopianbd115332013-04-18 16:41:04 -07004351 if ((uid != AID_SHELL) &&
4352 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4354 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004355 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004356 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004357 // (this would indicate SF is stuck, but we want to be able to
4358 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004359 status_t err = mStateLock.timedLock(s2ns(1));
4360 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004361 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 StringAppendF(&result,
4363 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4364 "(no locks held)\n",
4365 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004366 }
4367
Dominik Laskowskic2867142019-01-21 11:33:38 -08004368 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004369
Dominik Laskowskic2867142019-01-21 11:33:38 -08004370 static const std::unordered_map<std::string, Dumper> dumpers = {
4371 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4372 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4373 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004374 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004375 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004376 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004377 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4378 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004379 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4380 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4381 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4382 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4383 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4384 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004385 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004386 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4387 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004388
Dominik Laskowskic2867142019-01-21 11:33:38 -08004389 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004390
Dominik Laskowskic2867142019-01-21 11:33:38 -08004391 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4392 (it->second)(args, asProto, result);
4393 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004394 if (asProto) {
4395 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4396 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4397 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004398 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004399 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004400 }
4401
Mathias Agopian9795c422009-08-26 16:36:26 -07004402 if (locked) {
4403 mStateLock.unlock();
4404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004405 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004406 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004407 return NO_ERROR;
4408}
4409
Dominik Laskowskic2867142019-01-21 11:33:38 -08004410void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 mCurrentState.traverseInZOrder(
4412 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004413}
4414
Dominik Laskowskic2867142019-01-21 11:33:38 -08004415void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004416 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004417
Dominik Laskowskic2867142019-01-21 11:33:38 -08004418 if (args.size() > 1) {
4419 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004420 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004421 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004422 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004423 }
Robert Carr2047fae2016-11-28 14:09:09 -08004424 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004425 } else {
4426 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427 }
4428}
4429
Dominik Laskowskic2867142019-01-21 11:33:38 -08004430void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004431 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004432 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004433 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004434 }
Robert Carr2047fae2016-11-28 14:09:09 -08004435 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004436
Svetoslavd85084b2014-03-20 10:28:31 -07004437 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004438}
4439
Dominik Laskowskic2867142019-01-21 11:33:38 -08004440void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4441 mTimeStats->parseArgs(asProto, args, result);
4442}
4443
Jamie Gennis6547ff42013-07-16 20:12:42 -07004444// This should only be called from the main thread. Otherwise it would need
4445// the lock and should use mCurrentState rather than mDrawingState.
4446void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004447 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004448 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004449 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004450
4451 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4452}
4453
Yiwei Zhang5434a782018-12-05 18:06:32 -08004454void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004455 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004456
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004457 if (isLayerTripleBufferingDisabled())
4458 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004459
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4461 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4462 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4463 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4464 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4465 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004466 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004467}
4468
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004469void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004470 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004471 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004472 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004473 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004474
Ana Krulecba13ab32019-02-20 14:14:12 -08004475 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4476 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4477 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004478 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004479}
4480
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4482 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004483 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4484 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004485 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004486 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004487 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004488 }
David Sodman4a36e932017-11-07 14:29:47 -08004489 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004490 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004491 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4493 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004494}
4495
Dan Stozae77c7662016-05-13 11:37:28 -07004496void SurfaceFlinger::recordBufferingStats(const char* layerName,
4497 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004498 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4499 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004500 for (const auto& segment : history) {
4501 if (!segment.usedThirdBuffer) {
4502 stats.twoBufferTime += segment.totalTime;
4503 }
4504 if (segment.occupancyAverage < 1.0f) {
4505 stats.doubleBufferedTime += segment.totalTime;
4506 } else if (segment.occupancyAverage < 2.0f) {
4507 stats.tripleBufferedTime += segment.totalTime;
4508 }
4509 ++stats.numSegments;
4510 stats.totalTime += segment.totalTime;
4511 }
4512}
4513
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4515 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004516
4517 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4518 const size_t count = currentLayers.size();
4519 for (size_t i=0 ; i<count ; i++) {
4520 currentLayers[i]->dumpFrameEvents(result);
4521 }
4522}
4523
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004525 result.append("Buffering stats:\n");
4526 result.append(" [Layer name] <Active time> <Two buffer> "
4527 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004528 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004529 typedef std::tuple<std::string, float, float, float> BufferTuple;
4530 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004531 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004532 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004533 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004534 if (stats.numSegments == 0) {
4535 continue;
4536 }
4537 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4538 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4539 stats.totalTime;
4540 float doubleBufferRatio = static_cast<float>(
4541 stats.doubleBufferedTime) / stats.totalTime;
4542 float tripleBufferRatio = static_cast<float>(
4543 stats.tripleBufferedTime) / stats.totalTime;
4544 sorted.insert({activeTime, {name, twoBufferRatio,
4545 doubleBufferRatio, tripleBufferRatio}});
4546 }
4547 for (const auto& sortedPair : sorted) {
4548 float activeTime = sortedPair.first;
4549 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004550 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4551 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004552 }
4553 result.append("\n");
4554}
4555
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004557 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004558 const auto displayId = display->getId();
4559 if (!displayId) {
4560 continue;
4561 }
4562 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004563 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004564 continue;
4565 }
4566
Yiwei Zhang5434a782018-12-05 18:06:32 -08004567 StringAppendF(&result,
4568 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4569 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004570 uint8_t port;
4571 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004572 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004573 result.append("no identification data\n");
4574 continue;
4575 }
4576
4577 if (!isEdid(data)) {
4578 result.append("unknown identification data: ");
4579 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004581 }
4582 result.append("\n");
4583 continue;
4584 }
4585
4586 const auto edid = parseEdid(data);
4587 if (!edid) {
4588 result.append("invalid EDID: ");
4589 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004590 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004591 }
4592 result.append("\n");
4593 continue;
4594 }
4595
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004597 result.append(edid->displayName.data(), edid->displayName.length());
4598 result.append("\"\n");
4599 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004600}
4601
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4603 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4604 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4605 StringAppendF(&result, "DisplayColorSetting: %s\n",
4606 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004607
4608 // TODO: print out if wide-color mode is active or not
4609
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004610 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004611 const auto displayId = display->getId();
4612 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004613 continue;
4614 }
4615
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004617 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004618 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004620 }
4621
Lloyd Pique32cbe282018-10-19 13:09:22 -07004622 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result, " Current color mode: %s (%d)\n",
4624 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004625 }
4626 result.append("\n");
4627}
4628
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004629LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004630 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004631 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4632 const State& state = useDrawing ? mDrawingState : mCurrentState;
4633 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004634 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004635 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004636 });
4637
4638 return layersProto;
4639}
4640
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004641LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4642 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004643 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004644
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004645 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004646 resolution->set_w(displayDevice->getWidth());
4647 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004648
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004649 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004650 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004651
Lloyd Pique32cbe282018-10-19 13:09:22 -07004652 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4653 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4654 layersProto.set_global_transform(displayState.orientation);
4655
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004656 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004657 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004658 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004659 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004660 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004661 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004662 }
4663 });
4664
4665 return layersProto;
4666}
4667
Dominik Laskowskic2867142019-01-21 11:33:38 -08004668void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4669 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004670 Colorizer colorizer(colorize);
4671
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004672 // figure out if we're stuck somewhere
4673 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004675 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4676
4677 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004678 * Dump library configuration.
4679 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680
4681 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004682 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004683 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004684 appendSfConfigString(result);
4685 appendUiConfigString(result);
4686 appendGuiConfigString(result);
4687 result.append("\n");
4688
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004689 result.append("\nDisplay identification data:\n");
4690 dumpDisplayIdentificationData(result);
4691
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004692 result.append("\nWide-Color information:\n");
4693 dumpWideColorInfo(result);
4694
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004695 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004696 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004697 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004698 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004699 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004700
Andy McFadden41d67d72014-04-25 16:58:34 -07004701 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004702 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004703 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004704 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004705 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004706
Dan Stozab90cf072015-03-05 11:05:59 -08004707 dumpStaticScreenStats(result);
4708 result.append("\n");
4709
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004711
Dan Stozae77c7662016-05-13 11:37:28 -07004712 dumpBufferingStats(result);
4713
Andy McFadden4803b742012-09-24 19:07:20 -07004714 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004715 * Dump the visible layer list
4716 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4719 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4720 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004721 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004722
Chia-I Wu2f884132018-09-13 15:17:58 -07004723 {
4724 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4725 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004727 result.append("\n");
4728 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729
4730 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004731 * Dump Display state
4732 */
4733
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004734 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004735 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004736 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004738 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004739 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004740 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004741
4742 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743 * Dump SurfaceFlinger global state
4744 */
4745
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004746 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004747 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004748 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004749
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004750 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004751
Dominik Laskowski075d3172018-05-24 15:50:06 -07004752 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004753 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4754 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4756 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004757 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result,
4759 " transaction-flags : %08x\n"
4760 " gpu_to_cpu_unsupported : %d\n",
4761 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004762
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004763 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004764 displayId && getHwComposer().isConnected(*displayId)) {
4765 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004766 StringAppendF(&result,
4767 " refresh-rate : %f fps\n"
4768 " x-dpi : %f\n"
4769 " y-dpi : %f\n",
4770 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4771 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004772 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773
Yiwei Zhang5434a782018-12-05 18:06:32 -08004774 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004775
Dan Stozae22aec72016-08-01 13:20:59 -07004776 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004777 * Tracing state
4778 */
4779 mTracing.dump(result);
4780 result.append("\n");
4781
4782 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004783 * HWC layer minidump
4784 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004785 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004786 const auto displayId = display->getId();
4787 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004788 continue;
4789 }
4790
Yiwei Zhang5434a782018-12-05 18:06:32 -08004791 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004792 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004793 const sp<DisplayDevice> displayDevice = display;
4794 mCurrentState.traverseInZOrder(
4795 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004796 result.append("\n");
4797 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004798
4799 /*
4800 * Dump HWComposer state
4801 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004802 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004803 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004804 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004805 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004806 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004807 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004808
4809 /*
4810 * Dump gralloc state
4811 */
4812 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4813 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004814
4815 /*
4816 * Dump VrFlinger state if in use.
4817 */
4818 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4819 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004820 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004821 result.append("\n");
4822 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004823
4824 /**
4825 * Scheduler dump state.
4826 */
Ana Krulecc2870422019-01-29 19:00:58 -08004827 result.append("\nScheduler state:\n");
4828 result.append(mScheduler->doDump() + "\n");
4829 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004830}
4831
Dominik Laskowski075d3172018-05-24 15:50:06 -07004832const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004833 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004834 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004835 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004836 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004837 }
4838 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004839
Dominik Laskowski34157762018-10-31 13:07:19 -07004840 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004841 static const Vector<sp<Layer>> empty;
4842 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004843}
4844
Chia-I Wu28f320b2018-05-03 11:02:56 -07004845void SurfaceFlinger::updateColorMatrixLocked() {
4846 mat4 colorMatrix;
4847 if (mGlobalSaturationFactor != 1.0f) {
4848 // Rec.709 luma coefficients
4849 float3 luminance{0.213f, 0.715f, 0.072f};
4850 luminance *= 1.0f - mGlobalSaturationFactor;
4851 mat4 saturationMatrix = mat4(
4852 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4853 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4854 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4855 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4856 );
4857 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4858 } else {
4859 colorMatrix = mClientColorMatrix * mDaltonizer();
4860 }
4861
4862 if (mCurrentState.colorMatrix != colorMatrix) {
4863 mCurrentState.colorMatrix = colorMatrix;
4864 mCurrentState.colorMatrixChanged = true;
4865 setTransactionFlags(eTransactionNeeded);
4866 }
4867}
4868
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004869status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870#pragma clang diagnostic push
4871#pragma clang diagnostic error "-Wswitch-enum"
4872 switch (static_cast<ISurfaceComposerTag>(code)) {
4873 // These methods should at minimum make sure that the client requested
4874 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004875 case BOOT_FINISHED:
4876 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877 case CREATE_DISPLAY:
4878 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004879 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004880 case GET_ACTIVE_COLOR_MODE:
4881 case GET_ANIMATION_FRAME_STATS:
4882 case GET_HDR_CAPABILITIES:
4883 case SET_ACTIVE_CONFIG:
4884 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004885 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004886 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004887 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004888 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4889 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004890 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4891 IPCThreadState* ipc = IPCThreadState::self();
4892 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4893 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004894 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 }
Robert Carr1db73f62016-12-21 12:58:51 -08004896 return OK;
4897 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004898 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004899 IPCThreadState* ipc = IPCThreadState::self();
4900 const int pid = ipc->getCallingPid();
4901 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004902 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4903 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004904 return PERMISSION_DENIED;
4905 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004906 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004908 // Used by apps to hook Choreographer to SurfaceFlinger.
4909 case CREATE_DISPLAY_EVENT_CONNECTION:
4910 // The following calls are currently used by clients that do not
4911 // request necessary permissions. However, they do not expose any secret
4912 // information, so it is OK to pass them.
4913 case AUTHENTICATE_SURFACE:
4914 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004915 case GET_PHYSICAL_DISPLAY_IDS:
4916 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004917 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004918 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 case GET_DISPLAY_CONFIGS:
4920 case GET_DISPLAY_STATS:
4921 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4922 // Calling setTransactionState is safe, because you need to have been
4923 // granted a reference to Client* and Handle* to do anything with it.
4924 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004925 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004926 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004927 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004928 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw5f21a5e2019-02-14 10:00:34 -08004929 case IS_WIDE_COLOR_DISPLAY:
4930 case SET_INPUT_WINDOWS_FINISHED: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931 return OK;
4932 }
4933 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004934 case CAPTURE_SCREEN:
4935 case ADD_REGION_SAMPLING_LISTENER:
4936 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004938 IPCThreadState* ipc = IPCThreadState::self();
4939 const int pid = ipc->getCallingPid();
4940 const int uid = ipc->getCallingUid();
4941 if ((uid != AID_GRAPHICS) &&
4942 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4943 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4944 return PERMISSION_DENIED;
4945 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 return OK;
4947 }
4948 // The following codes are deprecated and should never be allowed to access SF.
4949 case CONNECT_DISPLAY_UNUSED:
4950 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4951 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4952 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004953 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955
4956 // These codes are used for the IBinder protocol to either interrogate the recipient
4957 // side of the transaction for its canonical interface descriptor or to dump its state.
4958 // We let them pass by default.
4959 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4960 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4961 code == IBinder::SYSPROPS_TRANSACTION) {
4962 return OK;
4963 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004964 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004965 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004966 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004967 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4968 return OK;
4969 }
4970 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4971 return PERMISSION_DENIED;
4972#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004973}
4974
Ana Krulec13be8ad2018-08-21 02:43:56 +00004975status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4976 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004977 status_t credentialCheck = CheckTransactCodeCredentials(code);
4978 if (credentialCheck != OK) {
4979 return credentialCheck;
4980 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004981
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4983 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004984 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004985 IPCThreadState* ipc = IPCThreadState::self();
4986 const int uid = ipc->getCallingUid();
4987 if (CC_UNLIKELY(uid != AID_SYSTEM
4988 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004989 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004990 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004991 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004992 return PERMISSION_DENIED;
4993 }
4994 int n;
4995 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004996 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004997 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004998 return NO_ERROR;
4999 case 1002: // SHOW_UPDATES
5000 n = data.readInt32();
5001 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005002 invalidateHwcGeometry();
5003 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005006 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005007 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005009 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005010 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005011 setTransactionFlags(
5012 eTransactionNeeded|
5013 eDisplayTransactionNeeded|
5014 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005015 return NO_ERROR;
5016 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005017 case 1006:{ // send empty update
5018 signalRefresh();
5019 return NO_ERROR;
5020 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005021 case 1008: // toggle use of hw composer
5022 n = data.readInt32();
5023 mDebugDisableHWC = n ? 1 : 0;
5024 invalidateHwcGeometry();
5025 repaintEverything();
5026 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005027 case 1009: // toggle use of transform hint
5028 n = data.readInt32();
5029 mDebugDisableTransformHint = n ? 1 : 0;
5030 invalidateHwcGeometry();
5031 repaintEverything();
5032 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005033 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005034 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 reply->writeInt32(0);
5036 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005037 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005038 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005039 return NO_ERROR;
5040 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005041 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005042 if (!display) {
5043 return NAME_NOT_FOUND;
5044 }
5045
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005046 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005047 return NO_ERROR;
5048 }
5049 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005050 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005051 // daltonize
5052 n = data.readInt32();
5053 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005054 case 1:
5055 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5056 break;
5057 case 2:
5058 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5059 break;
5060 case 3:
5061 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5062 break;
5063 default:
5064 mDaltonizer.setType(ColorBlindnessType::None);
5065 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005066 }
5067 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005068 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005069 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005070 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005071 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005072
5073 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005074 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005075 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005076 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005077 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005078 // apply a color matrix
5079 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005080 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005081 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005082 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005083 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005084 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005085 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005086 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005087 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005088 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005089 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005090
5091 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5092 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005093 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005094 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5095 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5096 }
5097
Chia-I Wu28f320b2018-05-03 11:02:56 -07005098 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005099 return NO_ERROR;
5100 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005101 // This is an experimental interface
5102 // Needs to be shifted to proper binder interface when we productize
5103 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005104 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005105 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005106 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005107 return NO_ERROR;
5108 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005109 case 1017: {
5110 n = data.readInt32();
5111 mForceFullDamage = static_cast<bool>(n);
5112 return NO_ERROR;
5113 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005114 case 1018: { // Modify Choreographer's phase offset
5115 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005116 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005117 return NO_ERROR;
5118 }
5119 case 1019: { // Modify SurfaceFlinger's phase offset
5120 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005121 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005122 return NO_ERROR;
5123 }
Irvel468051e2016-06-13 16:44:44 -07005124 case 1020: { // Layer updates interceptor
5125 n = data.readInt32();
5126 if (n) {
5127 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005128 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005129 }
5130 else{
5131 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005132 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005133 }
5134 return NO_ERROR;
5135 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005136 case 1021: { // Disable HWC virtual displays
5137 n = data.readInt32();
5138 mUseHwcVirtualDisplays = !n;
5139 return NO_ERROR;
5140 }
Romain Guy0147a172017-06-01 13:53:56 -07005141 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005142 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005143 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005144
Chia-I Wu28f320b2018-05-03 11:02:56 -07005145 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005146 return NO_ERROR;
5147 }
Romain Guy54f154a2017-10-24 21:40:32 +01005148 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005149 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005150 invalidateHwcGeometry();
5151 repaintEverything();
5152 return NO_ERROR;
5153 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005154 // Deprecate, use 1030 to check whether the device is color managed.
5155 case 1024: {
5156 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005157 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005158 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005159 n = data.readInt32();
5160 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005161 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005162 mTracing.enable();
5163 doTracing("tracing.enable");
5164 reply->writeInt32(NO_ERROR);
5165 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005166 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005167 status_t err = mTracing.disable();
5168 reply->writeInt32(err);
5169 }
5170 return NO_ERROR;
5171 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005172 case 1026: { // Get layer tracing status
5173 reply->writeBool(mTracing.isEnabled());
5174 return NO_ERROR;
5175 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005176 // Is a DisplayColorSetting supported?
5177 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005178 const auto display = getDefaultDisplayDevice();
5179 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005180 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005181 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005182
5183 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5184 switch (setting) {
5185 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005186 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005187 break;
5188 case DisplayColorSetting::UNMANAGED:
5189 reply->writeBool(true);
5190 break;
5191 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005192 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005193 break;
5194 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005195 reply->writeBool(
5196 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005197 break;
5198 }
5199 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005200 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005201 // Is VrFlinger active?
5202 case 1028: {
5203 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005204 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005205 return NO_ERROR;
5206 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005207 // Is device color managed?
5208 case 1030: {
5209 reply->writeBool(useColorManagement);
5210 return NO_ERROR;
5211 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005212 // Override default composition data space
5213 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5214 // && adb shell stop zygote && adb shell start zygote
5215 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5216 // adb shell stop zygote && adb shell start zygote
5217 case 1031: {
5218 Mutex::Autolock _l(mStateLock);
5219 n = data.readInt32();
5220 if (n) {
5221 n = data.readInt32();
5222 if (n) {
5223 Dataspace dataspace = static_cast<Dataspace>(n);
5224 if (!validateCompositionDataspace(dataspace)) {
5225 return BAD_VALUE;
5226 }
5227 mDefaultCompositionDataspace = dataspace;
5228 }
5229 n = data.readInt32();
5230 if (n) {
5231 Dataspace dataspace = static_cast<Dataspace>(n);
5232 if (!validateCompositionDataspace(dataspace)) {
5233 return BAD_VALUE;
5234 }
5235 mWideColorGamutCompositionDataspace = dataspace;
5236 }
5237 } else {
5238 // restore composition data space.
5239 mDefaultCompositionDataspace = defaultCompositionDataspace;
5240 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5241 }
5242 return NO_ERROR;
5243 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005244 }
5245 }
5246 return err;
5247}
5248
Steven Thomas6d8110b2017-08-31 18:24:21 -07005249void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005250 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005251 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005252}
5253
Ana Krulec7d1d6832018-12-27 11:10:09 -08005254void SurfaceFlinger::repaintEverythingForHWC() {
5255 mRepaintEverything = true;
5256 mEventQueue->invalidateForHWC();
5257}
5258
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005259// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5260class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005261public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5263 ~WindowDisconnector() {
5264 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005265 }
5266
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005267private:
5268 ANativeWindow* mWindow;
5269 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005270};
5271
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005272status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005273 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5274 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005275 uint32_t reqWidth, uint32_t reqHeight,
5276 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005277 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005279
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005280 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005281
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005282 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5283
Chia-I Wu20261cb2018-08-23 12:55:44 -07005284 sp<DisplayDevice> display;
5285 {
5286 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005287
Chia-I Wu20261cb2018-08-23 12:55:44 -07005288 display = getDisplayDeviceLocked(displayToken);
5289 if (!display) return BAD_VALUE;
5290
Chia-I Wucb023152018-08-28 12:57:23 -07005291 // set the requested width/height to the logical display viewport size
5292 // by default
5293 if (reqWidth == 0 || reqHeight == 0) {
5294 reqWidth = uint32_t(display->getViewport().width());
5295 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005296 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005297 }
5298
Peiyong Lin0e003c92018-09-17 11:09:51 -07005299 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5300 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005301
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005302 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5303 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005304 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5305 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005306}
5307
5308status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005309 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5310 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005311 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005312 ATRACE_CALL();
5313
5314 class LayerRenderArea : public RenderArea {
5315 public:
Robert Carr578038f2018-03-09 12:25:24 -08005316 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005317 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5318 bool childrenOnly)
5319 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005320 mLayer(layer),
5321 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005322 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005323 mFlinger(flinger),
5324 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005325 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005326 Rect getBounds() const override {
5327 const Layer::State& layerState(mLayer->getDrawingState());
5328 return mLayer->getBufferSize(layerState);
5329 }
Marissa Wall61c58622018-07-18 10:12:20 -07005330 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005331 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005332 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005333 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005334 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005335 }
chaviwa76b2712017-09-20 12:02:26 -07005336 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005337 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005338 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005339 Rect getSourceCrop() const override {
5340 if (mCrop.isEmpty()) {
5341 return getBounds();
5342 } else {
5343 return mCrop;
5344 }
5345 }
Robert Carr578038f2018-03-09 12:25:24 -08005346 class ReparentForDrawing {
5347 public:
5348 const sp<Layer>& oldParent;
5349 const sp<Layer>& newParent;
5350
Vishnu Nair4351ad52019-02-11 14:13:02 -08005351 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5352 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005353 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005354 // Compute and cache the bounds for the new parent layer.
5355 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005356 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005357 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005358 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005359 };
5360
5361 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005362 const Rect sourceCrop = getSourceCrop();
5363 // no need to check rotation because there is none
5364 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5365 sourceCrop.height() != getReqHeight();
5366
Robert Carr578038f2018-03-09 12:25:24 -08005367 if (!mChildrenOnly) {
5368 mTransform = mLayer->getTransform().inverse();
5369 drawLayers();
5370 } else {
5371 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005372 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005373 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5374 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005375
Vishnu Nair4351ad52019-02-11 14:13:02 -08005376 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005377 drawLayers();
5378 }
5379 }
chaviwa76b2712017-09-20 12:02:26 -07005380
chaviwa76b2712017-09-20 12:02:26 -07005381 private:
chaviw7206d492017-11-10 16:16:12 -08005382 const sp<Layer> mLayer;
5383 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005384
5385 // In the "childrenOnly" case we reparent the children to a screenshot
5386 // layer which has no properties set and which does not draw.
5387 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005388 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005389 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005390
5391 SurfaceFlinger* mFlinger;
5392 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005393 };
5394
5395 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5396 auto parent = layerHandle->owner.promote();
5397
Robert Carr2e102c92018-10-23 12:11:15 -07005398 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005399 ALOGE("captureLayers called with a removed parent");
5400 return NAME_NOT_FOUND;
5401 }
5402
Robert Carr578038f2018-03-09 12:25:24 -08005403 const int uid = IPCThreadState::self()->getCallingUid();
5404 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005405 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005406 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5407 return PERMISSION_DENIED;
5408 }
5409
chaviw7206d492017-11-10 16:16:12 -08005410 Rect crop(sourceCrop);
5411 if (sourceCrop.width() <= 0) {
5412 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005413 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005414 }
5415
5416 if (sourceCrop.height() <= 0) {
5417 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005418 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005419 }
5420
5421 int32_t reqWidth = crop.width() * frameScale;
5422 int32_t reqHeight = crop.height() * frameScale;
5423
Chia-I Wu20261cb2018-08-23 12:55:44 -07005424 // really small crop or frameScale
5425 if (reqWidth <= 0) {
5426 reqWidth = 1;
5427 }
5428 if (reqHeight <= 0) {
5429 reqHeight = 1;
5430 }
5431
Peiyong Lin0e003c92018-09-17 11:09:51 -07005432 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005433
Robert Carr578038f2018-03-09 12:25:24 -08005434 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005435 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5436 if (!layer->isVisible()) {
5437 return;
Robert Carr578038f2018-03-09 12:25:24 -08005438 } else if (childrenOnly && layer == parent.get()) {
5439 return;
chaviwa76b2712017-09-20 12:02:26 -07005440 }
5441 visitor(layer);
5442 });
5443 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005444 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005445}
5446
5447status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5448 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005449 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005450 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005451 bool useIdentityTransform) {
5452 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005453
Peiyong Lin0e003c92018-09-17 11:09:51 -07005454 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005455 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5456 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005457 *outBuffer =
5458 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5459 static_cast<android_pixel_format>(reqPixelFormat), 1,
5460 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005461
5462 // This mutex protects syncFd and captureResult for communication of the return values from the
5463 // main thread back to this Binder thread
5464 std::mutex captureMutex;
5465 std::condition_variable captureCondition;
5466 std::unique_lock<std::mutex> captureLock(captureMutex);
5467 int syncFd = -1;
5468 std::optional<status_t> captureResult;
5469
Robert Carr03480e22018-01-04 16:02:06 -08005470 const int uid = IPCThreadState::self()->getCallingUid();
5471 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5472
Dominik Laskowski8c001672018-05-30 16:52:06 -07005473 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005474 // If there is a refresh pending, bug out early and tell the binder thread to try again
5475 // after the refresh.
5476 if (mRefreshPending) {
5477 ATRACE_NAME("Skipping screenshot for now");
5478 std::unique_lock<std::mutex> captureLock(captureMutex);
5479 captureResult = std::make_optional<status_t>(EAGAIN);
5480 captureCondition.notify_one();
5481 return;
5482 }
5483
5484 status_t result = NO_ERROR;
5485 int fd = -1;
5486 {
5487 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005488 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005489 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5490 useIdentityTransform, forSystem, &fd);
5491 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005492 }
5493
5494 {
5495 std::unique_lock<std::mutex> captureLock(captureMutex);
5496 syncFd = fd;
5497 captureResult = std::make_optional<status_t>(result);
5498 captureCondition.notify_one();
5499 }
5500 });
5501
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005502 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005503 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005504 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005505 while (*captureResult == EAGAIN) {
5506 captureResult.reset();
5507 result = postMessageAsync(message);
5508 if (result != NO_ERROR) {
5509 return result;
5510 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005511 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005512 }
5513 result = *captureResult;
5514 }
5515
5516 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005517 sync_wait(syncFd, -1);
5518 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005520
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005521 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005522}
5523
chaviwa76b2712017-09-20 12:02:26 -07005524void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005525 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005526 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5527 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005529
chaviwa76b2712017-09-20 12:02:26 -07005530 const auto reqWidth = renderArea.getReqWidth();
5531 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005532 const auto sourceCrop = renderArea.getSourceCrop();
5533 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005534
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005535 renderengine::DisplaySettings clientCompositionDisplay;
5536 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005537
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005538 // assume that bounds are never offset, and that they are the same as the
5539 // buffer bounds.
5540 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5541 ui::Transform transform = renderArea.getTransform();
5542 mat4 m;
5543 m[0][0] = transform[0][0];
5544 m[0][1] = transform[0][1];
5545 m[0][3] = transform[0][2];
5546 m[1][0] = transform[1][0];
5547 m[1][1] = transform[1][1];
5548 m[1][3] = transform[1][2];
5549 m[3][0] = transform[2][0];
5550 m[3][1] = transform[2][1];
5551 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005552
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005553 clientCompositionDisplay.globalTransform = m;
5554 mat4 rotMatrix;
5555 // Displacement for repositioning the clipping rectangle after rotating it
5556 // with the rotation hint.
5557 int displacementX = 0;
5558 int displacementY = 0;
5559 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5560 switch (rotation) {
5561 case ui::Transform::ROT_90:
5562 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5563 displacementX = reqWidth;
5564 break;
5565 case ui::Transform::ROT_180:
5566 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5567 displacementX = reqWidth;
5568 displacementY = reqHeight;
5569 break;
5570 case ui::Transform::ROT_270:
5571 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5572 displacementY = reqHeight;
5573 break;
5574 default:
5575 break;
5576 }
5577 // We need to transform the clipping window into the right spot.
5578 // First, rotate the clipping rectangle by the rotation hint to get the
5579 // right orientation
5580 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5581 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5582 const vec4 rotClipTL = rotMatrix * clipTL;
5583 const vec4 rotClipBR = rotMatrix * clipBR;
5584 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5585 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5586 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5587 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5588
5589 // Now reposition the clipping rectangle with the displacement vector
5590 // computed above.
5591 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5592
5593 clientCompositionDisplay.clip =
5594 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5595 newClipRight + displacementX, newClipBottom + displacementY);
5596
5597 // We need to perform the same transformation in layer space, so propagate
5598 // it to the global transform.
5599 mat4 clipTransform = displacementMat * rotMatrix;
5600 clientCompositionDisplay.globalTransform *= clipTransform;
5601 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5602 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005603
chaviw50da5042018-04-09 13:49:37 -07005604 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005605
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005606 renderengine::LayerSettings fillLayer;
5607 fillLayer.source.buffer.buffer = nullptr;
5608 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5609 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5610 fillLayer.alpha = half(alpha);
5611 clientCompositionLayers.push_back(fillLayer);
5612
5613 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005614 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005615 renderengine::LayerSettings layerSettings;
5616 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5617 layerSettings);
5618 if (prepared) {
5619 clientCompositionLayers.push_back(layerSettings);
5620 }
chaviwa76b2712017-09-20 12:02:26 -07005621 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005622
5623 clientCompositionDisplay.clearRegion = clearRegion;
5624 base::unique_fd drawFence;
5625 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5626 &drawFence);
5627
5628 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005629}
5630
chaviwa76b2712017-09-20 12:02:26 -07005631status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5632 TraverseLayersFunction traverseLayers,
5633 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005634 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005635 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005636 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005637 ATRACE_CALL();
5638
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005639 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005640
5641 traverseLayers([&](Layer* layer) {
5642 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5643 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005644
Robert Carr03480e22018-01-04 16:02:06 -08005645 // We allow the system server to take screenshots of secure layers for
5646 // use in situations like the Screen-rotation animation and place
5647 // the impetus on WindowManager to not persist them.
5648 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005649 ALOGW("FB is protected: PERMISSION_DENIED");
5650 return PERMISSION_DENIED;
5651 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005652 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005653 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005654}
5655
chaviw5f21a5e2019-02-14 10:00:34 -08005656void SurfaceFlinger::setInputWindowsFinished() {}
5657
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005658// ---------------------------------------------------------------------------
5659
Dan Stoza412903f2017-04-27 13:42:17 -07005660void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5661 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005662}
5663
Dan Stoza412903f2017-04-27 13:42:17 -07005664void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5665 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005666}
5667
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005668void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005669 const LayerVector::Visitor& visitor) {
5670 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005671 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005672 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005673 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005674 continue;
5675 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005676 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005677 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005678 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005679 return;
5680 }
chaviwa76b2712017-09-20 12:02:26 -07005681 if (!layer->isVisible()) {
5682 return;
5683 }
5684 visitor(layer);
5685 });
5686 }
5687}
5688
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005689}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005690
Lloyd Pique074e8122018-07-26 12:57:23 -07005691
Mathias Agopian3f844832013-08-07 21:24:32 -07005692#if defined(__gl_h_)
5693#error "don't include gl/gl.h in this file"
5694#endif
5695
5696#if defined(__gl2_h_)
5697#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005698#endif