blob: f8f258b6172e0919cd696c53ef52088d35f9f9ba [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()),
chaviw291d88a2019-02-14 10:33:58 -0800300 mCompositionEngine{getFactory().createCompositionEngine()} {
301 mSetInputWindowsListener = new SetInputWindowsListener(this);
302}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800303
Lloyd Pique90c115d2018-09-18 21:39:42 -0700304SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
305 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800306 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800307
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700311
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900312 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800315
Steven Thomas050b2c82017-03-06 11:45:16 -0800316 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700322
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900323 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600324
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 mDefaultCompositionDataspace =
326 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
327 mWideColorGamutCompositionDataspace =
328 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
329 defaultCompositionDataspace = mDefaultCompositionDataspace;
330 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
331 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
332 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
333 wideColorGamutCompositionPixelFormat =
334 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700335
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
339 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
340 switch (tmpPrimaryDisplayOrientation) {
341 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
353 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800355
Daniel Solomon42d04562019-01-20 21:03:19 -0800356 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
357 if (surfaceFlingerConfigsServiceV1_2) {
358 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
359 [&](auto tmpPrimaries) {
360 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
361 });
362 } else {
363 initDefaultDisplayNativePrimaries();
364 }
365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800366 // debugging stuff...
367 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700370 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372 property_get("debug.sf.showupdates", value, "0");
373 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700374
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700375 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000376
377 // DDMS debugging deprecated (b/120782499)
378 property_get("debug.sf.ddms", value, "0");
379 int debugDdms = atoi(value);
380 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700381
382 property_get("debug.sf.disable_backpressure", value, "0");
383 mPropagateBackpressure = !atoi(value);
384 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700385
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800386 property_get("debug.sf.enable_hwc_vds", value, "0");
387 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800388 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800389
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800390 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800391 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800392 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700393
Yiwei Zhang243b3782018-05-15 17:40:04 -0700394 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700395 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
396 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
397
Ana Krulecc2870422019-01-29 19:00:58 -0800398 property_get("debug.sf.use_90Hz", value, "0");
399 mUse90Hz = atoi(value);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800400
Ana Krulecba13ab32019-02-20 14:14:12 -0800401 property_get("debug.sf.use_smart_90_for_video", value, "0");
402 mUseSmart90ForVideo = atoi(value);
403
Dan Stozaec460082018-12-17 15:35:09 -0800404 property_get("debug.sf.luma_sampling", value, "1");
405 mLumaSampling = atoi(value);
406
Ana Krulec757f63a2019-01-25 10:46:18 -0800407 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
408 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700409
Romain Guy11d63f42017-07-20 12:47:14 -0700410 // We should be reading 'persist.sys.sf.color_saturation' here
411 // but since /data may be encrypted, we need to wait until after vold
412 // comes online to attempt to read the property. The property is
413 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800414
415 if (useTrebleTestingOverride()) {
416 // Without the override SurfaceFlinger cannot connect to HIDL
417 // services that are not listed in the manifests. Considered
418 // deriving the setting from the set service name, but it
419 // would be brittle if the name that's not 'default' is used
420 // for production purposes later on.
421 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423}
424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425void SurfaceFlinger::onFirstRef()
426{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800427 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800428}
429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430SurfaceFlinger::~SurfaceFlinger()
431{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Dan Stozac7014012014-02-14 15:03:43 -0800434void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800435{
436 // the window manager died on us. prepare its eulogy.
437
Andy McFadden13a082e2012-08-24 10:16:42 -0700438 // restore initial conditions (default device unblank, etc)
439 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800440
441 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700442 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800443}
444
Robert Carr1db73f62016-12-21 12:58:51 -0800445static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700446 status_t err = client->initCheck();
447 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800448 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449 }
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return nullptr;
451}
452
453sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
454 return initClient(new Client(this));
455}
456
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700457sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
458 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459{
460 class DisplayToken : public BBinder {
461 sp<SurfaceFlinger> flinger;
462 virtual ~DisplayToken() {
463 // no more references, this display must be terminated
464 Mutex::Autolock _l(flinger->mStateLock);
465 flinger->mCurrentState.displays.removeItem(this);
466 flinger->setTransactionFlags(eDisplayTransactionNeeded);
467 }
468 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700469 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 : flinger(flinger) {
471 }
472 };
473
474 sp<BBinder> token = new DisplayToken(this);
475
476 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 // Display ID is assigned when virtual display is allocated by HWC.
478 DisplayDeviceState state;
479 state.isSecure = secure;
480 state.displayName = displayName;
481 mCurrentState.displays.add(token, state);
482 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700483 return token;
484}
485
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 Mutex::Autolock _l(mStateLock);
488
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
490 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700491 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 return;
493 }
494
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
496 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700497 ALOGE("destroyDisplay called for non-virtual display");
498 return;
499 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500 mInterceptor->saveDisplayDeletion(state.sequenceId);
501 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 setTransactionFlags(eDisplayTransactionNeeded);
503}
504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
506 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800508 const auto internalDisplayId = getInternalDisplayIdLocked();
509 if (!internalDisplayId) {
510 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700511 }
512
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800513 std::vector<PhysicalDisplayId> displayIds;
514 displayIds.reserve(mPhysicalDisplayTokens.size());
515 displayIds.push_back(internalDisplayId->value);
516
517 for (const auto& [id, token] : mPhysicalDisplayTokens) {
518 if (id != *internalDisplayId) {
519 displayIds.push_back(id.value);
520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700522
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800523 return displayIds;
524}
525
526sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
527 Mutex::Autolock lock(mStateLock);
528 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529}
530
Ady Abraham37965d42018-11-01 13:43:32 -0700531status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
532 if (!outGetColorManagement) {
533 return BAD_VALUE;
534 }
535 *outGetColorManagement = useColorManagement;
536 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700537}
538
Lloyd Pique441d5042018-10-18 16:49:51 -0700539HWComposer& SurfaceFlinger::getHwComposer() const {
540 return mCompositionEngine->getHwComposer();
541}
542
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700543renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
544 return mCompositionEngine->getRenderEngine();
545}
546
Lloyd Pique70d91362018-10-18 16:02:55 -0700547compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
548 return *mCompositionEngine.get();
549}
550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800551void SurfaceFlinger::bootFinished()
552{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700553 if (mStartPropertySetThread->join() != NO_ERROR) {
554 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556 const nsecs_t now = systemTime();
557 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000558 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559
560 // wait patiently for the window manager death
561 const String16 name("window");
562 sp<IBinder> window(defaultServiceManager()->getService(name));
563 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565 }
Robert Carr720e5062018-07-30 17:45:14 -0700566 sp<IBinder> input(defaultServiceManager()->getService(
567 String16("inputflinger")));
568 if (input == nullptr) {
569 ALOGE("Failed to link to input service");
570 } else {
571 mInputFlinger = interface_cast<IInputFlinger>(input);
572 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700573
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 if (mVrFlinger) {
575 mVrFlinger->OnBootFinished();
576 }
577
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700578 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700579 // formerly we would just kill the process, but we now ask it to exit so it
580 // can choose where to stop the animation.
581 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700582
583 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
584 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
585 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700586
Ana Krulecbd6654b2019-02-15 15:18:15 -0800587 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800590
591 // TODO(b/122905403): Once the display policy is completely integrated, this flag should go
592 // away and it should be controlled by flipping the switch in setting. The switch in
593 // settings should only be available to P19 devices, if they are opted into 90Hz fishfood.
594 // The boot must be complete before we can set the active config.
595
596 if (mUse90Hz) {
597 mPhaseOffsets->setRefreshRateType(
598 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
599 setRefreshRateTo(RefreshRateType::PERFORMANCE);
600 } else {
601 mPhaseOffsets->setRefreshRateType(
602 scheduler::RefreshRateConfigs::RefreshRateType::DEFAULT);
603 setRefreshRateTo(RefreshRateType::DEFAULT);
604 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800605 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800606}
607
Dan Stoza436ccf32018-06-21 12:10:12 -0700608uint32_t SurfaceFlinger::getNewTexture() {
609 {
610 std::lock_guard lock(mTexturePoolMutex);
611 if (!mTexturePool.empty()) {
612 uint32_t name = mTexturePool.back();
613 mTexturePool.pop_back();
614 ATRACE_INT("TexturePoolSize", mTexturePool.size());
615 return name;
616 }
617
618 // The pool was too small, so increase it for the future
619 ++mTexturePoolSize;
620 }
621
622 // The pool was empty, so we need to get a new texture name directly using a
623 // blocking call to the main thread
624 uint32_t name = 0;
625 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
626 return name;
627}
628
Mathias Agopian3f844832013-08-07 21:24:32 -0700629void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700630 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700631}
632
Wei Wangf9b05ee2017-07-19 20:59:39 -0700633// Do not call property_set on main thread which will be blocked by init
634// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700635void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700636 ALOGI( "SurfaceFlinger's main thread ready to run. "
637 "Initializing graphics H/W...");
638
Ana Krulec757f63a2019-01-25 10:46:18 -0800639 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900640
Steven Thomasb02664d2017-07-26 18:48:28 -0700641 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700642 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800643 mScheduler =
644 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
645 auto resyncCallback =
646 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800647
Ana Krulecc2870422019-01-29 19:00:58 -0800648 mAppConnectionHandle =
649 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
650 resyncCallback,
651 impl::EventThread::InterceptVSyncsCallback());
652 mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
653 resyncCallback, [this](nsecs_t timestamp) {
654 mInterceptor->saveVSyncEvent(timestamp);
655 });
656
657 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
658 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
659 mSfConnectionHandle.get());
660
Steven Thomasb02664d2017-07-26 18:48:28 -0700661 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700662 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700663 renderEngineFeature |= (useColorManagement ?
664 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700665 renderEngineFeature |= (useContextPriority ?
666 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700667
668 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800669 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700670 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700671 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800672 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700673
674 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
675 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700676 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
677 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800678 // Process any initial hotplug and resulting display changes.
679 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 const auto display = getDefaultDisplayDeviceLocked();
681 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700682 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800684
Steven Thomas050b2c82017-03-06 11:45:16 -0800685 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700687 // This callback is called from the vr flinger dispatch thread. We
688 // need to call signalTransaction(), which requires holding
689 // mStateLock when we're not on the main thread. Acquiring
690 // mStateLock from the vr flinger dispatch thread might trigger a
691 // deadlock in surface flinger (see b/66916578), so post a message
692 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700693 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700694 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
695 mVrFlingerRequestsDisplay = requestDisplay;
696 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700697 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700699 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
700 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700701 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700702 .value_or(0),
703 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800704 if (!mVrFlinger) {
705 ALOGE("Failed to start vrflinger");
706 }
707 }
708
Mathias Agopian92a979a2012-08-02 18:32:23 -0700709 // initialize our drawing state
710 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700711
Andy McFadden13a082e2012-08-24 10:16:42 -0700712 // set initial conditions (e.g. unblank default device)
713 initializeDisplays();
714
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700715 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700716
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700718
719 const bool presentFenceReliable =
720 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
721 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700722
723 if (mStartPropertySetThread->Start() != NO_ERROR) {
724 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800725 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726
Kevin DuBois36233132019-02-19 14:08:55 -0800727 if (mUse90Hz) {
728 mScheduler->setExpiredIdleTimerCallback([this] {
729 Mutex::Autolock lock(mStateLock);
730 setRefreshRateTo(RefreshRateType::DEFAULT);
731 });
732 mScheduler->setResetIdleTimerCallback([this] {
733 Mutex::Autolock lock(mStateLock);
734 setRefreshRateTo(RefreshRateType::PERFORMANCE);
735 });
736 }
Ana Krulecc2870422019-01-29 19:00:58 -0800737 mRefreshRateStats = std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
738 *display->getId()),
739 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800740
Dan Stoza9e56aa02015-11-02 13:00:03 -0800741 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700742}
743
Romain Guy11d63f42017-07-20 12:47:14 -0700744void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700745 Mutex::Autolock _l(mStateLock);
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747 char value[PROPERTY_VALUE_MAX];
748
749 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100753
754 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700755 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800756
757 property_get("persist.sys.sf.color_mode", value, "0");
758 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700759}
760
Mathias Agopiana67e4182012-06-19 17:26:12 -0700761void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800762 // Start boot animation service by setting a property mailbox
763 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700764 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700766 if (mStartPropertySetThread->join() != NO_ERROR) {
767 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800768 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700769}
770
Mathias Agopian875d8e12013-06-07 15:35:48 -0700771size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700772 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700773}
774
Mathias Agopian875d8e12013-06-07 15:35:48 -0700775size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700776 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700777}
778
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800779// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800780
Jamie Gennis582270d2011-08-17 18:19:00 -0700781bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800782 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800783 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800784 return authenticateSurfaceTextureLocked(bufferProducer);
785}
786
787bool SurfaceFlinger::authenticateSurfaceTextureLocked(
788 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800789 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800790 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800791}
792
Brian Anderson6b376712017-04-04 10:51:39 -0700793status_t SurfaceFlinger::getSupportedFrameTimestamps(
794 std::vector<FrameEvent>* outSupported) const {
795 *outSupported = {
796 FrameEvent::REQUESTED_PRESENT,
797 FrameEvent::ACQUIRE,
798 FrameEvent::LATCH,
799 FrameEvent::FIRST_REFRESH_START,
800 FrameEvent::LAST_REFRESH_START,
801 FrameEvent::GPU_COMPOSITION_DONE,
802 FrameEvent::DEQUEUE_READY,
803 FrameEvent::RELEASE,
804 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700805 ConditionalLock _l(mStateLock,
806 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700807 if (!getHwComposer().hasCapability(
808 HWC2::Capability::PresentFenceIsNotReliable)) {
809 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
810 }
811 return NO_ERROR;
812}
813
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800814status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
815 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700816 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 return BAD_VALUE;
818 }
819
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800820 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 if (!displayId) {
822 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700823 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 // TODO: Not sure if display density should handled by SF any longer
826 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700827 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700829 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800830 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700831 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 }
833 return density;
834 }
835 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700836 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("ro.sf.lcd_density"); }
840 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700841
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Dominik Laskowski075d3172018-05-24 15:50:06 -0700844 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 DisplayInfo info = DisplayInfo();
846
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 float xdpi = hwConfig->getDpiX();
848 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700849
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700850 info.w = hwConfig->getWidth();
851 info.h = hwConfig->getHeight();
852 // Default display viewport to display width and height
853 info.viewportW = info.w;
854 info.viewportH = info.h;
855
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800856 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 // The density of the device is provided by a build property
858 float density = Density::getBuildDensity() / 160.0f;
859 if (density == 0) {
860 // the build doesn't provide a density -- this is wrong!
861 // use xdpi instead
862 ALOGE("ro.sf.lcd_density must be defined as a build property");
863 density = xdpi / 160.0f;
864 }
865 if (Density::getEmuDensity()) {
866 // if "qemu.sf.lcd_density" is specified, it overrides everything
867 xdpi = ydpi = density = Density::getEmuDensity();
868 density /= 160.0f;
869 }
870 info.density = density;
871
872 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700873 const auto display = getDefaultDisplayDeviceLocked();
874 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700875
876 // This is for screenrecord
877 const Rect viewport = display->getViewport();
878 if (viewport.isValid()) {
879 info.viewportW = uint32_t(viewport.getWidth());
880 info.viewportH = uint32_t(viewport.getHeight());
881 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700882 } else {
883 // TODO: where should this value come from?
884 static const int TV_DENSITY = 213;
885 info.density = TV_DENSITY / 160.0f;
886 info.orientation = 0;
887 }
888
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 info.xdpi = xdpi;
890 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800891 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800892 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893
Andy McFadden91b2ca82014-06-13 14:04:23 -0700894 // This is how far in advance a buffer must be queued for
895 // presentation at a given time. If you want a buffer to appear
896 // on the screen at time N, you must submit the buffer before
897 // (N - presentationDeadline).
898 //
899 // Normally it's one full refresh period (to give SF a chance to
900 // latch the buffer), but this can be reduced by configuring a
901 // DispSync offset. Any additional delays introduced by the hardware
902 // composer or panel must be accounted for here.
903 //
904 // We add an additional 1ms to allow for processing time and
905 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800906 info.presentationDeadline =
907 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700908
909 // All non-virtual displays are currently considered secure.
910 info.secure = true;
911
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800912 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700913 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800914 std::swap(info.w, info.h);
915 }
916
Michael Wright28f24d02016-07-12 13:30:53 -0700917 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700918 }
919
Dan Stoza7f7da322014-05-02 15:26:25 -0700920 return NO_ERROR;
921}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700922
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
924 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700925 return BAD_VALUE;
926 }
927
Ana Krulecc2870422019-01-29 19:00:58 -0800928 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return NO_ERROR;
930}
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
933 const auto display = getDisplayDevice(displayToken);
934 if (!display) {
935 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800936 return BAD_VALUE;
937 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700940}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700941
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
943 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800944
Ana Krulec7d1d6832018-12-27 11:10:09 -0800945 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 // Lock is acquired by setRefreshRateTo.
947 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
949 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
950 return;
951 }
952
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953 // Lock is acquired by setRefreshRateTo.
954 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800955 if (!display) {
956 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
957 displayToken.get());
958 return;
959 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700960 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800961 ALOGW("Attempt to set active config %d for virtual display", mode);
962 return;
963 }
964 int currentDisplayPowerMode = display->getPowerMode();
965 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
966 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700967 return;
968 }
969
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970 // Don't check against the current mode yet. Worst case we set the desired
971 // config twice.
Ady Abrahamb838aed2019-02-12 15:30:16 -0800972 std::lock_guard<std::mutex> lock(mActiveConfigLock);
973 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
974
975 if (!mDesiredActiveConfigChanged) {
976 // This is the first time we set the desired
977 mScheduler->pauseVsyncCallback(mAppConnectionHandle, true);
978
979 // This will trigger HWC refresh without resetting the idle timer.
980 repaintEverythingForHWC();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800982 mDesiredActiveConfigChanged = true;
983 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
986status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
987 ATRACE_CALL();
988 postMessageSync(new LambdaMessage(
989 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
990 return NO_ERROR;
991}
992
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993void SurfaceFlinger::setActiveConfigInternal() {
994 ATRACE_CALL();
995
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ana Krulecc2870422019-01-29 19:00:58 -0800997 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998
999 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1000 display->setActiveConfig(mUpcomingActiveConfig.configId);
1001
Ana Krulecc2870422019-01-29 19:00:58 -08001002 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001003 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1004}
1005
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006bool SurfaceFlinger::performSetActiveConfig() NO_THREAD_SAFETY_ANALYSIS {
Alec Mourife3dc942019-02-12 14:19:18 -08001007 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 // we may be in the process of changing the active state
1009 if (mWaitForNextInvalidate) {
1010 mWaitForNextInvalidate = false;
1011
1012 repaintEverythingForHWC();
1013 // We do not want to give another frame to HWC while we are transitioning.
1014 return true;
1015 }
1016
1017 if (mCheckPendingFence) {
1018 if (mPreviousPresentFence != Fence::NO_FENCE &&
1019 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled)) {
1020 // fence has not signaled yet. wait for the next invalidate
1021 repaintEverythingForHWC();
1022 return true;
1023 }
1024
1025 // We received the present fence from the HWC, so we assume it successfully updated
1026 // the config, hence we update SF.
1027 mCheckPendingFence = false;
1028 setActiveConfigInternal();
1029 }
1030
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001031 // Store the local variable to release the lock.
1032 ActiveConfigInfo desiredActiveConfig;
1033 {
1034 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 if (!mDesiredActiveConfigChanged) {
1036 return false;
1037 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001038 desiredActiveConfig = mDesiredActiveConfig;
1039 }
1040
1041 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001042 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1043 // display is not valid or we are already in the requested mode
1044 // on both cases there is nothing left to do
1045 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1046 mScheduler->pauseVsyncCallback(mAppConnectionHandle, false);
1047 mDesiredActiveConfigChanged = false;
1048 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1049 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001050 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001051
1052 // Desired active config was set, it is different than the config currently in use. Notify HWC.
1053 mUpcomingActiveConfig = desiredActiveConfig;
1054 const auto displayId = display->getId();
1055 LOG_ALWAYS_FATAL_IF(!displayId);
1056
1057 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1058 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1059
1060 // we need to submit an empty frame to HWC to start the process
1061 mWaitForNextInvalidate = true;
1062 mCheckPendingFence = true;
1063
1064 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001065}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1068 Vector<ColorMode>* outColorModes) {
1069 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001070 return BAD_VALUE;
1071 }
1072
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001074 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001075 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1076
1077 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1078 if (!displayId) {
1079 return NAME_NOT_FOUND;
1080 }
1081
Dominik Laskowski075d3172018-05-24 15:50:06 -07001082 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001083 }
Michael Wright28f24d02016-07-12 13:30:53 -07001084 outColorModes->clear();
1085 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1086
1087 return NO_ERROR;
1088}
1089
Daniel Solomon42d04562019-01-20 21:03:19 -08001090status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1091 ui::DisplayPrimaries &primaries) {
1092 if (!displayToken) {
1093 return BAD_VALUE;
1094 }
1095
1096 // Currently we only support this API for a single internal display.
1097 if (getInternalDisplayToken() != displayToken) {
1098 return BAD_VALUE;
1099 }
1100
1101 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1102 return NO_ERROR;
1103}
1104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001105ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1106 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001107 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001108 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001109 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001110}
1111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001113 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 Vector<ColorMode> modes;
1115 getDisplayColorModes(displayToken, &modes);
1116 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1117 if (mode < ColorMode::NATIVE || !exists) {
1118 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1119 decodeColorMode(mode).c_str(), mode, displayToken.get());
1120 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001121 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 const auto display = getDisplayDevice(displayToken);
1123 if (!display) {
1124 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 } else if (display->isVirtual()) {
1127 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1128 decodeColorMode(mode).c_str(), mode);
1129 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001130 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1131 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001132 }
1133 }));
1134
Michael Wright28f24d02016-07-12 13:30:53 -07001135 return NO_ERROR;
1136}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001137
Svetoslavd85084b2014-03-20 10:28:31 -07001138status_t SurfaceFlinger::clearAnimationFrameStats() {
1139 Mutex::Autolock _l(mStateLock);
1140 mAnimFrameTracker.clearStats();
1141 return NO_ERROR;
1142}
1143
1144status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1145 Mutex::Autolock _l(mStateLock);
1146 mAnimFrameTracker.getStats(outStats);
1147 return NO_ERROR;
1148}
1149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1151 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001152 Mutex::Autolock _l(mStateLock);
1153
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001154 const auto display = getDisplayDeviceLocked(displayToken);
1155 if (!display) {
1156 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001157 return BAD_VALUE;
1158 }
1159
Peiyong Linfb069302018-04-25 14:34:31 -07001160 // At this point the DisplayDeivce should already be set up,
1161 // meaning the luminance information is already queried from
1162 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001164 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1165 capabilities.getDesiredMaxLuminance(),
1166 capabilities.getDesiredMaxAverageLuminance(),
1167 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001168
1169 return NO_ERROR;
1170}
1171
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001172status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1173 ui::PixelFormat* outFormat,
1174 ui::Dataspace* outDataspace,
1175 uint8_t* outComponentMask) const {
1176 if (!outFormat || !outDataspace || !outComponentMask) {
1177 return BAD_VALUE;
1178 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001179 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001180 if (!display || !display->getId()) {
1181 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1182 return BAD_VALUE;
1183 }
1184 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1185 outDataspace, outComponentMask);
1186}
1187
Kevin DuBois74e53772018-11-19 10:52:38 -08001188status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1189 bool enable, uint8_t componentMask,
1190 uint64_t maxFrames) const {
1191 const auto display = getDisplayDevice(displayToken);
1192 if (!display || !display->getId()) {
1193 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1194 return BAD_VALUE;
1195 }
1196
1197 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1198 componentMask, maxFrames);
1199}
1200
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001201status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1202 uint64_t maxFrames, uint64_t timestamp,
1203 DisplayedFrameStats* outStats) const {
1204 const auto display = getDisplayDevice(displayToken);
1205 if (!display || !display->getId()) {
1206 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1207 return BAD_VALUE;
1208 }
1209
1210 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1211 outStats);
1212}
1213
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001214status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1215 if (!outSupported) {
1216 return BAD_VALUE;
1217 }
1218 *outSupported = getRenderEngine().supportsProtectedContent();
1219 return NO_ERROR;
1220}
1221
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001222status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1223 bool* outIsWideColorDisplay) const {
1224 if (!displayToken || !outIsWideColorDisplay) {
1225 return BAD_VALUE;
1226 }
1227 Mutex::Autolock _l(mStateLock);
1228 const auto display = getDisplayDeviceLocked(displayToken);
1229 if (!display) {
1230 return BAD_VALUE;
1231 }
1232 *outIsWideColorDisplay = display->hasWideColorGamut();
1233 return NO_ERROR;
1234}
1235
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001236status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001237 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001238 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001239
Chia-I Wu90f669f2017-10-05 14:24:41 -07001240 if (mInjectVSyncs == enable) {
1241 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001242 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001243
Ana Krulecc2870422019-01-29 19:00:58 -08001244 auto resyncCallback =
1245 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001246
Ana Krulec98b5b242018-08-10 15:03:23 -07001247 // TODO(akrulec): Part of the Injector should be refactored, so that it
1248 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001249 if (enable) {
1250 ALOGV("VSync Injections enabled");
1251 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001252 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001253 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001254 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001255 impl::EventThread::InterceptVSyncsCallback(),
1256 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001258 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001259 } else {
1260 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001261 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1262 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001263 }
1264
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001265 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001266 }));
1267
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001268 return NO_ERROR;
1269}
1270
1271status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 Mutex::Autolock _l(mStateLock);
1273
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001274 if (!mInjectVSyncs) {
1275 ALOGE("VSync Injections not enabled");
1276 return BAD_VALUE;
1277 }
1278 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1279 ALOGV("Injecting VSync inside SurfaceFlinger");
1280 mVSyncInjector->onInjectSyncEvent(when);
1281 }
1282 return NO_ERROR;
1283}
1284
Lloyd Pique755e3192018-01-31 16:46:15 -08001285status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1286 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001287 // Try to acquire a lock for 1s, fail gracefully
1288 const status_t err = mStateLock.timedLock(s2ns(1));
1289 const bool locked = (err == NO_ERROR);
1290 if (!locked) {
1291 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1292 return TIMED_OUT;
1293 }
1294
1295 outLayers->clear();
1296 mCurrentState.traverseInZOrder([&](Layer* layer) {
1297 outLayers->push_back(layer->getLayerDebugInfo());
1298 });
1299
1300 mStateLock.unlock();
1301 return NO_ERROR;
1302}
1303
Peiyong Linc6780972018-10-28 15:24:08 -07001304status_t SurfaceFlinger::getCompositionPreference(
1305 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1306 Dataspace* outWideColorGamutDataspace,
1307 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001308 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001309 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001310 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001311 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001312 return NO_ERROR;
1313}
1314
Dan Stozaec460082018-12-17 15:35:09 -08001315status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1316 const sp<IBinder>& stopLayerHandle,
1317 const sp<IRegionSamplingListener>& listener) {
1318 if (!listener) {
1319 return BAD_VALUE;
1320 }
1321 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001322 return NO_ERROR;
1323}
1324
Dan Stozaec460082018-12-17 15:35:09 -08001325status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1326 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001327 return NO_ERROR;
1328}
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001329// ----------------------------------------------------------------------------
1330
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001331sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1332 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulecc2870422019-01-29 19:00:58 -08001333 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001334 Mutex::Autolock lock(mStateLock);
1335 return getVsyncPeriod();
1336 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001337
Ana Krulecc2870422019-01-29 19:00:58 -08001338 const auto& handle =
1339 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001340
Ana Krulecc2870422019-01-29 19:00:58 -08001341 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Mathias Agopianbb641242010-05-18 17:06:55 -07001342}
1343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001344// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345
1346void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001347 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001348}
1349
1350void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001351 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001352}
1353
1354void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001355 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001356}
1357
1358void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001359 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001360 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001361}
1362
1363status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001364 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001365 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001366}
1367
1368status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001369 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001370 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001371 if (res == NO_ERROR) {
1372 msg->wait();
1373 }
1374 return res;
1375}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001376
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001377void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001378 do {
1379 waitForEvent();
1380 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001381}
1382
Dominik Laskowski83b88212018-12-11 13:34:06 -08001383nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001384 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001385 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1386 return 0;
1387 }
1388
1389 const auto config = getHwComposer().getActiveConfig(*displayId);
1390 return config ? config->getVsyncPeriod() : 0;
1391}
1392
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001393void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1394 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001395 ATRACE_NAME("SF onVsync");
1396
Steven Thomas3cfac282017-02-06 12:29:30 -08001397 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001398 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001399 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001400 return;
1401 }
1402
Dominik Laskowski075d3172018-05-24 15:50:06 -07001403 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001404 return;
1405 }
1406
Dominik Laskowski075d3172018-05-24 15:50:06 -07001407 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001408 // For now, we don't do anything with external display vsyncs.
1409 return;
1410 }
1411
Ana Krulecc2870422019-01-29 19:00:58 -08001412 mScheduler->addResyncSample(timestamp);
Mathias Agopian148994e2012-09-19 17:31:36 -07001413}
1414
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001415void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001416 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1417 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001418}
1419
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001420void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1421 mPhaseOffsets->setRefreshRateType(refreshRate);
1422
1423 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1424 mVsyncModulator.setPhaseOffsets(early, gl, late);
1425
1426 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001427 return;
1428 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001429
Ana Krulec7d1d6832018-12-27 11:10:09 -08001430 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1431 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1432 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1433 // refresh cycle.
1434
1435 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001436 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001437 if (currentVsyncPeriod == 0) {
1438 return;
1439 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001440
Ana Krulec7d1d6832018-12-27 11:10:09 -08001441 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1442 // floating numbers.
1443 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001444 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1445 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001446 if (std::abs(currentFps - newFps) <= 1) {
1447 return;
1448 }
1449
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001450 const auto displayId = getInternalDisplayIdLocked();
1451 LOG_ALWAYS_FATAL_IF(!displayId);
1452
1453 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001454 for (int i = 0; i < configs.size(); i++) {
1455 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1456 if (vsyncPeriod == 0) {
1457 continue;
1458 }
1459 const float fps = 1e9 / vsyncPeriod;
1460 // TODO(b/113612090): There should be a better way at determining which config
1461 // has the right refresh rate.
1462 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001463 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001464 }
1465 }
1466}
1467
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001468void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001469 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001471 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001472
Lloyd Piqueba04e622017-12-14 17:11:26 -08001473 // Ignore events that do not have the right sequenceId.
1474 if (sequenceId != getBE().mComposerSequenceId) {
1475 return;
1476 }
1477
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 // Only lock if we're not on the main thread. This function is normally
1479 // called on a hwbinder thread, but for the primary display it's called on
1480 // the main thread with the state lock already held, so don't attempt to
1481 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001482 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001483
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001484 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001485
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001486 if (std::this_thread::get_id() == mMainThreadId) {
1487 // Process all pending hot plug events immediately if we are on the main thread.
1488 processDisplayHotplugEventsLocked();
1489 }
1490
Lloyd Piqueba04e622017-12-14 17:11:26 -08001491 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001492}
1493
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001494void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001495 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001496 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001498 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001499 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001500}
1501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001502void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001503 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001504 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001505 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001506 getHwComposer().setVsyncEnabled(*displayId,
1507 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1508 }
Mathias Agopian86303202012-07-24 22:46:10 -07001509}
1510
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001511// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001512void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001513 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001514 // Clear the drawing state so that the logic inside of
1515 // handleTransactionLocked will fire. It will determine the delta between
1516 // mCurrentState and mDrawingState and re-apply all changes when we make the
1517 // transition.
1518 mDrawingState.displays.clear();
1519 mDisplays.clear();
1520}
1521
Steven Thomas050b2c82017-03-06 11:45:16 -08001522void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001523 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001524 if (!mVrFlinger)
1525 return;
1526 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001527 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001528 return;
1529 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530
Lloyd Pique441d5042018-10-18 16:49:51 -07001531 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 ALOGE("Vr flinger is only supported for remote hardware composer"
1533 " service connections. Ignoring request to transition to vr"
1534 " flinger.");
1535 mVrFlingerRequestsDisplay = false;
1536 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001537 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001538
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540
Steven Thomas0123ac62018-07-12 11:32:34 -07001541 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001542 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001543
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001544 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001545
1546 // Clear out all the output layers from the composition engine for all
1547 // displays before destroying the hardware composer interface. This ensures
1548 // any HWC layers are destroyed through that interface before it becomes
1549 // invalid.
1550 for (const auto& [token, displayDevice] : mDisplays) {
1551 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1552 compositionengine::Output::OutputLayers());
1553 }
1554
Steven Thomas0123ac62018-07-12 11:32:34 -07001555 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1556 // called below. Clear the reference now so we don't accidentally use it
1557 // later.
1558 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001559
Steven Thomasb02664d2017-07-26 18:48:28 -07001560 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001561 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001562 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001563
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001565 // Delete the current instance before creating the new one
1566 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1567 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1568 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1569 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001570
Lloyd Pique441d5042018-10-18 16:49:51 -07001571 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001572 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001573
1574 if (vrFlingerRequestsDisplay) {
1575 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001576 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577
1578 mVisibleRegionsDirty = true;
1579 invalidateHwcGeometry();
1580
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001581 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001582 display = getDefaultDisplayDeviceLocked();
1583 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001584 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001585
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001587 const nsecs_t vsyncPeriod = getVsyncPeriod();
1588 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001589
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590 // The present fences returned from vr_hwc are not an accurate
1591 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001592 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001593
Steven Thomasb02664d2017-07-26 18:48:28 -07001594 // Use phase of 0 since phase is not known.
1595 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001596 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001597 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001598
Ana Krulecc2870422019-01-29 19:00:58 -08001599 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001600
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001601 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001602 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001603}
1604
Mathias Agopian4fec8732012-06-29 14:12:52 -07001605void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001606 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001607 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001608 case MessageQueue::INVALIDATE: {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001609 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001610 break;
1611 }
1612
Ana Krulecba13ab32019-02-20 14:14:12 -08001613 if (mUse90Hz && mUseSmart90ForVideo) {
1614 // This call is made each time SF wakes up and creates a new frame. It is part
1615 // of video detection feature.
1616 mScheduler->incrementFrameCounter();
1617 }
Alec Mourife3dc942019-02-12 14:19:18 -08001618 bool frameMissed = mPreviousPresentFence != Fence::NO_FENCE &&
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001619 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Alec Mourife3dc942019-02-12 14:19:18 -08001620 bool hwcFrameMissed = !mHadClientComposition && frameMissed;
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001621 if (frameMissed) {
Alec Mourife3dc942019-02-12 14:19:18 -08001622 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1623 mFrameMissedCount++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001624 mTimeStats->incrementMissedFrames();
Alec Mourife3dc942019-02-12 14:19:18 -08001625 }
1626 // For now, only propagate backpressure when missing a hwc frame.
1627 if (hwcFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001628 if (mPropagateBackpressure) {
1629 signalLayerUpdate();
1630 break;
1631 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001632 }
Dan Stoza50182882016-07-08 12:02:20 -07001633
Steven Thomas050b2c82017-03-06 11:45:16 -08001634 // Now that we're going to make it to the handleMessageTransaction()
1635 // call below it's safe to call updateVrFlinger(), which will
1636 // potentially trigger a display handoff.
1637 updateVrFlinger();
1638
Dan Stoza6b9454d2014-11-07 16:00:59 -08001639 bool refreshNeeded = handleMessageTransaction();
1640 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001641
1642 updateCursorAsync();
1643 updateInputFlinger();
1644
Dan Stoza58784442014-12-02 16:58:17 -08001645 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001646 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001647 // Signal a refresh if a transaction modified the window state,
1648 // a new buffer was latched, or if HWC has requested a full
1649 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001650 signalRefresh();
1651 }
1652 break;
1653 }
1654 case MessageQueue::REFRESH: {
1655 handleMessageRefresh();
1656 break;
1657 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001658 }
1659}
1660
Dan Stoza6b9454d2014-11-07 16:00:59 -08001661bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001662 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001663 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001664
1665 // Apply any ready transactions in the queues if there are still transactions that have not been
1666 // applied, wake up during the next vsync period and check again
1667 bool transactionNeeded = false;
1668 if (!flushTransactionQueues()) {
1669 transactionNeeded = true;
1670 }
1671
Mathias Agopian4fec8732012-06-29 14:12:52 -07001672 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001673 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001674 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001675
1676 if (transactionNeeded) {
1677 setTransactionFlags(eTransactionNeeded);
1678 }
1679
1680 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001681}
1682
Mathias Agopian4fec8732012-06-29 14:12:52 -07001683void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001684 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001685
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001686 mRefreshPending = false;
1687
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001688 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001689 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001690 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001691 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001692 for (const auto& [token, display] : mDisplays) {
1693 beginFrame(display);
1694 prepareFrame(display);
1695 doDebugFlashRegions(display, repaintEverything);
1696 doComposition(display, repaintEverything);
1697 }
1698
Adrian Roos1e1a1282017-11-01 19:05:31 +01001699 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001700 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001701
1702 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001703 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001704
Dan Stozabfbffeb2016-07-21 14:49:33 -07001705 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001706 for (const auto& [token, displayDevice] : mDisplays) {
1707 auto display = displayDevice->getCompositionDisplay();
1708 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001709 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001710 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001711 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001712
Jorim Jaggi90535212018-05-23 23:44:06 +02001713 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001714
David Sodman7e4ae112018-02-09 15:02:28 -08001715 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001716
1717 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001719
David Sodmanfa9b2af2017-12-24 13:28:59 -08001720
1721bool SurfaceFlinger::handleMessageInvalidate() {
1722 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001723 bool refreshNeeded = handlePageFlip();
1724
Vishnu Nair4351ad52019-02-11 14:13:02 -08001725 if (mVisibleRegionsDirty) {
1726 computeLayerBounds();
1727 }
1728
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001729 for (auto& layer : mLayersPendingRefresh) {
1730 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001731 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001732 invalidateLayerStack(layer, visibleReg);
1733 }
1734 mLayersPendingRefresh.clear();
1735 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001736}
1737
David Sodman79bba0e2018-08-05 18:07:49 -07001738void SurfaceFlinger::calculateWorkingSet() {
1739 ATRACE_CALL();
1740 ALOGV(__FUNCTION__);
1741
David Sodman79bba0e2018-08-05 18:07:49 -07001742 // build the h/w work list
1743 if (CC_UNLIKELY(mGeometryInvalid)) {
1744 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001745 for (const auto& [token, displayDevice] : mDisplays) {
1746 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001747 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001748 if (!displayId) {
1749 continue;
1750 }
David Sodman79bba0e2018-08-05 18:07:49 -07001751
Lloyd Pique32cbe282018-10-19 13:09:22 -07001752 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001753 for (size_t i = 0; i < currentLayers.size(); i++) {
1754 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001755
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001756 if (!layer->hasHwcLayer(displayDevice)) {
Lloyd Pique07e33212018-12-18 16:33:37 -08001757 layer->forceClientComposition(displayDevice);
1758 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001759 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001760
Lloyd Pique32cbe282018-10-19 13:09:22 -07001761 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001762 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001763 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001764 }
David Sodman79bba0e2018-08-05 18:07:49 -07001765 }
1766 }
1767 }
1768
1769 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001770 for (const auto& [token, displayDevice] : mDisplays) {
1771 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001772 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001773 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001774 continue;
1775 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001776 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001777
1778 if (mDrawingState.colorMatrixChanged) {
1779 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001780 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001781 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001782 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001783 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001784 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1785 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001786 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001787 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001788 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1789 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001790 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001791 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001792 }
1793
Peiyong Lind3788632018-09-18 16:01:31 -07001794 // TODO(b/111562338) remove when composer 2.3 is shipped.
1795 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001796 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001797 }
1798
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001799 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001800 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001801 }
1802
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001803 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001804 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001805 layer->setCompositionType(displayDevice,
1806 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001807 continue;
1808 }
1809
Lloyd Pique32cbe282018-10-19 13:09:22 -07001810 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001811 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001812 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001813 }
1814
Peiyong Lin13effd12018-07-24 17:01:47 -07001815 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001816 ColorMode colorMode;
1817 Dataspace dataSpace;
1818 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001819 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001821 }
1822 }
1823
1824 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001825
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001826 for (const auto& [token, displayDevice] : mDisplays) {
1827 auto display = displayDevice->getCompositionDisplay();
1828 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001829 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001830 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1831 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1832 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001833 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001834 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001835 }
1836 }
David Sodman79bba0e2018-08-05 18:07:49 -07001837}
1838
Lloyd Pique32cbe282018-10-19 13:09:22 -07001839void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1840 bool repaintEverything) {
1841 auto display = displayDevice->getCompositionDisplay();
1842 const auto& displayState = display->getState();
1843
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844 // is debugging enabled
1845 if (CC_LIKELY(!mDebugRegion))
1846 return;
1847
Lloyd Pique32cbe282018-10-19 13:09:22 -07001848 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001849 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001850 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001851 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001852 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001853 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001854 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001855
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001856 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857 }
1858 }
1859
Lloyd Pique32cbe282018-10-19 13:09:22 -07001860 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861
1862 if (mDebugRegion > 1) {
1863 usleep(mDebugRegion * 1000);
1864 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001865
Lloyd Pique32cbe282018-10-19 13:09:22 -07001866 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867}
1868
Adrian Roos1e1a1282017-11-01 19:05:31 +01001869void SurfaceFlinger::doTracing(const char* where) {
1870 ATRACE_CALL();
1871 ATRACE_NAME(where);
1872 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001873 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001874 }
1875}
1876
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001877void SurfaceFlinger::logLayerStats() {
1878 ATRACE_CALL();
1879 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001880 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001881 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001882 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001883 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001884 }
1885 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001886
1887 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001888 }
1889}
1890
David Sodman2b406362017-12-15 13:33:47 -08001891void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001892{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001893 ATRACE_CALL();
1894 ALOGV("preComposition");
1895
David Sodman2b406362017-12-15 13:33:47 -08001896 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1897
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001899 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001900 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901 needExtraInvalidate = true;
1902 }
Robert Carr2047fae2016-11-28 14:09:09 -08001903 });
1904
Mathias Agopiancd60f992012-08-16 16:28:27 -07001905 if (needExtraInvalidate) {
1906 signalLayerUpdate();
1907 }
1908}
1909
Ana Krulece588e312018-09-18 12:32:24 -07001910void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1911 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001912 // Update queue of past composite+present times and determine the
1913 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001914 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001916 while (!getBE().mCompositePresentTimes.empty()) {
1917 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001918 // Cached values should have been updated before calling this method,
1919 // which helps avoid duplicate syscalls.
1920 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1921 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1922 break;
1923 }
1924 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001925 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926 }
1927
1928 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001929 while (getBE().mCompositePresentTimes.size() > 16) {
1930 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 }
1932
Ana Krulece588e312018-09-18 12:32:24 -07001933 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001934}
1935
Ana Krulece588e312018-09-18 12:32:24 -07001936void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1937 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 // Integer division and modulo round toward 0 not -inf, so we need to
1939 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001940 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1941 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1942 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943
Ana Krulec757f63a2019-01-25 10:46:18 -08001944 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001945 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001946 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001947 }
1948
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001949 // Snap the latency to a value that removes scheduling jitter from the
1950 // composition and present times, which often have >1ms of jitter.
1951 // Reducing jitter is important if an app attempts to extrapolate
1952 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001953 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001955 nsecs_t bias = stats.vsyncPeriod / 2;
1956 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1957 nsecs_t snappedCompositeToPresentLatency =
1958 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959
David Sodman99974d22017-11-28 12:04:33 -08001960 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001961 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1962 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001963 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001964}
1965
Ady Abraham8164d482019-01-11 14:47:59 -08001966// debug patch for b/119477596 - add stack guards to catch stack
1967// corruptions and disable clang optimizations.
1968// The code below is temporary and planned to be removed once stack
1969// corruptions are found.
1970#pragma clang optimize off
1971class StackGuard {
1972public:
1973 StackGuard(const char* name, const char* func, int line) {
1974 guarders.reserve(MIN_CAPACITY);
1975 guarders.push_back({this, name, func, line});
1976 validate();
1977 }
1978 ~StackGuard() {
1979 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
1980 if (i->guard == this) {
1981 guarders.erase(i);
1982 break;
1983 }
1984 }
1985 }
1986
1987 static void validate() {
1988 for (const auto& guard : guarders) {
1989 if (guard.guard->cookie != COOKIE_VALUE) {
1990 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
1991 CallStack stack(LOG_TAG);
1992 abort();
1993 }
1994 }
1995 }
1996
1997private:
1998 uint64_t cookie = COOKIE_VALUE;
1999 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2000 static constexpr size_t MIN_CAPACITY = 16;
2001
2002 struct GuarderElement {
2003 StackGuard* guard;
2004 const char* name;
2005 const char* func;
2006 int line;
2007 };
2008
2009 static std::vector<GuarderElement> guarders;
2010};
2011std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2012
2013#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2014
2015#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002016void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017{
Ady Abraham8164d482019-01-11 14:47:59 -08002018 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 ATRACE_CALL();
2020 ALOGV("postComposition");
2021
Brian Anderson3546a3f2016-07-14 11:51:14 -07002022 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002023 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002024 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002025 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002026 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002027 }
Ady Abraham8164d482019-01-11 14:47:59 -08002028 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002029
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002030 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002031 const auto displayDevice = getDefaultDisplayDeviceLocked();
2032 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033
David Sodman73beded2017-11-15 11:56:06 -08002034 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002035 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002036 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2037
Lloyd Pique32cbe282018-10-19 13:09:22 -07002038 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002040 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2041 ->getRenderSurface()
2042 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002043 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002044 } else {
2045 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2046 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002047
Ady Abraham8164d482019-01-11 14:47:59 -08002048 ASSERT_ON_STACK_GUARD();
2049
David Sodman73beded2017-11-15 11:56:06 -08002050 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002051 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2052 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002053 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002054 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002055 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056
Ana Krulece588e312018-09-18 12:32:24 -07002057 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002058 DEFINE_STACK_GUARD(stats);
Ana Krulecc2870422019-01-29 19:00:58 -08002059 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002060
Ady Abraham8164d482019-01-11 14:47:59 -08002061 ASSERT_ON_STACK_GUARD();
2062
David Sodman2b406362017-12-15 13:33:47 -08002063 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064 // when we started doing work for this frame, but that should be okay
2065 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002066 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002067 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002068 DEFINE_STACK_GUARD(compositorTiming);
2069
Brian Andersond0010582017-03-07 13:20:31 -08002070 {
David Sodman99974d22017-11-28 12:04:33 -08002071 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002072 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002073 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002074
2075 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002076 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077
Robert Carr2047fae2016-11-28 14:09:09 -08002078 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002079 bool frameLatched =
2080 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2081 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002082 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002083 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002084 recordBufferingStats(layer->getName().string(),
2085 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002086 }
Ady Abraham8164d482019-01-11 14:47:59 -08002087 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002088 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002089
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002090 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002091 ASSERT_ON_STACK_GUARD();
Ana Krulecc2870422019-01-29 19:00:58 -08002092 mScheduler->addPresentFence(presentFenceTime);
2093 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002094 }
2095
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002096 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2098 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002099 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002100 }
2101 }
2102
Ady Abraham8164d482019-01-11 14:47:59 -08002103 ASSERT_ON_STACK_GUARD();
2104
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002105 if (mAnimCompositionPending) {
2106 mAnimCompositionPending = false;
2107
Brian Anderson4e606e32017-03-16 15:34:57 -07002108 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002109 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002110 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002111
2112 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002113 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002114 // The HWC doesn't support present fences, so use the refresh
2115 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002116 const nsecs_t presentTime =
2117 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002118 DEFINE_STACK_GUARD(presentTime);
2119
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002120 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002121 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002122 }
2123 mAnimFrameTracker.advanceFrame();
2124 }
Dan Stozab90cf072015-03-05 11:05:59 -08002125
Ady Abraham8164d482019-01-11 14:47:59 -08002126 ASSERT_ON_STACK_GUARD();
2127
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002128 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002129 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002130 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002131 }
2132
Ady Abraham8164d482019-01-11 14:47:59 -08002133 ASSERT_ON_STACK_GUARD();
2134
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002135 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002136
Ady Abraham8164d482019-01-11 14:47:59 -08002137 ASSERT_ON_STACK_GUARD();
2138
Lloyd Pique32cbe282018-10-19 13:09:22 -07002139 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2140 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002141 return;
2142 }
2143
2144 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002145 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002146 if (mHasPoweredOff) {
2147 mHasPoweredOff = false;
2148 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002149 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002150 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002151 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002152 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002153 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2154 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002155 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002156 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002157 }
David Sodman4a36e932017-11-07 14:29:47 -08002158 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002159
2160 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002161 }
David Sodman4a36e932017-11-07 14:29:47 -08002162 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002163 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002164
2165 {
2166 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002167 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002168 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002169 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002170 if (refillCount > 0) {
2171 const size_t offset = mTexturePool.size();
2172 mTexturePool.resize(mTexturePoolSize);
2173 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2174 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2175 }
Ady Abraham8164d482019-01-11 14:47:59 -08002176 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002177 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002178
Marissa Wallfda30bb2018-10-12 11:34:28 -07002179 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002180 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002181
Dan Stozaec460082018-12-17 15:35:09 -08002182 if (mLumaSampling) {
2183 mRegionSamplingThread->sampleNow();
2184 }
2185
Ady Abraham8164d482019-01-11 14:47:59 -08002186 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002187}
Ady Abraham8164d482019-01-11 14:47:59 -08002188#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002189
Vishnu Nair4351ad52019-02-11 14:13:02 -08002190void SurfaceFlinger::computeLayerBounds() {
2191 for (const auto& pair : mDisplays) {
2192 const auto& displayDevice = pair.second;
2193 const auto display = displayDevice->getCompositionDisplay();
2194 for (const auto& layer : mDrawingState.layersSortedByZ) {
2195 // only consider the layers on the given layer stack
2196 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002197 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002198 }
2199
2200 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2201 }
2202 }
2203}
2204
Mathias Agopiancd60f992012-08-16 16:28:27 -07002205void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 ATRACE_CALL();
2207 ALOGV("rebuildLayerStacks");
2208
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002209 // We need to clear these out now as these may be holding on to a
2210 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2211 // also holds a reference. When the set of visible layers is recomputed,
2212 // some layers may be destroyed if the only thing keeping them alive was
2213 // that list of visible layers associated with each display. The layer
2214 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2215 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2216 for (const auto& [token, display] : mDisplays) {
2217 getBE().mCompositionInfo[token].clear();
2218 }
2219
Mathias Agopiancd60f992012-08-16 16:28:27 -07002220 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002221 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002222 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002223 mVisibleRegionsDirty = false;
2224 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002225
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002226 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002227 const auto& displayDevice = pair.second;
2228 auto display = displayDevice->getCompositionDisplay();
2229 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002230 Region opaqueRegion;
2231 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002232 compositionengine::Output::OutputLayers layersSortedByZ;
2233 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002234 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002235 const ui::Transform& tr = displayState.transform;
2236 const Rect bounds = displayState.bounds;
2237 if (displayState.isEnabled) {
2238 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002239
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002241 auto compositionLayer = layer->getCompositionLayer();
2242 if (compositionLayer == nullptr) {
2243 return;
2244 }
2245
Lloyd Pique32cbe282018-10-19 13:09:22 -07002246 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002247 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2248 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2249
Lloyd Pique07e33212018-12-18 16:33:37 -08002250 bool needsOutputLayer = false;
2251
Lloyd Piqueef36b002019-01-23 17:52:04 -08002252 if (display->belongsInOutput(layer->getLayerStack(),
2253 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002254 Region drawRegion(tr.transform(
2255 layer->visibleNonTransparentRegion));
2256 drawRegion.andSelf(bounds);
2257 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002258 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002259 }
Chia-I Wu83806892017-11-16 10:50:20 -08002260 }
2261
Lloyd Pique07e33212018-12-18 16:33:37 -08002262 if (needsOutputLayer) {
2263 layersSortedByZ.emplace_back(
2264 display->getOrCreateOutputLayer(displayId, compositionLayer,
2265 layerFE));
2266 deprecated_layersSortedByZ.add(layer);
2267
2268 auto& outputLayerState = layersSortedByZ.back()->editState();
2269 outputLayerState.visibleRegion =
2270 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2271 } else if (displayId) {
2272 // For layers that are being removed from a HWC display,
2273 // and that have queued frames, add them to a a list of
2274 // released layers so we can properly set a fence.
2275 bool hasExistingOutputLayer =
2276 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2277 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2278 mLayersWithQueuedFrames.cend(),
2279 layer) != mLayersWithQueuedFrames.cend();
2280
2281 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002282 layersNeedingFences.add(layer);
2283 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002284 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002285 });
2286 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002287
2288 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2289
2290 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002291 displayDevice->setLayersNeedingFences(layersNeedingFences);
2292
2293 Region undefinedRegion{bounds};
2294 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2295
2296 display->editState().undefinedRegion = undefinedRegion;
2297 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002298 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002299 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002300}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002301
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002302// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002304// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002305// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002306// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307// The returned HDR data space is one of
2308// - Dataspace::UNKNOWN
2309// - Dataspace::BT2020_HLG
2310// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2312 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002313 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 *outHdrDataSpace = Dataspace::UNKNOWN;
2315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002316 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002317 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318 case Dataspace::V0_SCRGB:
2319 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002320 case Dataspace::BT2020:
2321 case Dataspace::BT2020_ITU:
2322 case Dataspace::BT2020_LINEAR:
2323 case Dataspace::DISPLAY_BT2020:
2324 bestDataSpace = Dataspace::DISPLAY_BT2020;
2325 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002326 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002327 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002328 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 case Dataspace::BT2020_PQ:
2330 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002331 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002333 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002334 case Dataspace::BT2020_HLG:
2335 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002336 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002337 // When there's mixed PQ content and HLG content, we set the HDR
2338 // data space to be BT2020_PQ and convert HLG to PQ.
2339 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2340 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002341 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002342 break;
2343 default:
2344 break;
2345 }
Romain Guy54f154a2017-10-24 21:40:32 +01002346 }
2347
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002348 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002349}
2350
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002352void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2353 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002354 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2355 *outMode = ColorMode::NATIVE;
2356 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002358 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002359 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002360
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002361 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002363
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002364 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2365
Peiyong Lina3ea5592019-02-10 14:45:00 -08002366 switch (mForceColorMode) {
2367 case ColorMode::SRGB:
2368 bestDataSpace = Dataspace::V0_SRGB;
2369 break;
2370 case ColorMode::DISPLAY_P3:
2371 bestDataSpace = Dataspace::DISPLAY_P3;
2372 break;
2373 default:
2374 break;
2375 }
2376
Peiyong Lindfde5112018-06-05 10:58:41 -07002377 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002378 const bool isHdr =
2379 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002380 if (isHdr) {
2381 bestDataSpace = hdrDataSpace;
2382 }
2383
Chia-I Wu0d711262018-05-21 15:19:35 -07002384 RenderIntent intent;
2385 switch (mDisplayColorSetting) {
2386 case DisplayColorSetting::MANAGED:
2387 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002388 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002389 break;
2390 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002391 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002392 break;
2393 default: // vendor display color setting
2394 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2395 break;
2396 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002397
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002398 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002399}
2400
Lloyd Pique32cbe282018-10-19 13:09:22 -07002401void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2402 auto display = displayDevice->getCompositionDisplay();
2403 const auto& displayState = display->getState();
2404
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002405 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002406 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2407 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002408
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409 // If nothing has changed (!dirty), don't recompose.
2410 // If something changed, but we don't currently have any visible layers,
2411 // and didn't when we last did a composition, then skip it this time.
2412 // The second rule does two things:
2413 // - When all layers are removed from a display, we'll emit one black
2414 // frame, then nothing more until we get new layers.
2415 // - When a display is created with a private layer stack, we won't
2416 // emit any black frames until a layer is added to the layer stack.
2417 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002418
Dominik Laskowski075d3172018-05-24 15:50:06 -07002419 const char flagPrefix[] = {'-', '+'};
2420 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2422 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2423 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2424 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002425
Lloyd Pique31cb2942018-10-19 17:23:03 -07002426 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002427
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002430 }
2431}
2432
Lloyd Pique32cbe282018-10-19 13:09:22 -07002433void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2434 auto display = displayDevice->getCompositionDisplay();
2435 const auto& displayState = display->getState();
2436
2437 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002438 return;
David Sodman2b406362017-12-15 13:33:47 -08002439 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002440
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002441 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002442 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002443 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002444}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002445
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002447 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 ALOGV("doComposition");
2449
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 auto display = displayDevice->getCompositionDisplay();
2451 const auto& displayState = display->getState();
2452
2453 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002454 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002455 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002456
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002458 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002459
Lloyd Pique32cbe282018-10-19 13:09:22 -07002460 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002461 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002464}
2465
David Sodmanfa9b2af2017-12-24 13:28:59 -08002466void SurfaceFlinger::postFrame()
2467{
2468 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 const auto display = getDefaultDisplayDeviceLocked();
2470 if (display && getHwComposer().isConnected(*display->getId())) {
2471 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002472 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2473 logFrameStats();
2474 }
2475 }
2476}
2477
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002479 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002481
Lloyd Pique32cbe282018-10-19 13:09:22 -07002482 auto display = displayDevice->getCompositionDisplay();
2483 const auto& displayState = display->getState();
2484 const auto displayId = display->getId();
2485
David Sodmanfa9b2af2017-12-24 13:28:59 -08002486 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002487
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (displayId) {
2490 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002491 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002492 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002493 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002494 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002495
Chia-I Wu7b549592017-11-15 09:14:57 -08002496 // The layer buffer from the previous frame (if any) is released
2497 // by HWC only when the release fence from this frame (if any) is
2498 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002499 if (displayId && layer->hasHwcLayer(displayDevice)) {
2500 releaseFence =
2501 getHwComposer().getLayerReleaseFence(*displayId,
2502 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002503 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002504
2505 // If the layer was client composited in the previous frame, we
2506 // need to merge with the previous client target acquire fence.
2507 // Since we do not track that, always merge with the current
2508 // client target acquire fence when it is available, even though
2509 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002510 if (layer->getCompositionType(displayDevice) ==
2511 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002512 releaseFence =
2513 Fence::merge("LayerRelease", releaseFence,
2514 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002515 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002516
David Sodman15094112018-10-11 09:39:37 -07002517 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002518 }
Chia-I Wu83806892017-11-16 10:50:20 -08002519
2520 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002521 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002522 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002523 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002525 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002526 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002527 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002528 }
2529 }
2530
Dominik Laskowski075d3172018-05-24 15:50:06 -07002531 if (displayId) {
2532 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002533 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535}
2536
Mathias Agopian87baae12012-07-31 12:38:26 -07002537void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538{
Mathias Agopian841cde52012-03-01 15:44:37 -08002539 ATRACE_CALL();
2540
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002541 // here we keep a copy of the drawing state (that is the state that's
2542 // going to be overwritten by handleTransactionLocked()) outside of
2543 // mStateLock so that the side-effects of the State assignment
2544 // don't happen with mStateLock held (which can cause deadlocks).
2545 State drawingState(mDrawingState);
2546
Mathias Agopianca4d3602011-05-19 15:38:14 -07002547 Mutex::Autolock _l(mStateLock);
2548 const nsecs_t now = systemTime();
2549 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002550
Mathias Agopianca4d3602011-05-19 15:38:14 -07002551 // Here we're guaranteed that some transaction flags are set
2552 // so we can call handleTransactionLocked() unconditionally.
2553 // We call getTransactionFlags(), which will also clear the flags,
2554 // with mStateLock held to guarantee that mCurrentState won't change
2555 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002556
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002557 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002558 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002559 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002560
Mathias Agopianca4d3602011-05-19 15:38:14 -07002561 mLastTransactionTime = systemTime() - now;
2562 mDebugInTransaction = 0;
2563 invalidateHwcGeometry();
2564 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002565}
2566
Lloyd Piqueba04e622017-12-14 17:11:26 -08002567void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2568 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 const std::optional<DisplayIdentificationInfo> info =
2570 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002571
Dominik Laskowski075d3172018-05-24 15:50:06 -07002572 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002573 continue;
2574 }
2575
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002578 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 mPhysicalDisplayTokens[info->id] = new BBinder();
2580 DisplayDeviceState state;
2581 state.displayId = info->id;
2582 state.isSecure = true; // All physical displays are currently considered secure.
2583 state.displayName = info->name;
2584 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2585 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002586 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002588 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002589
Dominik Laskowski075d3172018-05-24 15:50:06 -07002590 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2591 if (index >= 0) {
2592 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2593 mInterceptor->saveDisplayDeletion(state.sequenceId);
2594 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002595 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002597 }
2598
2599 processDisplayChangesLocked();
2600 }
2601
2602 mPendingHotplugEvents.clear();
2603}
2604
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002605void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002606 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2607 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002608}
2609
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002612 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 const sp<IGraphicBufferProducer>& producer) {
2614 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002615 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002616 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002617 creationArgs.isSecure = state.isSecure;
2618 creationArgs.displaySurface = dispSurface;
2619 creationArgs.hasWideColorGamut = false;
2620 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002621
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002622 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 creationArgs.isPrimary = isInternalDisplay;
2624
2625 if (useColorManagement && displayId) {
2626 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002628 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002629 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002631
Dominik Laskowski7e045462018-05-30 13:02:02 -07002632 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002634 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635 }
tangrobin6753a022018-08-10 10:58:54 +08002636 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 if (displayId) {
2639 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002640 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002641 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002642 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002643
Lloyd Pique90c115d2018-09-18 21:39:42 -07002644 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002645 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002646 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647
Lloyd Pique99d3da52018-01-22 17:48:03 -08002648 // Make sure that composition can never be stalled by a virtual display
2649 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002650 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002651 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2653 }
2654
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 creationArgs.displayInstallOrientation =
2656 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002657
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002659 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660
Lloyd Pique90c115d2018-09-18 21:39:42 -07002661 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662
2663 if (maxFrameBufferAcquiredBuffers >= 3) {
2664 nativeWindowSurface->preallocateBuffers();
2665 }
2666
2667 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002668 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002669 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002670 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002671 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002673 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2674 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002675 if (!state.isVirtual()) {
2676 LOG_ALWAYS_FATAL_IF(!displayId);
2677 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002678 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002679
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002680 display->setLayerStack(state.layerStack);
2681 display->setProjection(state.orientation, state.viewport, state.frame);
2682 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002683
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002685}
2686
Lloyd Pique347200f2017-12-14 17:00:15 -08002687void SurfaceFlinger::processDisplayChangesLocked() {
2688 // here we take advantage of Vector's copy-on-write semantics to
2689 // improve performance by skipping the transaction entirely when
2690 // know that the lists are identical
2691 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2692 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2693 if (!curr.isIdenticalTo(draw)) {
2694 mVisibleRegionsDirty = true;
2695 const size_t cc = curr.size();
2696 size_t dc = draw.size();
2697
2698 // find the displays that were removed
2699 // (ie: in drawing state but not in current state)
2700 // also handle displays that changed
2701 // (ie: displays that are in both lists)
2702 for (size_t i = 0; i < dc;) {
2703 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2704 if (j < 0) {
2705 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002707 // Save display ID before disconnecting.
2708 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002709 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002710
2711 if (!display->isVirtual()) {
2712 LOG_ALWAYS_FATAL_IF(!displayId);
2713 dispatchDisplayHotplugEvent(displayId->value, false);
2714 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002716
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002717 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 } else {
2719 // this display is in both lists. see if something changed.
2720 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2723 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2724 if (state_binder != draw_binder) {
2725 // changing the surface is like destroying and
2726 // recreating the DisplayDevice, so we just remove it
2727 // from the drawing state, so that it get re-added
2728 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002730 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002732 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002733 mDrawingState.displays.removeItemsAt(i);
2734 dc--;
2735 // at this point we must loop to the next item
2736 continue;
2737 }
2738
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002741 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 }
2743 if ((state.orientation != draw[i].orientation) ||
2744 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002745 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 }
2747 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002748 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002749 }
2750 }
2751 }
2752 ++i;
2753 }
2754
2755 // find displays that were added
2756 // (ie: in current state but not in drawing state)
2757 for (size_t i = 0; i < cc; i++) {
2758 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2759 const DisplayDeviceState& state(curr[i]);
2760
Lloyd Pique542307f2018-10-19 13:24:08 -07002761 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002762 sp<IGraphicBufferProducer> producer;
2763 sp<IGraphicBufferProducer> bqProducer;
2764 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002765 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002766
Dominik Laskowski075d3172018-05-24 15:50:06 -07002767 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002768 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002769 // Virtual displays without a surface are dormant:
2770 // they have external state (layer stack, projection,
2771 // etc.) but no internal state (i.e. a DisplayDevice).
2772 if (state.surface != nullptr) {
2773 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002774 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 int width = 0;
2776 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2777 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2778 int height = 0;
2779 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2780 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2781 int intFormat = 0;
2782 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2783 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002784 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002785
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 displayId =
2787 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 }
2789
2790 // TODO: Plumb requested format back up to consumer
2791
2792 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002793 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 bqProducer, bqConsumer,
2795 state.displayName);
2796
2797 dispSurface = vds;
2798 producer = vds;
2799 }
2800 } else {
2801 ALOGE_IF(state.surface != nullptr,
2802 "adding a supported display, but rendering "
2803 "surface is provided (%p), ignoring it",
2804 state.surface.get());
2805
Dominik Laskowski075d3172018-05-24 15:50:06 -07002806 displayId = state.displayId;
2807 LOG_ALWAYS_FATAL_IF(!displayId);
2808 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002809 producer = bqProducer;
2810 }
2811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002812 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002813 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002814 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002815 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002816 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002817 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002818 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002819 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002820 }
2821 }
2822 }
2823 }
2824 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002825
2826 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002827}
2828
Mathias Agopian87baae12012-07-31 12:38:26 -07002829void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002830{
Dan Stoza7dde5992015-05-22 09:51:44 -07002831 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mCurrentState.traverseInZOrder([](Layer* layer) {
2833 layer->notifyAvailableFrames();
2834 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002835
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002836 /*
2837 * Traversal of the children
2838 * (perform the transaction for each of them if needed)
2839 */
2840
Mathias Agopian3559b072012-08-15 13:46:03 -07002841 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002842 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002844 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845
2846 const uint32_t flags = layer->doTransaction(0);
2847 if (flags & Layer::eVisibleRegion)
2848 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002849
2850 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002851 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002852 }
Robert Carr2047fae2016-11-28 14:09:09 -08002853 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 }
2855
2856 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002857 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 */
2859
Mathias Agopiane57f2922012-08-09 16:29:12 -07002860 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002861 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002862 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002863 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002865 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002866 // The transform hint might have changed for some layers
2867 // (either because a display has changed, or because a layer
2868 // as changed).
2869 //
2870 // Walk through all the layers in currentLayers,
2871 // and update their transform hint.
2872 //
2873 // If a layer is visible only on a single display, then that
2874 // display is used to calculate the hint, otherwise we use the
2875 // default display.
2876 //
2877 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2878 // the hint is set before we acquire a buffer from the surface texture.
2879 //
2880 // NOTE: layer transactions have taken place already, so we use their
2881 // drawing state. However, SurfaceFlinger's own transaction has not
2882 // happened yet, so we must use the current state layer list
2883 // (soon to become the drawing state list).
2884 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002885 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002886 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002887 bool first = true;
2888 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002889 // NOTE: we rely on the fact that layers are sorted by
2890 // layerStack first (so we don't have to traverse the list
2891 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002893 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002894 currentlayerStack = layerStack;
2895 // figure out if this layerstack is mirrored
2896 // (more than one display) if so, pick the default display,
2897 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002898 hintDisplay = nullptr;
2899 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002900 if (display->getCompositionDisplay()
2901 ->belongsInOutput(layer->getLayerStack(),
2902 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 if (hintDisplay) {
2904 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002905 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002906 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002907 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002908 }
2909 }
2910 }
2911 }
Chet Haase91d25932013-04-11 15:24:55 -07002912
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002913 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002914 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2915 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002916
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002917 // could be null when this layer is using a layerStack
2918 // that is not visible on any display. Also can occur at
2919 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002920 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002921 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002922
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002923 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002924 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 if (hintDisplay) {
2926 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002927 }
Robert Carr2047fae2016-11-28 14:09:09 -08002928
2929 first = false;
2930 });
Mathias Agopian84300952012-11-21 16:02:13 -08002931 }
2932
2933
Mathias Agopian3559b072012-08-15 13:46:03 -07002934 /*
2935 * Perform our own transaction if needed
2936 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002937
2938 if (mLayersAdded) {
2939 mLayersAdded = false;
2940 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002941 mVisibleRegionsDirty = true;
2942 }
2943
2944 // some layers might have been removed, so
2945 // we need to update the regions they're exposing.
2946 if (mLayersRemoved) {
2947 mLayersRemoved = false;
2948 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002949 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002950 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002951 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002952 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002953 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002954 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002955 }
Robert Carr2047fae2016-11-28 14:09:09 -08002956 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 }
2958
Vishnu Nairec0ab382019-02-13 15:32:56 -08002959 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002961}
2962
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002963void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002964 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002965 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002966 return;
2967 }
2968
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002969 if (mVisibleRegionsDirty || mInputInfoChanged) {
2970 mInputInfoChanged = false;
2971 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002972 } else if (mInputWindowCommands.syncInputWindows) {
2973 // If the caller requested to sync input windows, but there are no
2974 // changes to input windows, notify immediately.
2975 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002976 }
2977
2978 executeInputWindowCommands();
2979}
2980
2981void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07002982 Vector<InputWindowInfo> inputHandles;
2983
2984 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2985 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002986 // When calculating the screen bounds we ignore the transparent region since it may
2987 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08002988 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002989 }
2990 });
chaviw291d88a2019-02-14 10:33:58 -08002991
2992 mInputFlinger->setInputWindows(inputHandles,
2993 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2994 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002995}
2996
Vishnu Nairec0ab382019-02-13 15:32:56 -08002997void SurfaceFlinger::commitInputWindowCommands() {
2998 mInputWindowCommands.merge(mPendingInputWindowCommands);
2999 mPendingInputWindowCommands.clear();
3000}
3001
chaviwfbe5d9c2018-12-26 12:23:37 -08003002void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003003 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3004 if (transferTouchFocusCommand.fromToken != nullptr &&
3005 transferTouchFocusCommand.toToken != nullptr &&
3006 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3007 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3008 transferTouchFocusCommand.toToken);
3009 }
3010 }
3011
3012 mInputWindowCommands.clear();
3013}
3014
Riley Andrews03414a12014-07-01 14:22:59 -07003015void SurfaceFlinger::updateCursorAsync()
3016{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003017 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003018 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003019 continue;
3020 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3023 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003024 }
3025 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003026}
3027
chaviw61626f22018-11-15 16:26:27 -08003028void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3029 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003030 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003031 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003032 }
3033 layer->releasePendingBuffer(systemTime());
3034}
3035
Mathias Agopian4fec8732012-06-29 14:12:52 -07003036void SurfaceFlinger::commitTransaction()
3037{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003038 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003039 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003040 for (const auto& l : mLayersPendingRemoval) {
3041 recordBufferingStats(l->getName().string(),
3042 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003043
Lloyd Pique07e33212018-12-18 16:33:37 -08003044 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003045 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003046 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003047 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003048 }
3049 mLayersPendingRemoval.clear();
3050 }
3051
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003052 // If this transaction is part of a window animation then the next frame
3053 // we composite should be considered an animation as well.
3054 mAnimCompositionPending = mAnimTransactionPending;
3055
Mathias Agopian4fec8732012-06-29 14:12:52 -07003056 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003057 // clear the "changed" flags in current state
3058 mCurrentState.colorMatrixChanged = false;
3059
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060 mDrawingState.traverseInZOrder([](Layer* layer) {
3061 layer->commitChildList();
3062 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003063 mTransactionPending = false;
3064 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066}
3067
Lloyd Pique32cbe282018-10-19 13:09:22 -07003068void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003069 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003070 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003071 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003072
Lloyd Pique32cbe282018-10-19 13:09:22 -07003073 auto display = displayDevice->getCompositionDisplay();
3074
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 Region aboveOpaqueLayers;
3076 Region aboveCoveredLayers;
3077 Region dirty;
3078
Mathias Agopian87baae12012-07-31 12:38:26 -07003079 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080
Robert Carr2047fae2016-11-28 14:09:09 -08003081 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003082 // start with the whole surface at its current location
3083 const Layer::State& s(layer->getDrawingState());
3084
Jesse Hall01e29052013-02-19 16:13:35 -08003085 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003086 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003087 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003088 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003089
Mathias Agopianab028732010-03-16 16:41:46 -07003090 /*
3091 * opaqueRegion: area of a surface that is fully opaque.
3092 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003094
3095 /*
3096 * visibleRegion: area of a surface that is visible on screen
3097 * and not fully transparent. This is essentially the layer's
3098 * footprint minus the opaque regions above it.
3099 * Areas covered by a translucent surface are considered visible.
3100 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003102
3103 /*
3104 * coveredRegion: area of a surface that is covered by all
3105 * visible regions above it (which includes the translucent areas).
3106 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003107 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003108
Jesse Halla8026d22012-09-25 13:25:04 -07003109 /*
3110 * transparentRegion: area of a surface that is hinted to be completely
3111 * transparent. This is only used to tell when the layer has no visible
3112 * non-transparent regions and can be removed from the layer list. It
3113 * does not affect the visibleRegion of this layer or any layers
3114 * beneath it. The hint may not be correct if apps don't respect the
3115 * SurfaceView restrictions (which, sadly, some don't).
3116 */
3117 Region transparentRegion;
3118
Mathias Agopianab028732010-03-16 16:41:46 -07003119
3120 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003121 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003122 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003123 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003126 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003127 if (!visibleRegion.isEmpty()) {
3128 // Remove the transparent area from the visible region
3129 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003130 if (tr.preserveRects()) {
3131 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003132 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003133 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003134 // transformation too complex, can't do the
3135 // transparent region optimization.
3136 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003137 }
Mathias Agopianab028732010-03-16 16:41:46 -07003138 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139
Mathias Agopianab028732010-03-16 16:41:46 -07003140 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003141 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003142 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003143 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003144 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003145 // the opaque region is the layer's footprint
3146 opaqueRegion = visibleRegion;
3147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 }
3149 }
3150
Robert Carre5f4f692018-01-12 13:12:28 -08003151 if (visibleRegion.isEmpty()) {
3152 layer->clearVisibilityRegions();
3153 return;
3154 }
3155
Mathias Agopianab028732010-03-16 16:41:46 -07003156 // Clip the covered region to the visible region
3157 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3158
3159 // Update aboveCoveredLayers for next (lower) layer
3160 aboveCoveredLayers.orSelf(visibleRegion);
3161
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 // subtract the opaque region covered by the layers above us
3163 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164
3165 // compute this layer's dirty region
3166 if (layer->contentDirty) {
3167 // we need to invalidate the whole region
3168 dirty = visibleRegion;
3169 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003170 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 layer->contentDirty = false;
3172 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003173 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003174 * the exposed region consists of two components:
3175 * 1) what's VISIBLE now and was COVERED before
3176 * 2) what's EXPOSED now less what was EXPOSED before
3177 *
3178 * note that (1) is conservative, we start with the whole
3179 * visible region but only keep what used to be covered by
3180 * something -- which mean it may have been exposed.
3181 *
3182 * (2) handles areas that were not covered by anything but got
3183 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003184 */
Mathias Agopianab028732010-03-16 16:41:46 -07003185 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003186 const Region oldVisibleRegion = layer->visibleRegion;
3187 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003188 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3189 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190 }
3191 dirty.subtractSelf(aboveOpaqueLayers);
3192
3193 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003194 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195
Mathias Agopianab028732010-03-16 16:41:46 -07003196 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003198
Jesse Halla8026d22012-09-25 13:25:04 -07003199 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 layer->setVisibleRegion(visibleRegion);
3201 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003202 layer->setVisibleNonTransparentRegion(
3203 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003204 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003205
Mathias Agopian87baae12012-07-31 12:38:26 -07003206 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Chia-I Wuab0c3192017-08-01 11:29:00 -07003209void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003210 for (const auto& [token, displayDevice] : mDisplays) {
3211 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003212 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003213 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003214 }
3215 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003216}
3217
Daniel Solomon42d04562019-01-20 21:03:19 -08003218void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3219 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3220 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3221 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3222 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3223 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3224 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3225 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3226 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3227 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3228 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3229 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3230 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3231}
3232
Dan Stoza6b9454d2014-11-07 16:00:59 -08003233bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003235 ALOGV("handlePageFlip");
3236
Brian Andersond6927fb2016-07-23 23:37:30 -07003237 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238
Mathias Agopian4fec8732012-06-29 14:12:52 -07003239 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003240 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003241 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003242
3243 // Store the set of layers that need updates. This set must not change as
3244 // buffers are being latched, as this could result in a deadlock.
3245 // Example: Two producers share the same command stream and:
3246 // 1.) Layer 0 is latched
3247 // 2.) Layer 0 gets a new frame
3248 // 2.) Layer 1 gets a new frame
3249 // 3.) Layer 1 is latched.
3250 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3251 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003252 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003253 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003254 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003255 nsecs_t expectedPresentTime;
Ana Krulecc2870422019-01-29 19:00:58 -08003256 expectedPresentTime = mScheduler->expectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003257 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003258 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003259 } else {
3260 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003261 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003262 } else {
3263 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003264 }
Robert Carr2047fae2016-11-28 14:09:09 -08003265 });
3266
Lloyd Piquef2c79392018-12-20 16:23:33 -08003267 if (!mLayersWithQueuedFrames.empty()) {
3268 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3269 // writes to Layer current state. See also b/119481871
3270 Mutex::Autolock lock(mStateLock);
3271
3272 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003273 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003274 mLayersPendingRefresh.push_back(layer);
3275 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003276 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003277 if (layer->isBufferLatched()) {
3278 newDataLatched = true;
3279 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003280 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003281 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003282
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003283 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003284
3285 // If we will need to wake up at some time in the future to deal with a
3286 // queued frame that shouldn't be displayed during this vsync period, wake
3287 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003288 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003289 signalLayerUpdate();
3290 }
3291
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003292 // enter boot animation on first buffer latch
3293 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3294 ALOGI("Enter boot animation");
3295 mBootStage = BootStage::BOOTANIMATION;
3296 }
3297
Dan Stoza6b9454d2014-11-07 16:00:59 -08003298 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003299 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300}
3301
Mathias Agopianad456f92011-01-13 17:53:01 -08003302void SurfaceFlinger::invalidateHwcGeometry()
3303{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003305}
3306
Lloyd Pique32cbe282018-10-19 13:09:22 -07003307void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003308 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003309 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003310 // We only need to actually compose the display if:
3311 // 1) It is being handled by hardware composer, which may need this to
3312 // keep its virtual display state machine in sync, or
3313 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003314 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003315 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003316 return;
3317 }
3318
Dan Stoza9e56aa02015-11-02 13:00:03 -08003319 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003320 base::unique_fd readyFence;
3321 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003322
3323 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003324 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003325}
3326
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003327bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3328 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003329 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003330 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003331
Lloyd Pique32cbe282018-10-19 13:09:22 -07003332 auto display = displayDevice->getCompositionDisplay();
3333 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003334 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003335
3336 const Region bounds(displayState.bounds);
3337 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003338 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003339 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003340
Peiyong Lind3788632018-09-18 16:01:31 -07003341 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003342 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003343
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003344 renderengine::DisplaySettings clientCompositionDisplay;
3345 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3346 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003347 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003348
Dan Stoza9e56aa02015-11-02 13:00:03 -08003349 if (hasClientComposition) {
3350 ALOGV("hasClientComposition");
3351
Alec Mouri6338c9d2019-02-07 16:57:51 -08003352 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003353 if (buf == nullptr) {
3354 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3355 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003356 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003357 return false;
3358 }
3359
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003360 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3361 clientCompositionDisplay.clip = displayState.scissor;
3362 const ui::Transform& displayTransform = displayState.transform;
3363 mat4 m;
3364 m[0][0] = displayTransform[0][0];
3365 m[0][1] = displayTransform[0][1];
3366 m[0][3] = displayTransform[0][2];
3367 m[1][0] = displayTransform[1][0];
3368 m[1][1] = displayTransform[1][1];
3369 m[1][3] = displayTransform[1][2];
3370 m[3][0] = displayTransform[2][0];
3371 m[3][1] = displayTransform[2][1];
3372 m[3][3] = displayTransform[2][2];
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003373 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003374
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003375 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003376 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003377 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003378 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003379 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003380 clientCompositionDisplay.outputDataspace = outputDataspace;
3381 clientCompositionDisplay.maxLuminance =
3382 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003383
Lloyd Pique441d5042018-10-18 16:49:51 -07003384 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003385 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003386 getHwComposer()
3387 .hasDisplayCapability(displayId,
3388 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003389
Peiyong Lind3788632018-09-18 16:01:31 -07003390 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003391 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3392 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003393 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003394 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003395 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003396
Mathias Agopian85d751c2012-08-29 16:59:24 -07003397 /*
3398 * and then, render the layers targeted at the framebuffer
3399 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003400
Dan Stoza9e56aa02015-11-02 13:00:03 -08003401 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003402 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003403 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003404 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003405 const Region viewportRegion(displayState.viewport);
3406 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003407 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003408 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003409 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003410 switch (layer->getCompositionType(displayDevice)) {
3411 case Hwc2::IComposerClient::Composition::CURSOR:
3412 case Hwc2::IComposerClient::Composition::DEVICE:
3413 case Hwc2::IComposerClient::Composition::SIDEBAND:
3414 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003415 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003416 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003417 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003418 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003419 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003420 // never clear the very first layer since we're
3421 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003422 renderengine::LayerSettings layerSettings;
3423 Region dummyRegion;
3424 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3425 layerSettings);
3426
3427 if (prepared) {
3428 layerSettings.source.buffer.buffer = nullptr;
3429 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3430 layerSettings.alpha = half(0.0);
3431 layerSettings.disableBlending = true;
3432 clientCompositionLayers.push_back(layerSettings);
3433 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003434 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003435 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003436 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003437 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003438 renderengine::LayerSettings layerSettings;
3439 bool prepared =
3440 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3441 if (prepared) {
3442 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003443 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003444 break;
3445 }
3446 default:
3447 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003448 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 } else {
3450 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003451 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003452 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003453 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003454
Alec Mouri820c7402019-01-23 13:02:39 -08003455 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003456 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003457 clientCompositionDisplay.clearRegion = clearRegion;
3458 if (!debugRegion.isEmpty()) {
3459 Region::const_iterator it = debugRegion.begin();
3460 Region::const_iterator end = debugRegion.end();
3461 while (it != end) {
3462 const Rect& rect = *it++;
3463 renderengine::LayerSettings layerSettings;
3464 layerSettings.source.buffer.buffer = nullptr;
3465 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3466 layerSettings.geometry.boundaries = rect.toFloatRect();
3467 layerSettings.alpha = half(1.0);
3468 clientCompositionLayers.push_back(layerSettings);
3469 }
3470 }
3471 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mouri6338c9d2019-02-07 16:57:51 -08003472 buf->getNativeBuffer(), std::move(fd), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003473 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003474 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475}
3476
Chia-I Wu28e3a252018-09-07 12:05:02 -07003477void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003478 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003479 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003480}
3481
Dan Stoza7d89d062015-04-30 13:29:25 -07003482status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003483 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003484 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003485 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003486 const sp<Layer>& parent,
3487 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003488{
Dan Stoza7d89d062015-04-30 13:29:25 -07003489 // add this layer to the current state list
3490 {
3491 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003492 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003493 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3494 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003495 return NO_MEMORY;
3496 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003497 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003498 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003499 } else if (parent == nullptr) {
3500 lbc->onRemovedFromCurrentState();
3501 } else if (parent->isRemovedFromCurrentState()) {
3502 parent->addChild(lbc);
3503 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003504 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003505 parent->addChild(lbc);
3506 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003507
Yiwei Zhang243b3782018-05-15 17:40:04 -07003508 if (gbc != nullptr) {
3509 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3510 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3511 mMaxGraphicBufferProducerListSize,
3512 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3513 mGraphicBufferProducerList.size(),
3514 mMaxGraphicBufferProducerListSize, mNumLayers);
3515 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003516 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003517 }
3518
Mathias Agopian96f08192010-06-02 23:28:45 -07003519 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003520 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003521
Dan Stoza7d89d062015-04-30 13:29:25 -07003522 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003523}
3524
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003525uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003526 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003527}
3528
Mathias Agopian3f844832013-08-07 21:24:32 -07003529uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003530 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531}
3532
Mathias Agopian3f844832013-08-07 21:24:32 -07003533uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003534 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003535}
3536
3537uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003538 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003539 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003540 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003542 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 }
3544 return old;
3545}
3546
Marissa Wall713b63f2018-10-17 15:42:43 -07003547bool SurfaceFlinger::flushTransactionQueues() {
3548 Mutex::Autolock _l(mStateLock);
3549 auto it = mTransactionQueues.begin();
3550 while (it != mTransactionQueues.end()) {
3551 auto& [applyToken, transactionQueue] = *it;
3552
3553 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003554 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3555 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003556 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003557 break;
3558 }
Robert Carr14167e02019-02-13 13:50:55 -08003559 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003560 transactionQueue.pop();
3561 }
3562
3563 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3564 }
3565 return mTransactionQueues.empty();
3566}
3567
chaviwca27f252018-02-06 16:46:39 -08003568bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3569 for (const ComposerState& state : states) {
3570 // Here we need to check that the interface we're given is indeed
3571 // one of our own. A malicious client could give us a nullptr
3572 // IInterface, or one of its own or even one of our own but a
3573 // different type. All these situations would cause us to crash.
3574 if (state.client == nullptr) {
3575 return true;
3576 }
3577
3578 sp<IBinder> binder = IInterface::asBinder(state.client);
3579 if (binder == nullptr) {
3580 return true;
3581 }
3582
3583 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3584 return true;
3585 }
3586 }
3587 return false;
3588}
3589
Marissa Wall17b4e452018-12-26 16:32:34 -08003590bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3591 const Vector<ComposerState>& states) {
Ana Krulecc2870422019-01-29 19:00:58 -08003592 nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003593 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3594 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3595 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3596 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3597 return false;
3598 }
3599
Marissa Wall713b63f2018-10-17 15:42:43 -07003600 for (const ComposerState& state : states) {
3601 const layer_state_t& s = state.state;
3602 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3603 continue;
3604 }
3605 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003606 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003607 }
3608 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003609 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003610}
3611
3612void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3613 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003614 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003615 const InputWindowCommands& inputWindowCommands,
3616 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003617 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003618
3619 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3620
Mathias Agopian698c0872011-06-28 19:09:31 -07003621 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003622
chaviwca27f252018-02-06 16:46:39 -08003623 if (containsAnyInvalidClientState(states)) {
3624 return;
3625 }
3626
Marissa Wall713b63f2018-10-17 15:42:43 -07003627 // If its TransactionQueue already has a pending TransactionState or if it is pending
3628 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003629 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003630 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3631 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003632 setTransactionFlags(eTransactionNeeded);
3633 return;
3634 }
3635
Robert Carr14167e02019-02-13 13:50:55 -08003636 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003637}
3638
3639void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003640 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003641 const InputWindowCommands& inputWindowCommands,
3642 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003643 uint32_t transactionFlags = 0;
3644
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003645 if (flags & eAnimation) {
3646 // For window updates that are part of an animation we must wait for
3647 // previous animation "frames" to be handled.
3648 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003649 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003650 if (CC_UNLIKELY(err != NO_ERROR)) {
3651 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003652 // caller after a few seconds.
3653 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3654 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003655 mAnimTransactionPending = false;
3656 break;
3657 }
3658 }
3659 }
3660
chaviwca27f252018-02-06 16:46:39 -08003661 for (const DisplayState& display : displays) {
3662 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003663 }
3664
Marissa Walle2ffb422018-10-12 11:33:52 -07003665 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003666 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003667 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003668 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003669 // If the state doesn't require a traversal and there are callbacks, send them now
3670 if (!(clientStateFlags & eTraversalNeeded)) {
3671 mTransactionCompletedThread.sendCallbacks();
3672 }
3673 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003674
chaviw273171b2018-12-26 11:46:30 -08003675 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3676
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003677 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3678 // anyway. This can be used as a flush mechanism for previous async transactions.
3679 // Empty animation transaction can be used to simulate back-pressure, so also force a
3680 // transaction for empty animation transactions.
3681 if (transactionFlags == 0 &&
3682 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003683 transactionFlags = eTransactionNeeded;
3684 }
3685
Mathias Agopian386aa982011-11-07 21:58:03 -08003686 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003687 if (mInterceptor->isEnabled()) {
3688 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003689 }
Irvel468051e2016-06-13 16:44:44 -07003690
Mathias Agopian386aa982011-11-07 21:58:03 -08003691 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003692 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3693 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003694 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003695
3696 // if this is a synchronous transaction, wait for it to take effect
3697 // before returning.
3698 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003699 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003700 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003701 if (flags & eAnimation) {
3702 mAnimTransactionPending = true;
3703 }
chaviw95ef3c42019-02-14 10:55:09 -08003704
3705 mPendingSyncInputWindows = mPendingInputWindowCommands.syncInputWindows;
3706 while (mTransactionPending || mPendingSyncInputWindows) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003707 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3708 if (CC_UNLIKELY(err != NO_ERROR)) {
3709 // just in case something goes wrong in SF, return to the
3710 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003711 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3712 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003713 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003714 break;
3715 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 }
3718}
3719
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003720uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3721 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3722 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003723
Mathias Agopiane57f2922012-08-09 16:29:12 -07003724 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003725 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3726
3727 const uint32_t what = s.what;
3728 if (what & DisplayState::eSurfaceChanged) {
3729 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3730 state.surface = s.surface;
3731 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003732 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003733 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003734 if (what & DisplayState::eLayerStackChanged) {
3735 if (state.layerStack != s.layerStack) {
3736 state.layerStack = s.layerStack;
3737 flags |= eDisplayTransactionNeeded;
3738 }
3739 }
3740 if (what & DisplayState::eDisplayProjectionChanged) {
3741 if (state.orientation != s.orientation) {
3742 state.orientation = s.orientation;
3743 flags |= eDisplayTransactionNeeded;
3744 }
3745 if (state.frame != s.frame) {
3746 state.frame = s.frame;
3747 flags |= eDisplayTransactionNeeded;
3748 }
3749 if (state.viewport != s.viewport) {
3750 state.viewport = s.viewport;
3751 flags |= eDisplayTransactionNeeded;
3752 }
3753 }
3754 if (what & DisplayState::eDisplaySizeChanged) {
3755 if (state.width != s.width) {
3756 state.width = s.width;
3757 flags |= eDisplayTransactionNeeded;
3758 }
3759 if (state.height != s.height) {
3760 state.height = s.height;
3761 flags |= eDisplayTransactionNeeded;
3762 }
3763 }
3764
Mathias Agopiane57f2922012-08-09 16:29:12 -07003765 return flags;
3766}
3767
Robert Carr14167e02019-02-13 13:50:55 -08003768bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003769 IPCThreadState* ipc = IPCThreadState::self();
3770 const int pid = ipc->getCallingPid();
3771 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003772 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003773 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003774 return false;
3775 }
3776 return true;
3777}
3778
Robert Carr14167e02019-02-13 13:50:55 -08003779uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3780 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003781 const layer_state_t& s = composerState.state;
3782 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3783
Mathias Agopian13127d82013-03-05 17:47:11 -08003784 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003785 if (layer == nullptr) {
3786 return 0;
3787 }
3788
chaviw8b3871a2017-11-01 17:41:01 -07003789 uint32_t flags = 0;
3790
Garfield Tan8a3083e2018-12-03 13:21:07 -08003791 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003792 bool geometryAppliesWithResize =
3793 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003794
3795 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3796 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003797 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003798 layer->pushPendingState();
3799 }
3800
chaviw8b3871a2017-11-01 17:41:01 -07003801 if (what & layer_state_t::ePositionChanged) {
3802 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3803 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003804 }
chaviw8b3871a2017-11-01 17:41:01 -07003805 }
3806 if (what & layer_state_t::eLayerChanged) {
3807 // NOTE: index needs to be calculated before we update the state
3808 const auto& p = layer->getParent();
3809 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003810 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003811 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003812 mCurrentState.layersSortedByZ.removeAt(idx);
3813 mCurrentState.layersSortedByZ.add(layer);
3814 // we need traversal (state changed)
3815 // AND transaction (list changed)
3816 flags |= eTransactionNeeded|eTraversalNeeded;
3817 }
chaviw8b3871a2017-11-01 17:41:01 -07003818 } else {
3819 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003820 flags |= eTransactionNeeded|eTraversalNeeded;
3821 }
3822 }
chaviw8b3871a2017-11-01 17:41:01 -07003823 }
3824 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003825 // NOTE: index needs to be calculated before we update the state
3826 const auto& p = layer->getParent();
3827 if (p == nullptr) {
3828 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3829 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3830 mCurrentState.layersSortedByZ.removeAt(idx);
3831 mCurrentState.layersSortedByZ.add(layer);
3832 // we need traversal (state changed)
3833 // AND transaction (list changed)
3834 flags |= eTransactionNeeded|eTraversalNeeded;
3835 }
3836 } else {
3837 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3838 flags |= eTransactionNeeded|eTraversalNeeded;
3839 }
chaviw8b3871a2017-11-01 17:41:01 -07003840 }
3841 }
3842 if (what & layer_state_t::eSizeChanged) {
3843 if (layer->setSize(s.w, s.h)) {
3844 flags |= eTraversalNeeded;
3845 }
3846 }
3847 if (what & layer_state_t::eAlphaChanged) {
3848 if (layer->setAlpha(s.alpha))
3849 flags |= eTraversalNeeded;
3850 }
3851 if (what & layer_state_t::eColorChanged) {
3852 if (layer->setColor(s.color))
3853 flags |= eTraversalNeeded;
3854 }
Peiyong Lind3788632018-09-18 16:01:31 -07003855 if (what & layer_state_t::eColorTransformChanged) {
3856 if (layer->setColorTransform(s.colorTransform)) {
3857 flags |= eTraversalNeeded;
3858 }
3859 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003860 if (what & layer_state_t::eBackgroundColorChanged) {
3861 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3862 flags |= eTraversalNeeded;
3863 }
3864 }
chaviw8b3871a2017-11-01 17:41:01 -07003865 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003866 // TODO: b/109894387
3867 //
3868 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3869 // rotation. To see the problem observe that if we have a square parent, and a child
3870 // of the same size, then we rotate the child 45 degrees around it's center, the child
3871 // must now be cropped to a non rectangular 8 sided region.
3872 //
3873 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3874 // private API, and the WindowManager only uses rotation in one case, which is on a top
3875 // level layer in which cropping is not an issue.
3876 //
3877 // However given that abuse of rotation matrices could lead to surfaces extending outside
3878 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3879 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3880 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003881 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003882 flags |= eTraversalNeeded;
3883 }
3884 if (what & layer_state_t::eTransparentRegionChanged) {
3885 if (layer->setTransparentRegionHint(s.transparentRegion))
3886 flags |= eTraversalNeeded;
3887 }
3888 if (what & layer_state_t::eFlagsChanged) {
3889 if (layer->setFlags(s.flags, s.mask))
3890 flags |= eTraversalNeeded;
3891 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003892 if (what & layer_state_t::eCropChanged_legacy) {
3893 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003894 flags |= eTraversalNeeded;
3895 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003896 if (what & layer_state_t::eCornerRadiusChanged) {
3897 if (layer->setCornerRadius(s.cornerRadius))
3898 flags |= eTraversalNeeded;
3899 }
chaviw8b3871a2017-11-01 17:41:01 -07003900 if (what & layer_state_t::eLayerStackChanged) {
3901 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3902 // We only allow setting layer stacks for top level layers,
3903 // everything else inherits layer stack from its parent.
3904 if (layer->hasParent()) {
3905 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3906 layer->getName().string());
3907 } else if (idx < 0) {
3908 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3909 "that also does not appear in the top level layer list. Something"
3910 " has gone wrong.", layer->getName().string());
3911 } else if (layer->setLayerStack(s.layerStack)) {
3912 mCurrentState.layersSortedByZ.removeAt(idx);
3913 mCurrentState.layersSortedByZ.add(layer);
3914 // we need traversal (state changed)
3915 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003916 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003917 }
3918 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003919 if (what & layer_state_t::eDeferTransaction_legacy) {
3920 if (s.barrierHandle_legacy != nullptr) {
3921 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3922 } else if (s.barrierGbp_legacy != nullptr) {
3923 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003924 if (authenticateSurfaceTextureLocked(gbp)) {
3925 const auto& otherLayer =
3926 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003927 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003928 } else {
3929 ALOGE("Attempt to defer transaction to to an"
3930 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003931 }
3932 }
chaviw8b3871a2017-11-01 17:41:01 -07003933 // We don't trigger a traversal here because if no other state is
3934 // changed, we don't want this to cause any more work
3935 }
3936 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003937 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003938 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003939 if (!hadParent) {
3940 mCurrentState.layersSortedByZ.remove(layer);
3941 }
chaviw8b3871a2017-11-01 17:41:01 -07003942 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003943 }
chaviw8b3871a2017-11-01 17:41:01 -07003944 }
3945 if (what & layer_state_t::eReparentChildren) {
3946 if (layer->reparentChildren(s.reparentHandle)) {
3947 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003948 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003949 }
chaviw8b3871a2017-11-01 17:41:01 -07003950 if (what & layer_state_t::eDetachChildren) {
3951 layer->detachChildren();
3952 }
3953 if (what & layer_state_t::eOverrideScalingModeChanged) {
3954 layer->setOverrideScalingMode(s.overrideScalingMode);
3955 // We don't trigger a traversal here because if no other state is
3956 // changed, we don't want this to cause any more work
3957 }
Marissa Wall61c58622018-07-18 10:12:20 -07003958 if (what & layer_state_t::eTransformChanged) {
3959 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3960 }
3961 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3962 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3963 flags |= eTraversalNeeded;
3964 }
3965 if (what & layer_state_t::eCropChanged) {
3966 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3967 }
Marissa Wall861616d2018-10-22 12:52:23 -07003968 if (what & layer_state_t::eFrameChanged) {
3969 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3970 }
Marissa Wall61c58622018-07-18 10:12:20 -07003971 if (what & layer_state_t::eAcquireFenceChanged) {
3972 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3973 }
3974 if (what & layer_state_t::eDataspaceChanged) {
3975 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3976 }
3977 if (what & layer_state_t::eHdrMetadataChanged) {
3978 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3981 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3982 }
3983 if (what & layer_state_t::eApiChanged) {
3984 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3985 }
3986 if (what & layer_state_t::eSidebandStreamChanged) {
3987 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3988 }
Robert Carr720e5062018-07-30 17:45:14 -07003989 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003990 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
3991 layer->setInputInfo(s.inputInfo);
3992 flags |= eTraversalNeeded;
3993 } else {
3994 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3995 }
Robert Carr720e5062018-07-30 17:45:14 -07003996 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003997 if (what & layer_state_t::eMetadataChanged) {
3998 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3999 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004000 std::vector<sp<CallbackHandle>> callbackHandles;
4001 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4002 mTransactionCompletedThread.run();
4003 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4004 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4005 }
4006 }
Marissa Wall73411622019-01-25 10:45:41 -08004007
4008 if (what & layer_state_t::eBufferChanged) {
4009 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4010 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4011 s.buffer);
4012 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004013 if (what & layer_state_t::eCachedBufferChanged) {
4014 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004015 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4016 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004017 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4018 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004019 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4020 // Do not put anything that updates layer state or modifies flags after
4021 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004022 return flags;
4023}
4024
chaviw273171b2018-12-26 11:46:30 -08004025uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4026 uint32_t flags = 0;
4027 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4028 flags |= eTraversalNeeded;
4029 }
4030
chaviwa911b102019-02-14 10:18:33 -08004031 if (inputWindowCommands.syncInputWindows) {
4032 flags |= eTraversalNeeded;
4033 }
4034
Vishnu Nairec0ab382019-02-13 15:32:56 -08004035 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004036 return flags;
4037}
4038
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004039status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4040 uint32_t h, PixelFormat format, uint32_t flags,
4041 LayerMetadata metadata, sp<IBinder>* handle,
4042 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004043 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004044 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004045 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004046 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004047 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004048
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004049 status_t result = NO_ERROR;
4050
4051 sp<Layer> layer;
4052
Cody Northropbc755282017-03-31 12:00:08 -06004053 String8 uniqueName = getUniqueLayerName(name);
4054
Mathias Agopian3165cc22012-08-08 19:42:09 -07004055 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004056 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004057 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4058 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004059
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004060 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004061 case ISurfaceComposerClient::eFXSurfaceBufferState:
4062 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4063 break;
chaviw13fdc492017-06-27 12:40:18 -07004064 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004065 // check if buffer size is set for color layer.
4066 if (w > 0 || h > 0) {
4067 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4068 int(w), int(h));
4069 return BAD_VALUE;
4070 }
4071
chaviw13fdc492017-06-27 12:40:18 -07004072 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004073 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004074 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004075 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004076 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004077 // check if buffer size is set for container layer.
4078 if (w > 0 || h > 0) {
4079 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4080 int(w), int(h));
4081 return BAD_VALUE;
4082 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004083 result = createContainerLayer(client,
4084 uniqueName, w, h, flags,
4085 handle, &layer);
4086 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004087 default:
4088 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004089 break;
4090 }
4091
Dan Stoza7d89d062015-04-30 13:29:25 -07004092 if (result != NO_ERROR) {
4093 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004094 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004095
Chia-I Wuab0c3192017-08-01 11:29:00 -07004096 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4097 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004098 if (metadata.has(METADATA_WINDOW_TYPE)) {
4099 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4100 if (windowType == 441731) {
4101 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4102 layer->setPrimaryDisplayOnly();
4103 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004104 }
4105
Evan Roskyef876c92019-01-25 17:46:06 -08004106 layer->setMetadata(metadata);
Albert Chaulk479c60c2017-01-27 14:21:34 -05004107
Robert Carrb89ea9d2018-12-10 13:01:14 -08004108 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4109 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4110 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004111 if (result != NO_ERROR) {
4112 return result;
4113 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004114 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004115
4116 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004117 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004118}
4119
Cody Northropbc755282017-03-31 12:00:08 -06004120String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4121{
4122 bool matchFound = true;
4123 uint32_t dupeCounter = 0;
4124
4125 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4126 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4127
Dan Stoza436ccf32018-06-21 12:10:12 -07004128 // Grab the state lock since we're accessing mCurrentState
4129 Mutex::Autolock lock(mStateLock);
4130
Cody Northropbc755282017-03-31 12:00:08 -06004131 // Loop over layers until we're sure there is no matching name
4132 while (matchFound) {
4133 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004134 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004135 if (layer->getName() == uniqueName) {
4136 matchFound = true;
4137 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4138 }
4139 });
4140 }
4141
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004142 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4143 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004144
4145 return uniqueName;
4146}
4147
Marissa Wallfd668622018-05-10 10:21:13 -07004148status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4149 uint32_t w, uint32_t h, uint32_t flags,
4150 PixelFormat& format, sp<IBinder>* handle,
4151 sp<IGraphicBufferProducer>* gbp,
4152 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004153 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004154 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004155 case PIXEL_FORMAT_TRANSPARENT:
4156 case PIXEL_FORMAT_TRANSLUCENT:
4157 format = PIXEL_FORMAT_RGBA_8888;
4158 break;
4159 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004160 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004161 break;
4162 }
4163
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004164 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004165 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004166 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004167 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004168 *handle = layer->getHandle();
4169 *gbp = layer->getProducer();
4170 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004171 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004172
Marissa Wallfd668622018-05-10 10:21:13 -07004173 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004174 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004175}
4176
Marissa Wall61c58622018-07-18 10:12:20 -07004177status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4178 uint32_t w, uint32_t h, uint32_t flags,
4179 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004180 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004181 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004182 *handle = layer->getHandle();
4183 *outLayer = layer;
4184
4185 return NO_ERROR;
4186}
4187
chaviw13fdc492017-06-27 12:40:18 -07004188status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004189 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004190 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004191{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004192 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004193 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004194 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004195}
4196
Robert Carr6b3f6c52018-08-13 13:05:17 -07004197status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4198 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4199 sp<IBinder>* handle, sp<Layer>* outLayer)
4200{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004201 *outLayer =
4202 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004203 *handle = (*outLayer)->getHandle();
4204 return NO_ERROR;
4205}
4206
4207
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004208void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004209 mLayersPendingRemoval.add(layer);
4210 mLayersRemoved = true;
4211 setTransactionFlags(eTransactionNeeded);
4212}
4213
Robert Carr695d5282018-12-18 15:27:58 -08004214void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004215{
Robert Carr2e102c92018-10-23 12:11:15 -07004216 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004217 // If a layer has a parent, we allow it to out-live it's handle
4218 // with the idea that the parent holds a reference and will eventually
4219 // be cleaned up. However no one cleans up the top-level so we do so
4220 // here.
4221 if (layer->getParent() == nullptr) {
4222 mCurrentState.layersSortedByZ.remove(layer);
4223 }
4224 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004225 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004226}
4227
Mathias Agopianb60314a2012-04-10 22:09:54 -07004228// ---------------------------------------------------------------------------
4229
Andy McFadden13a082e2012-08-24 10:16:42 -07004230void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004231 const auto display = getDefaultDisplayDeviceLocked();
4232 if (!display) return;
4233
4234 const sp<IBinder> token = display->getDisplayToken().promote();
4235 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004236
Jesse Hall01e29052013-02-19 16:13:35 -08004237 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004238 Vector<ComposerState> state;
4239 Vector<DisplayState> displays;
4240 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004241 d.what = DisplayState::eDisplayProjectionChanged |
4242 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004243 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004244 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004245 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004246 d.frame.makeInvalid();
4247 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004248 d.width = 0;
4249 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004250 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004251 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004252
Dominik Laskowskie9774092018-12-11 10:04:24 -08004253 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004254
Dominik Laskowski83b88212018-12-11 13:34:06 -08004255 const nsecs_t vsyncPeriod = getVsyncPeriod();
4256 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004257
Brian Andersond0010582017-03-07 13:20:31 -08004258 // Use phase of 0 since phase is not known.
4259 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004260 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004261 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004262}
4263
4264void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004265 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004266 postMessageAsync(
4267 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004268}
4269
Dominik Laskowskie9774092018-12-11 10:04:24 -08004270void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004271 if (display->isVirtual()) {
4272 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004273 return;
4274 }
4275
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 const auto displayId = display->getId();
4277 LOG_ALWAYS_FATAL_IF(!displayId);
4278
Dominik Laskowski34157762018-10-31 13:07:19 -07004279 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004280
4281 int currentMode = display->getPowerMode();
4282 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004283 return;
4284 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004285
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004286 display->setPowerMode(mode);
4287
Lloyd Pique4dccc412018-01-22 17:21:36 -08004288 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004289 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004290 }
4291
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004292 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004293 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004294 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004295 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004296 mScheduler->onScreenAcquired(mAppConnectionHandle);
4297 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004300 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004301 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004302 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004303
4304 struct sched_param param = {0};
4305 param.sched_priority = 1;
4306 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4307 ALOGW("Couldn't set SCHED_FIFO on display on");
4308 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004309 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004310 // Turn off the display
4311 struct sched_param param = {0};
4312 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4313 ALOGW("Couldn't set SCHED_OTHER on display off");
4314 }
4315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004316 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004317 mScheduler->disableHardwareVsync(true);
4318 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004319 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004320
Dominik Laskowski075d3172018-05-24 15:50:06 -07004321 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004322 mVisibleRegionsDirty = true;
4323 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004324 } else if (mode == HWC_POWER_MODE_DOZE ||
4325 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004326 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004327 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004328 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004329 mScheduler->onScreenAcquired(mAppConnectionHandle);
4330 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004331 }
4332 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4333 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004334 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004335 mScheduler->disableHardwareVsync(true);
4336 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004337 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004338 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004339 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004340 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004341 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004342 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004343
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004344 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004345 mTimeStats->setPowerMode(mode);
Ana Krulecc2870422019-01-29 19:00:58 -08004346 if (mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004347 // Update refresh rate stats.
4348 mRefreshRateStats->setPowerMode(mode);
4349 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004350 }
4351
Dominik Laskowski34157762018-10-31 13:07:19 -07004352 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004353}
4354
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004355void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004356 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004357 const auto display = getDisplayDevice(displayToken);
4358 if (!display) {
4359 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4360 displayToken.get());
4361 } else if (display->isVirtual()) {
4362 ALOGW("Attempt to set power mode %d for virtual display", mode);
4363 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004364 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004365 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004366 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004367}
4368
4369// ---------------------------------------------------------------------------
4370
Dominik Laskowskic2867142019-01-21 11:33:38 -08004371status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4372 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004374
Mathias Agopianbd115332013-04-18 16:41:04 -07004375 IPCThreadState* ipc = IPCThreadState::self();
4376 const int pid = ipc->getCallingPid();
4377 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004378
Mathias Agopianbd115332013-04-18 16:41:04 -07004379 if ((uid != AID_SHELL) &&
4380 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004381 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4382 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004383 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004384 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004385 // (this would indicate SF is stuck, but we want to be able to
4386 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004387 status_t err = mStateLock.timedLock(s2ns(1));
4388 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004389 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004390 StringAppendF(&result,
4391 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4392 "(no locks held)\n",
4393 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004394 }
4395
Dominik Laskowskic2867142019-01-21 11:33:38 -08004396 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004397
Dominik Laskowskic2867142019-01-21 11:33:38 -08004398 static const std::unordered_map<std::string, Dumper> dumpers = {
4399 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4400 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4401 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004402 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004403 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004404 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004405 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4406 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004407 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4408 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4409 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4410 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4411 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4412 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004413 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004414 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4415 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004416
Dominik Laskowskic2867142019-01-21 11:33:38 -08004417 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004418
Dominik Laskowskic2867142019-01-21 11:33:38 -08004419 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4420 (it->second)(args, asProto, result);
4421 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004422 if (asProto) {
4423 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4424 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4425 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004426 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004427 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004428 }
4429
Mathias Agopian9795c422009-08-26 16:36:26 -07004430 if (locked) {
4431 mStateLock.unlock();
4432 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004433 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004434 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004435 return NO_ERROR;
4436}
4437
Dominik Laskowskic2867142019-01-21 11:33:38 -08004438void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004439 mCurrentState.traverseInZOrder(
4440 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004441}
4442
Dominik Laskowskic2867142019-01-21 11:33:38 -08004443void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004444 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004445
Dominik Laskowskic2867142019-01-21 11:33:38 -08004446 if (args.size() > 1) {
4447 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004448 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004449 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004450 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004451 }
Robert Carr2047fae2016-11-28 14:09:09 -08004452 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004453 } else {
4454 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004455 }
4456}
4457
Dominik Laskowskic2867142019-01-21 11:33:38 -08004458void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004459 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004460 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004461 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004462 }
Robert Carr2047fae2016-11-28 14:09:09 -08004463 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004464
Svetoslavd85084b2014-03-20 10:28:31 -07004465 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004466}
4467
Dominik Laskowskic2867142019-01-21 11:33:38 -08004468void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4469 mTimeStats->parseArgs(asProto, args, result);
4470}
4471
Jamie Gennis6547ff42013-07-16 20:12:42 -07004472// This should only be called from the main thread. Otherwise it would need
4473// the lock and should use mCurrentState rather than mDrawingState.
4474void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004475 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004476 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004477 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004478
4479 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4480}
4481
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004483 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004484
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004485 if (isLayerTripleBufferingDisabled())
4486 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004487
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4489 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4490 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4491 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4492 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4493 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004494 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004495}
4496
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004497void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004498 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004499 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004500 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004501 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004502
Ana Krulecba13ab32019-02-20 14:14:12 -08004503 StringAppendF(&result, "Scheduler enabled. 90Hz feature: %s\n", mUse90Hz ? "on" : "off");
4504 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4505 mUseSmart90ForVideo ? "on" : "off");
Ana Krulecc2870422019-01-29 19:00:58 -08004506 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004507}
4508
Yiwei Zhang5434a782018-12-05 18:06:32 -08004509void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4510 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004511 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4512 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004513 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004514 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004515 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004516 }
David Sodman4a36e932017-11-07 14:29:47 -08004517 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004518 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004519 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004520 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4521 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004522}
4523
Dan Stozae77c7662016-05-13 11:37:28 -07004524void SurfaceFlinger::recordBufferingStats(const char* layerName,
4525 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004526 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4527 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004528 for (const auto& segment : history) {
4529 if (!segment.usedThirdBuffer) {
4530 stats.twoBufferTime += segment.totalTime;
4531 }
4532 if (segment.occupancyAverage < 1.0f) {
4533 stats.doubleBufferedTime += segment.totalTime;
4534 } else if (segment.occupancyAverage < 2.0f) {
4535 stats.tripleBufferedTime += segment.totalTime;
4536 }
4537 ++stats.numSegments;
4538 stats.totalTime += segment.totalTime;
4539 }
4540}
4541
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4543 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004544
4545 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4546 const size_t count = currentLayers.size();
4547 for (size_t i=0 ; i<count ; i++) {
4548 currentLayers[i]->dumpFrameEvents(result);
4549 }
4550}
4551
Yiwei Zhang5434a782018-12-05 18:06:32 -08004552void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004553 result.append("Buffering stats:\n");
4554 result.append(" [Layer name] <Active time> <Two buffer> "
4555 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004556 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004557 typedef std::tuple<std::string, float, float, float> BufferTuple;
4558 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004559 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004560 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004561 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004562 if (stats.numSegments == 0) {
4563 continue;
4564 }
4565 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4566 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4567 stats.totalTime;
4568 float doubleBufferRatio = static_cast<float>(
4569 stats.doubleBufferedTime) / stats.totalTime;
4570 float tripleBufferRatio = static_cast<float>(
4571 stats.tripleBufferedTime) / stats.totalTime;
4572 sorted.insert({activeTime, {name, twoBufferRatio,
4573 doubleBufferRatio, tripleBufferRatio}});
4574 }
4575 for (const auto& sortedPair : sorted) {
4576 float activeTime = sortedPair.first;
4577 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4579 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004580 }
4581 result.append("\n");
4582}
4583
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004585 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004586 const auto displayId = display->getId();
4587 if (!displayId) {
4588 continue;
4589 }
4590 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004591 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004592 continue;
4593 }
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result,
4596 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4597 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004598 uint8_t port;
4599 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004600 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004601 result.append("no identification data\n");
4602 continue;
4603 }
4604
4605 if (!isEdid(data)) {
4606 result.append("unknown identification data: ");
4607 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004609 }
4610 result.append("\n");
4611 continue;
4612 }
4613
4614 const auto edid = parseEdid(data);
4615 if (!edid) {
4616 result.append("invalid EDID: ");
4617 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004619 }
4620 result.append("\n");
4621 continue;
4622 }
4623
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004625 result.append(edid->displayName.data(), edid->displayName.length());
4626 result.append("\"\n");
4627 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004628}
4629
Yiwei Zhang5434a782018-12-05 18:06:32 -08004630void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4631 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4632 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4633 StringAppendF(&result, "DisplayColorSetting: %s\n",
4634 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004635
4636 // TODO: print out if wide-color mode is active or not
4637
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004638 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004639 const auto displayId = display->getId();
4640 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004641 continue;
4642 }
4643
Yiwei Zhang5434a782018-12-05 18:06:32 -08004644 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004645 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004646 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004648 }
4649
Lloyd Pique32cbe282018-10-19 13:09:22 -07004650 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, " Current color mode: %s (%d)\n",
4652 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004653 }
4654 result.append("\n");
4655}
4656
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004657LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004658 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004659 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4660 const State& state = useDrawing ? mDrawingState : mCurrentState;
4661 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004662 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004663 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004664 });
4665
4666 return layersProto;
4667}
4668
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004669LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4670 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004671 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004672
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004673 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004674 resolution->set_w(displayDevice->getWidth());
4675 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004676
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004677 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004678 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004679
Lloyd Pique32cbe282018-10-19 13:09:22 -07004680 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4681 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4682 layersProto.set_global_transform(displayState.orientation);
4683
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004684 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004685 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004686 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004687 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004688 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004689 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004690 }
4691 });
4692
4693 return layersProto;
4694}
4695
Dominik Laskowskic2867142019-01-21 11:33:38 -08004696void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4697 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 Colorizer colorizer(colorize);
4699
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004700 // figure out if we're stuck somewhere
4701 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004702 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4704
4705 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004706 * Dump library configuration.
4707 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004708
4709 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004710 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004712 appendSfConfigString(result);
4713 appendUiConfigString(result);
4714 appendGuiConfigString(result);
4715 result.append("\n");
4716
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004717 result.append("\nDisplay identification data:\n");
4718 dumpDisplayIdentificationData(result);
4719
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004720 result.append("\nWide-Color information:\n");
4721 dumpWideColorInfo(result);
4722
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004723 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004724 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004725 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004726 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004727 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004728
Andy McFadden41d67d72014-04-25 16:58:34 -07004729 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004730 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004731 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004732 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004733 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004734
Dan Stozab90cf072015-03-05 11:05:59 -08004735 dumpStaticScreenStats(result);
4736 result.append("\n");
4737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004739
Dan Stozae77c7662016-05-13 11:37:28 -07004740 dumpBufferingStats(result);
4741
Andy McFadden4803b742012-09-24 19:07:20 -07004742 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743 * Dump the visible layer list
4744 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004745 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4747 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4748 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004749 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004750
Chia-I Wu2f884132018-09-13 15:17:58 -07004751 {
4752 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4753 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004754 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004755 result.append("\n");
4756 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004757
4758 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004759 * Dump Display state
4760 */
4761
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004762 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004764 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004765 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004766 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004767 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004768 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004769
4770 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771 * Dump SurfaceFlinger global state
4772 */
4773
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004775 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004776 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004777
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004778 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004779
Dominik Laskowski075d3172018-05-24 15:50:06 -07004780 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004781 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4782 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4784 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004785 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004786 StringAppendF(&result,
4787 " transaction-flags : %08x\n"
4788 " gpu_to_cpu_unsupported : %d\n",
4789 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004790
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004791 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004792 displayId && getHwComposer().isConnected(*displayId)) {
4793 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 StringAppendF(&result,
4795 " refresh-rate : %f fps\n"
4796 " x-dpi : %f\n"
4797 " y-dpi : %f\n",
4798 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4799 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004800 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004801
Yiwei Zhang5434a782018-12-05 18:06:32 -08004802 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004803
Dan Stozae22aec72016-08-01 13:20:59 -07004804 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004805 * Tracing state
4806 */
4807 mTracing.dump(result);
4808 result.append("\n");
4809
4810 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004811 * HWC layer minidump
4812 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004813 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004814 const auto displayId = display->getId();
4815 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004816 continue;
4817 }
4818
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004820 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004821 const sp<DisplayDevice> displayDevice = display;
4822 mCurrentState.traverseInZOrder(
4823 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004824 result.append("\n");
4825 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004826
4827 /*
4828 * Dump HWComposer state
4829 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004830 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004831 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004832 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004833 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004834 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004835 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004836
4837 /*
4838 * Dump gralloc state
4839 */
4840 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4841 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004842
4843 /*
4844 * Dump VrFlinger state if in use.
4845 */
4846 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4847 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004848 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004849 result.append("\n");
4850 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004851
4852 /**
4853 * Scheduler dump state.
4854 */
Ana Krulecc2870422019-01-29 19:00:58 -08004855 result.append("\nScheduler state:\n");
4856 result.append(mScheduler->doDump() + "\n");
4857 result.append(mRefreshRateStats->doDump() + "\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004858}
4859
Dominik Laskowski075d3172018-05-24 15:50:06 -07004860const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004861 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004862 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004863 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004864 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004865 }
4866 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004867
Dominik Laskowski34157762018-10-31 13:07:19 -07004868 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004869 static const Vector<sp<Layer>> empty;
4870 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004871}
4872
Chia-I Wu28f320b2018-05-03 11:02:56 -07004873void SurfaceFlinger::updateColorMatrixLocked() {
4874 mat4 colorMatrix;
4875 if (mGlobalSaturationFactor != 1.0f) {
4876 // Rec.709 luma coefficients
4877 float3 luminance{0.213f, 0.715f, 0.072f};
4878 luminance *= 1.0f - mGlobalSaturationFactor;
4879 mat4 saturationMatrix = mat4(
4880 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4881 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4882 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4883 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4884 );
4885 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4886 } else {
4887 colorMatrix = mClientColorMatrix * mDaltonizer();
4888 }
4889
4890 if (mCurrentState.colorMatrix != colorMatrix) {
4891 mCurrentState.colorMatrix = colorMatrix;
4892 mCurrentState.colorMatrixChanged = true;
4893 setTransactionFlags(eTransactionNeeded);
4894 }
4895}
4896
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004897status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004898#pragma clang diagnostic push
4899#pragma clang diagnostic error "-Wswitch-enum"
4900 switch (static_cast<ISurfaceComposerTag>(code)) {
4901 // These methods should at minimum make sure that the client requested
4902 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004903 case BOOT_FINISHED:
4904 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905 case CREATE_DISPLAY:
4906 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004907 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004908 case GET_ACTIVE_COLOR_MODE:
4909 case GET_ANIMATION_FRAME_STATS:
4910 case GET_HDR_CAPABILITIES:
4911 case SET_ACTIVE_CONFIG:
4912 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004913 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004914 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004915 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004916 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4917 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004918 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4919 IPCThreadState* ipc = IPCThreadState::self();
4920 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4921 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004922 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 }
Robert Carr1db73f62016-12-21 12:58:51 -08004924 return OK;
4925 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004926 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004927 IPCThreadState* ipc = IPCThreadState::self();
4928 const int pid = ipc->getCallingPid();
4929 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004930 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4931 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004932 return PERMISSION_DENIED;
4933 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004934 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004936 // Used by apps to hook Choreographer to SurfaceFlinger.
4937 case CREATE_DISPLAY_EVENT_CONNECTION:
4938 // The following calls are currently used by clients that do not
4939 // request necessary permissions. However, they do not expose any secret
4940 // information, so it is OK to pass them.
4941 case AUTHENTICATE_SURFACE:
4942 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004943 case GET_PHYSICAL_DISPLAY_IDS:
4944 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004945 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004946 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947 case GET_DISPLAY_CONFIGS:
4948 case GET_DISPLAY_STATS:
4949 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4950 // Calling setTransactionState is safe, because you need to have been
4951 // granted a reference to Client* and Handle* to do anything with it.
4952 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004953 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004954 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004955 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004956 case GET_PROTECTED_CONTENT_SUPPORT:
chaviw291d88a2019-02-14 10:33:58 -08004957 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004958 return OK;
4959 }
4960 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004961 case CAPTURE_SCREEN:
4962 case ADD_REGION_SAMPLING_LISTENER:
4963 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004964 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004965 IPCThreadState* ipc = IPCThreadState::self();
4966 const int pid = ipc->getCallingPid();
4967 const int uid = ipc->getCallingUid();
4968 if ((uid != AID_GRAPHICS) &&
4969 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4970 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4971 return PERMISSION_DENIED;
4972 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004973 return OK;
4974 }
4975 // The following codes are deprecated and should never be allowed to access SF.
4976 case CONNECT_DISPLAY_UNUSED:
4977 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4978 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4979 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004981 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004982
4983 // These codes are used for the IBinder protocol to either interrogate the recipient
4984 // side of the transaction for its canonical interface descriptor or to dump its state.
4985 // We let them pass by default.
4986 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4987 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4988 code == IBinder::SYSPROPS_TRANSACTION) {
4989 return OK;
4990 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004991 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004992 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004993 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004994 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4995 return OK;
4996 }
4997 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4998 return PERMISSION_DENIED;
4999#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005000}
5001
Ana Krulec13be8ad2018-08-21 02:43:56 +00005002status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5003 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005004 status_t credentialCheck = CheckTransactCodeCredentials(code);
5005 if (credentialCheck != OK) {
5006 return credentialCheck;
5007 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5010 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005011 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005012 IPCThreadState* ipc = IPCThreadState::self();
5013 const int uid = ipc->getCallingUid();
5014 if (CC_UNLIKELY(uid != AID_SYSTEM
5015 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005016 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005017 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005018 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 return PERMISSION_DENIED;
5020 }
5021 int n;
5022 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005023 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005024 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 return NO_ERROR;
5026 case 1002: // SHOW_UPDATES
5027 n = data.readInt32();
5028 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005029 invalidateHwcGeometry();
5030 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005032 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005033 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005034 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005035 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005036 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005037 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005038 setTransactionFlags(
5039 eTransactionNeeded|
5040 eDisplayTransactionNeeded|
5041 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005042 return NO_ERROR;
5043 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005044 case 1006:{ // send empty update
5045 signalRefresh();
5046 return NO_ERROR;
5047 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005048 case 1008: // toggle use of hw composer
5049 n = data.readInt32();
5050 mDebugDisableHWC = n ? 1 : 0;
5051 invalidateHwcGeometry();
5052 repaintEverything();
5053 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005054 case 1009: // toggle use of transform hint
5055 n = data.readInt32();
5056 mDebugDisableTransformHint = n ? 1 : 0;
5057 invalidateHwcGeometry();
5058 repaintEverything();
5059 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005060 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005061 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005062 reply->writeInt32(0);
5063 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005064 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005065 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005066 return NO_ERROR;
5067 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005068 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005069 if (!display) {
5070 return NAME_NOT_FOUND;
5071 }
5072
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005073 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005074 return NO_ERROR;
5075 }
5076 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005077 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005078 // daltonize
5079 n = data.readInt32();
5080 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005081 case 1:
5082 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5083 break;
5084 case 2:
5085 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5086 break;
5087 case 3:
5088 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5089 break;
5090 default:
5091 mDaltonizer.setType(ColorBlindnessType::None);
5092 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005093 }
5094 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005095 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005096 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005097 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005098 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099
5100 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005101 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005103 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005105 // apply a color matrix
5106 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005107 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005108 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005109 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005110 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005111 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005112 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005113 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005114 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005115 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005116 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005117
5118 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5119 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005120 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005121 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5122 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5123 }
5124
Chia-I Wu28f320b2018-05-03 11:02:56 -07005125 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005126 return NO_ERROR;
5127 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005128 // This is an experimental interface
5129 // Needs to be shifted to proper binder interface when we productize
5130 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005131 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005132 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005133 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005134 return NO_ERROR;
5135 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005136 case 1017: {
5137 n = data.readInt32();
5138 mForceFullDamage = static_cast<bool>(n);
5139 return NO_ERROR;
5140 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005141 case 1018: { // Modify Choreographer's phase offset
5142 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005143 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005144 return NO_ERROR;
5145 }
5146 case 1019: { // Modify SurfaceFlinger's phase offset
5147 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005148 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005149 return NO_ERROR;
5150 }
Irvel468051e2016-06-13 16:44:44 -07005151 case 1020: { // Layer updates interceptor
5152 n = data.readInt32();
5153 if (n) {
5154 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005155 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005156 }
5157 else{
5158 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005159 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005160 }
5161 return NO_ERROR;
5162 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005163 case 1021: { // Disable HWC virtual displays
5164 n = data.readInt32();
5165 mUseHwcVirtualDisplays = !n;
5166 return NO_ERROR;
5167 }
Romain Guy0147a172017-06-01 13:53:56 -07005168 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005169 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005170 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005171
Chia-I Wu28f320b2018-05-03 11:02:56 -07005172 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005173 return NO_ERROR;
5174 }
Romain Guy54f154a2017-10-24 21:40:32 +01005175 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005176 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005177 invalidateHwcGeometry();
5178 repaintEverything();
5179 return NO_ERROR;
5180 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005181 // Deprecate, use 1030 to check whether the device is color managed.
5182 case 1024: {
5183 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005184 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005185 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005186 n = data.readInt32();
5187 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005188 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005189 mTracing.enable();
5190 doTracing("tracing.enable");
5191 reply->writeInt32(NO_ERROR);
5192 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005193 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005194 status_t err = mTracing.disable();
5195 reply->writeInt32(err);
5196 }
5197 return NO_ERROR;
5198 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005199 case 1026: { // Get layer tracing status
5200 reply->writeBool(mTracing.isEnabled());
5201 return NO_ERROR;
5202 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005203 // Is a DisplayColorSetting supported?
5204 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005205 const auto display = getDefaultDisplayDevice();
5206 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005207 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005208 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005209
5210 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5211 switch (setting) {
5212 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005213 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005214 break;
5215 case DisplayColorSetting::UNMANAGED:
5216 reply->writeBool(true);
5217 break;
5218 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005219 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005220 break;
5221 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005222 reply->writeBool(
5223 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005224 break;
5225 }
5226 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005227 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005228 // Is VrFlinger active?
5229 case 1028: {
5230 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005231 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005232 return NO_ERROR;
5233 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005234 // Is device color managed?
5235 case 1030: {
5236 reply->writeBool(useColorManagement);
5237 return NO_ERROR;
5238 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005239 // Override default composition data space
5240 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5241 // && adb shell stop zygote && adb shell start zygote
5242 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5243 // adb shell stop zygote && adb shell start zygote
5244 case 1031: {
5245 Mutex::Autolock _l(mStateLock);
5246 n = data.readInt32();
5247 if (n) {
5248 n = data.readInt32();
5249 if (n) {
5250 Dataspace dataspace = static_cast<Dataspace>(n);
5251 if (!validateCompositionDataspace(dataspace)) {
5252 return BAD_VALUE;
5253 }
5254 mDefaultCompositionDataspace = dataspace;
5255 }
5256 n = data.readInt32();
5257 if (n) {
5258 Dataspace dataspace = static_cast<Dataspace>(n);
5259 if (!validateCompositionDataspace(dataspace)) {
5260 return BAD_VALUE;
5261 }
5262 mWideColorGamutCompositionDataspace = dataspace;
5263 }
5264 } else {
5265 // restore composition data space.
5266 mDefaultCompositionDataspace = defaultCompositionDataspace;
5267 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5268 }
5269 return NO_ERROR;
5270 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005271 }
5272 }
5273 return err;
5274}
5275
Steven Thomas6d8110b2017-08-31 18:24:21 -07005276void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005277 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005278 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005279}
5280
Ana Krulec7d1d6832018-12-27 11:10:09 -08005281void SurfaceFlinger::repaintEverythingForHWC() {
5282 mRepaintEverything = true;
5283 mEventQueue->invalidateForHWC();
5284}
5285
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005286// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5287class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005288public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005289 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5290 ~WindowDisconnector() {
5291 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005292 }
5293
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005294private:
5295 ANativeWindow* mWindow;
5296 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005297};
5298
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005299status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005300 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5301 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005302 uint32_t reqWidth, uint32_t reqHeight,
5303 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005304 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005306
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005307 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005308
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005309 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5310
Chia-I Wu20261cb2018-08-23 12:55:44 -07005311 sp<DisplayDevice> display;
5312 {
5313 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005314
Chia-I Wu20261cb2018-08-23 12:55:44 -07005315 display = getDisplayDeviceLocked(displayToken);
5316 if (!display) return BAD_VALUE;
5317
Chia-I Wucb023152018-08-28 12:57:23 -07005318 // set the requested width/height to the logical display viewport size
5319 // by default
5320 if (reqWidth == 0 || reqHeight == 0) {
5321 reqWidth = uint32_t(display->getViewport().width());
5322 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005323 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005324 }
5325
Peiyong Lin0e003c92018-09-17 11:09:51 -07005326 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5327 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005328
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005329 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5330 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005331 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5332 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005333}
5334
5335status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005336 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5337 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005338 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005339 ATRACE_CALL();
5340
5341 class LayerRenderArea : public RenderArea {
5342 public:
Robert Carr578038f2018-03-09 12:25:24 -08005343 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005344 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5345 bool childrenOnly)
5346 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005347 mLayer(layer),
5348 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005349 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005350 mFlinger(flinger),
5351 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005352 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005353 Rect getBounds() const override {
5354 const Layer::State& layerState(mLayer->getDrawingState());
5355 return mLayer->getBufferSize(layerState);
5356 }
Marissa Wall61c58622018-07-18 10:12:20 -07005357 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005358 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005359 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005360 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005361 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005362 }
chaviwa76b2712017-09-20 12:02:26 -07005363 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005364 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005365 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005366 Rect getSourceCrop() const override {
5367 if (mCrop.isEmpty()) {
5368 return getBounds();
5369 } else {
5370 return mCrop;
5371 }
5372 }
Robert Carr578038f2018-03-09 12:25:24 -08005373 class ReparentForDrawing {
5374 public:
5375 const sp<Layer>& oldParent;
5376 const sp<Layer>& newParent;
5377
Vishnu Nair4351ad52019-02-11 14:13:02 -08005378 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5379 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005380 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005381 // Compute and cache the bounds for the new parent layer.
5382 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005383 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005384 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005385 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005386 };
5387
5388 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005389 const Rect sourceCrop = getSourceCrop();
5390 // no need to check rotation because there is none
5391 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5392 sourceCrop.height() != getReqHeight();
5393
Robert Carr578038f2018-03-09 12:25:24 -08005394 if (!mChildrenOnly) {
5395 mTransform = mLayer->getTransform().inverse();
5396 drawLayers();
5397 } else {
5398 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005399 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005400 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5401 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005402
Vishnu Nair4351ad52019-02-11 14:13:02 -08005403 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005404 drawLayers();
5405 }
5406 }
chaviwa76b2712017-09-20 12:02:26 -07005407
chaviwa76b2712017-09-20 12:02:26 -07005408 private:
chaviw7206d492017-11-10 16:16:12 -08005409 const sp<Layer> mLayer;
5410 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005411
5412 // In the "childrenOnly" case we reparent the children to a screenshot
5413 // layer which has no properties set and which does not draw.
5414 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005415 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005416 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005417
5418 SurfaceFlinger* mFlinger;
5419 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005420 };
5421
5422 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5423 auto parent = layerHandle->owner.promote();
5424
Robert Carr2e102c92018-10-23 12:11:15 -07005425 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005426 ALOGE("captureLayers called with a removed parent");
5427 return NAME_NOT_FOUND;
5428 }
5429
Robert Carr578038f2018-03-09 12:25:24 -08005430 const int uid = IPCThreadState::self()->getCallingUid();
5431 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005432 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005433 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5434 return PERMISSION_DENIED;
5435 }
5436
chaviw7206d492017-11-10 16:16:12 -08005437 Rect crop(sourceCrop);
5438 if (sourceCrop.width() <= 0) {
5439 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005440 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005441 }
5442
5443 if (sourceCrop.height() <= 0) {
5444 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005445 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005446 }
5447
5448 int32_t reqWidth = crop.width() * frameScale;
5449 int32_t reqHeight = crop.height() * frameScale;
5450
Chia-I Wu20261cb2018-08-23 12:55:44 -07005451 // really small crop or frameScale
5452 if (reqWidth <= 0) {
5453 reqWidth = 1;
5454 }
5455 if (reqHeight <= 0) {
5456 reqHeight = 1;
5457 }
5458
Peiyong Lin0e003c92018-09-17 11:09:51 -07005459 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005460
Robert Carr578038f2018-03-09 12:25:24 -08005461 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005462 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5463 if (!layer->isVisible()) {
5464 return;
Robert Carr578038f2018-03-09 12:25:24 -08005465 } else if (childrenOnly && layer == parent.get()) {
5466 return;
chaviwa76b2712017-09-20 12:02:26 -07005467 }
5468 visitor(layer);
5469 });
5470 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005471 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005472}
5473
5474status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5475 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005476 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005477 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005478 bool useIdentityTransform) {
5479 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005480
Peiyong Lin0e003c92018-09-17 11:09:51 -07005481 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005482 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5483 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005484 *outBuffer =
5485 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5486 static_cast<android_pixel_format>(reqPixelFormat), 1,
5487 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005488
Dan Stozaec460082018-12-17 15:35:09 -08005489 return captureScreenCore(renderArea, traverseLayers, *outBuffer, useIdentityTransform);
5490}
5491
5492status_t SurfaceFlinger::captureScreenCore(RenderArea& renderArea,
5493 TraverseLayersFunction traverseLayers,
5494 const sp<GraphicBuffer>& buffer,
5495 bool useIdentityTransform) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005496 // This mutex protects syncFd and captureResult for communication of the return values from the
5497 // main thread back to this Binder thread
5498 std::mutex captureMutex;
5499 std::condition_variable captureCondition;
5500 std::unique_lock<std::mutex> captureLock(captureMutex);
5501 int syncFd = -1;
5502 std::optional<status_t> captureResult;
5503
Robert Carr03480e22018-01-04 16:02:06 -08005504 const int uid = IPCThreadState::self()->getCallingUid();
5505 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5506
Dominik Laskowski8c001672018-05-30 16:52:06 -07005507 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005508 // If there is a refresh pending, bug out early and tell the binder thread to try again
5509 // after the refresh.
5510 if (mRefreshPending) {
5511 ATRACE_NAME("Skipping screenshot for now");
5512 std::unique_lock<std::mutex> captureLock(captureMutex);
5513 captureResult = std::make_optional<status_t>(EAGAIN);
5514 captureCondition.notify_one();
5515 return;
5516 }
5517
5518 status_t result = NO_ERROR;
5519 int fd = -1;
5520 {
5521 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005522 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005523 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr578038f2018-03-09 12:25:24 -08005524 useIdentityTransform, forSystem, &fd);
5525 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005526 }
5527
5528 {
5529 std::unique_lock<std::mutex> captureLock(captureMutex);
5530 syncFd = fd;
5531 captureResult = std::make_optional<status_t>(result);
5532 captureCondition.notify_one();
5533 }
5534 });
5535
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005536 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005537 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005538 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005539 while (*captureResult == EAGAIN) {
5540 captureResult.reset();
5541 result = postMessageAsync(message);
5542 if (result != NO_ERROR) {
5543 return result;
5544 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005545 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005546 }
5547 result = *captureResult;
5548 }
5549
5550 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005551 sync_wait(syncFd, -1);
5552 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005553 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005554
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005555 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005556}
5557
chaviwa76b2712017-09-20 12:02:26 -07005558void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005559 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005560 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5561 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005562 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005563
chaviwa76b2712017-09-20 12:02:26 -07005564 const auto reqWidth = renderArea.getReqWidth();
5565 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005566 const auto sourceCrop = renderArea.getSourceCrop();
5567 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005568
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005569 renderengine::DisplaySettings clientCompositionDisplay;
5570 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005571
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005572 // assume that bounds are never offset, and that they are the same as the
5573 // buffer bounds.
5574 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5575 ui::Transform transform = renderArea.getTransform();
5576 mat4 m;
5577 m[0][0] = transform[0][0];
5578 m[0][1] = transform[0][1];
5579 m[0][3] = transform[0][2];
5580 m[1][0] = transform[1][0];
5581 m[1][1] = transform[1][1];
5582 m[1][3] = transform[1][2];
5583 m[3][0] = transform[2][0];
5584 m[3][1] = transform[2][1];
5585 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005586
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005587 clientCompositionDisplay.globalTransform = m;
5588 mat4 rotMatrix;
5589 // Displacement for repositioning the clipping rectangle after rotating it
5590 // with the rotation hint.
5591 int displacementX = 0;
5592 int displacementY = 0;
5593 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5594 switch (rotation) {
5595 case ui::Transform::ROT_90:
5596 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5597 displacementX = reqWidth;
5598 break;
5599 case ui::Transform::ROT_180:
5600 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5601 displacementX = reqWidth;
5602 displacementY = reqHeight;
5603 break;
5604 case ui::Transform::ROT_270:
5605 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5606 displacementY = reqHeight;
5607 break;
5608 default:
5609 break;
5610 }
5611 // We need to transform the clipping window into the right spot.
5612 // First, rotate the clipping rectangle by the rotation hint to get the
5613 // right orientation
5614 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5615 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5616 const vec4 rotClipTL = rotMatrix * clipTL;
5617 const vec4 rotClipBR = rotMatrix * clipBR;
5618 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5619 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5620 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5621 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5622
5623 // Now reposition the clipping rectangle with the displacement vector
5624 // computed above.
5625 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5626
5627 clientCompositionDisplay.clip =
5628 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5629 newClipRight + displacementX, newClipBottom + displacementY);
5630
5631 // We need to perform the same transformation in layer space, so propagate
5632 // it to the global transform.
5633 mat4 clipTransform = displacementMat * rotMatrix;
5634 clientCompositionDisplay.globalTransform *= clipTransform;
5635 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5636 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637
chaviw50da5042018-04-09 13:49:37 -07005638 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005639
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005640 renderengine::LayerSettings fillLayer;
5641 fillLayer.source.buffer.buffer = nullptr;
5642 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5643 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5644 fillLayer.alpha = half(alpha);
5645 clientCompositionLayers.push_back(fillLayer);
5646
5647 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005648 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005649 renderengine::LayerSettings layerSettings;
5650 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5651 layerSettings);
5652 if (prepared) {
5653 clientCompositionLayers.push_back(layerSettings);
5654 }
chaviwa76b2712017-09-20 12:02:26 -07005655 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005656
5657 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005658 // Use an empty fence for the buffer fence, since we just created the buffer so
5659 // there is no need for synchronization with the GPU.
5660 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005661 base::unique_fd drawFence;
5662 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mouri6338c9d2019-02-07 16:57:51 -08005663 std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005664
5665 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005666}
5667
chaviwa76b2712017-09-20 12:02:26 -07005668status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5669 TraverseLayersFunction traverseLayers,
5670 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005671 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005672 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005673 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005674 ATRACE_CALL();
5675
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005676 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005677
5678 traverseLayers([&](Layer* layer) {
5679 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5680 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005681
Robert Carr03480e22018-01-04 16:02:06 -08005682 // We allow the system server to take screenshots of secure layers for
5683 // use in situations like the Screen-rotation animation and place
5684 // the impetus on WindowManager to not persist them.
5685 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005686 ALOGW("FB is protected: PERMISSION_DENIED");
5687 return PERMISSION_DENIED;
5688 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005689 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005690 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005691}
5692
chaviw95ef3c42019-02-14 10:55:09 -08005693void SurfaceFlinger::setInputWindowsFinished() {
5694 Mutex::Autolock _l(mStateLock);
5695
5696 mPendingSyncInputWindows = false;
5697 mTransactionCV.broadcast();
5698}
chaviw5f21a5e2019-02-14 10:00:34 -08005699
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005700// ---------------------------------------------------------------------------
5701
Dan Stoza412903f2017-04-27 13:42:17 -07005702void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5703 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005704}
5705
Dan Stoza412903f2017-04-27 13:42:17 -07005706void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5707 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005708}
5709
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005710void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005711 const LayerVector::Visitor& visitor) {
5712 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005713 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005714 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005715 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005716 continue;
5717 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005718 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005719 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005720 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005721 return;
5722 }
chaviwa76b2712017-09-20 12:02:26 -07005723 if (!layer->isVisible()) {
5724 return;
5725 }
5726 visitor(layer);
5727 });
5728 }
5729}
5730
chaviw291d88a2019-02-14 10:33:58 -08005731// ----------------------------------------------------------------------------
5732
5733void SetInputWindowsListener::onSetInputWindowsFinished() {
5734 mFlinger->setInputWindowsFinished();
5735}
5736
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005737}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005738
Lloyd Pique074e8122018-07-26 12:57:23 -07005739
Mathias Agopian3f844832013-08-07 21:24:32 -07005740#if defined(__gl_h_)
5741#error "don't include gl/gl.h in this file"
5742#endif
5743
5744#if defined(__gl2_h_)
5745#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005746#endif