blob: 08fde8d0c0386345de425fdf708b68dc3b19d241 [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()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700295 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700296 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800297 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800298 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800299 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700300 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700301 mMainThreadId(std::this_thread::get_id()),
302 mCompositionEngine{getFactory().createCompositionEngine()} {}
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 Krulec98b5b242018-08-10 15:03:23 -0700398 property_get("debug.sf.use_scheduler", value, "0");
399 mUseScheduler = atoi(value);
400
Ady Abrahamc3e21312019-02-07 14:30:23 -0800401 if (!mUseScheduler) {
402 mPrimaryDispSync =
403 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
404 SurfaceFlinger::dispSyncPresentTimeOffset);
405 }
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
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800587 postMessageAsync(new LambdaMessage([this] {
588 readPersistentProperties();
589 mBootStage = BootStage::FINISHED;
590 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800591}
592
Dan Stoza436ccf32018-06-21 12:10:12 -0700593uint32_t SurfaceFlinger::getNewTexture() {
594 {
595 std::lock_guard lock(mTexturePoolMutex);
596 if (!mTexturePool.empty()) {
597 uint32_t name = mTexturePool.back();
598 mTexturePool.pop_back();
599 ATRACE_INT("TexturePoolSize", mTexturePool.size());
600 return name;
601 }
602
603 // The pool was too small, so increase it for the future
604 ++mTexturePoolSize;
605 }
606
607 // The pool was empty, so we need to get a new texture name directly using a
608 // blocking call to the main thread
609 uint32_t name = 0;
610 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
611 return name;
612}
613
Mathias Agopian3f844832013-08-07 21:24:32 -0700614void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700615 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700616}
617
Wei Wangf9b05ee2017-07-19 20:59:39 -0700618// Do not call property_set on main thread which will be blocked by init
619// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700620void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700621 ALOGI( "SurfaceFlinger's main thread ready to run. "
622 "Initializing graphics H/W...");
623
Ana Krulec757f63a2019-01-25 10:46:18 -0800624 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627
Dominik Laskowski83b88212018-12-11 13:34:06 -0800628 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800632 mScheduler = getFactory().createScheduler(
633 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
634
Ana Krulec757f63a2019-01-25 10:46:18 -0800635 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
636 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
637 mPhaseOffsets->setRefreshRateType(
638 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700639
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 mAppConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800641 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800642 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700643 impl::EventThread::InterceptVSyncsCallback());
644 mSfConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800645 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800646 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 mInterceptor->saveVSyncEvent(timestamp);
648 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800649
Ana Krulec98b5b242018-08-10 15:03:23 -0700650 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700651 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
652 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700653 } else {
654 mEventThreadSource =
655 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800656 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700657 mEventThread =
658 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700659 impl::EventThread::InterceptVSyncsCallback(),
660 "appEventThread");
661 mSfEventThreadSource =
662 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800663 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700664
665 mSFEventThread =
666 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700667 [this](nsecs_t timestamp) {
668 mInterceptor->saveVSyncEvent(timestamp);
669 },
670 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800671 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700672 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
673 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700676 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700677 renderEngineFeature |= (useColorManagement ?
678 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700679 renderEngineFeature |= (useContextPriority ?
680 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700681
682 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700684 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700685 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700686
687 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
688 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700689 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
690 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800691 // Process any initial hotplug and resulting display changes.
692 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 const auto display = getDefaultDisplayDeviceLocked();
694 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800697
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700700 // This callback is called from the vr flinger dispatch thread. We
701 // need to call signalTransaction(), which requires holding
702 // mStateLock when we're not on the main thread. Acquiring
703 // mStateLock from the vr flinger dispatch thread might trigger a
704 // deadlock in surface flinger (see b/66916578), so post a message
705 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700706 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700707 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
708 mVrFlingerRequestsDisplay = requestDisplay;
709 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700710 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700712 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
713 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700714 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700715 .value_or(0),
716 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800717 if (!mVrFlinger) {
718 ALOGE("Failed to start vrflinger");
719 }
720 }
721
Ady Abrahamc3e21312019-02-07 14:30:23 -0800722 if (!mUseScheduler) {
723 mEventControlThread = getFactory().createEventControlThread(
724 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
725 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700726
Mathias Agopian92a979a2012-08-02 18:32:23 -0700727 // initialize our drawing state
728 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700729
Andy McFadden13a082e2012-08-24 10:16:42 -0700730 // set initial conditions (e.g. unblank default device)
731 initializeDisplays();
732
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700733 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700734
Wei Wangf9b05ee2017-07-19 20:59:39 -0700735 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700736
737 const bool presentFenceReliable =
738 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
739 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700740
741 if (mStartPropertySetThread->Start() != NO_ERROR) {
742 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800744
Ana Krulec7d1d6832018-12-27 11:10:09 -0800745 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800746 mScheduler->setExpiredIdleTimerCallback([this] {
747 Mutex::Autolock lock(mStateLock);
748 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800749 });
Ady Abrahama1a49af2019-02-07 14:36:55 -0800750 mScheduler->setResetIdleTimerCallback([this] {
751 Mutex::Autolock lock(mStateLock);
752 setRefreshRateTo(RefreshRateType::PERFORMANCE);
753 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800754
Alec Mourifb571ea2019-01-24 18:42:10 -0800755 mRefreshRateStats =
756 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
757 *display->getId()),
758 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800759 }
760
Dan Stoza9e56aa02015-11-02 13:00:03 -0800761 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700762}
763
Romain Guy11d63f42017-07-20 12:47:14 -0700764void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700765 Mutex::Autolock _l(mStateLock);
766
Romain Guy11d63f42017-07-20 12:47:14 -0700767 char value[PROPERTY_VALUE_MAX];
768
769 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800770 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700771 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800772 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100773
774 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700775 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800776
777 property_get("persist.sys.sf.color_mode", value, "0");
778 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700779}
780
Mathias Agopiana67e4182012-06-19 17:26:12 -0700781void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800782 // Start boot animation service by setting a property mailbox
783 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700784 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800785 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700786 if (mStartPropertySetThread->join() != NO_ERROR) {
787 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800788 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700789}
790
Mathias Agopian875d8e12013-06-07 15:35:48 -0700791size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700792 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700793}
794
Mathias Agopian875d8e12013-06-07 15:35:48 -0700795size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700796 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700797}
798
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800799// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800800
Jamie Gennis582270d2011-08-17 18:19:00 -0700801bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800802 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800803 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800804 return authenticateSurfaceTextureLocked(bufferProducer);
805}
806
807bool SurfaceFlinger::authenticateSurfaceTextureLocked(
808 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800809 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800810 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800811}
812
Brian Anderson6b376712017-04-04 10:51:39 -0700813status_t SurfaceFlinger::getSupportedFrameTimestamps(
814 std::vector<FrameEvent>* outSupported) const {
815 *outSupported = {
816 FrameEvent::REQUESTED_PRESENT,
817 FrameEvent::ACQUIRE,
818 FrameEvent::LATCH,
819 FrameEvent::FIRST_REFRESH_START,
820 FrameEvent::LAST_REFRESH_START,
821 FrameEvent::GPU_COMPOSITION_DONE,
822 FrameEvent::DEQUEUE_READY,
823 FrameEvent::RELEASE,
824 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700825 ConditionalLock _l(mStateLock,
826 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700827 if (!getHwComposer().hasCapability(
828 HWC2::Capability::PresentFenceIsNotReliable)) {
829 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
830 }
831 return NO_ERROR;
832}
833
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800834status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
835 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700836 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 return BAD_VALUE;
838 }
839
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800840 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700841 if (!displayId) {
842 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700843 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844
Mathias Agopian8b736f12012-08-13 17:54:26 -0700845 // TODO: Not sure if display density should handled by SF any longer
846 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700847 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700849 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800850 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700851 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 }
853 return density;
854 }
855 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700856 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700857 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700858 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700859 return getDensityFromProperty("ro.sf.lcd_density"); }
860 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700861
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700863
Dominik Laskowski075d3172018-05-24 15:50:06 -0700864 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700865 DisplayInfo info = DisplayInfo();
866
Dan Stoza9e56aa02015-11-02 13:00:03 -0800867 float xdpi = hwConfig->getDpiX();
868 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700869
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870 info.w = hwConfig->getWidth();
871 info.h = hwConfig->getHeight();
872 // Default display viewport to display width and height
873 info.viewportW = info.w;
874 info.viewportH = info.h;
875
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800876 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 // The density of the device is provided by a build property
878 float density = Density::getBuildDensity() / 160.0f;
879 if (density == 0) {
880 // the build doesn't provide a density -- this is wrong!
881 // use xdpi instead
882 ALOGE("ro.sf.lcd_density must be defined as a build property");
883 density = xdpi / 160.0f;
884 }
885 if (Density::getEmuDensity()) {
886 // if "qemu.sf.lcd_density" is specified, it overrides everything
887 xdpi = ydpi = density = Density::getEmuDensity();
888 density /= 160.0f;
889 }
890 info.density = density;
891
892 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700893 const auto display = getDefaultDisplayDeviceLocked();
894 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700895
896 // This is for screenrecord
897 const Rect viewport = display->getViewport();
898 if (viewport.isValid()) {
899 info.viewportW = uint32_t(viewport.getWidth());
900 info.viewportH = uint32_t(viewport.getHeight());
901 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700902 } else {
903 // TODO: where should this value come from?
904 static const int TV_DENSITY = 213;
905 info.density = TV_DENSITY / 160.0f;
906 info.orientation = 0;
907 }
908
Dan Stoza7f7da322014-05-02 15:26:25 -0700909 info.xdpi = xdpi;
910 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800912 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913
Andy McFadden91b2ca82014-06-13 14:04:23 -0700914 // This is how far in advance a buffer must be queued for
915 // presentation at a given time. If you want a buffer to appear
916 // on the screen at time N, you must submit the buffer before
917 // (N - presentationDeadline).
918 //
919 // Normally it's one full refresh period (to give SF a chance to
920 // latch the buffer), but this can be reduced by configuring a
921 // DispSync offset. Any additional delays introduced by the hardware
922 // composer or panel must be accounted for here.
923 //
924 // We add an additional 1ms to allow for processing time and
925 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800926 info.presentationDeadline =
927 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700928
929 // All non-virtual displays are currently considered secure.
930 info.secure = true;
931
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800932 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700933 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800934 std::swap(info.w, info.h);
935 }
936
Michael Wright28f24d02016-07-12 13:30:53 -0700937 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700938 }
939
Dan Stoza7f7da322014-05-02 15:26:25 -0700940 return NO_ERROR;
941}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
944 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700945 return BAD_VALUE;
946 }
947
Ana Krulece588e312018-09-18 12:32:24 -0700948 if (mUseScheduler) {
949 mScheduler->getDisplayStatInfo(stats);
950 } else {
951 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
952 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
953 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700954 return NO_ERROR;
955}
956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
958 const auto display = getDisplayDevice(displayToken);
959 if (!display) {
960 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800961 return BAD_VALUE;
962 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700963
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700965}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700966
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800967void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
968 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800969
Ana Krulec7d1d6832018-12-27 11:10:09 -0800970 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800971 // Lock is acquired by setRefreshRateTo.
972 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800973 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
974 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
975 return;
976 }
977
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 // Lock is acquired by setRefreshRateTo.
979 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800980 if (!display) {
981 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
982 displayToken.get());
983 return;
984 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700985 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800986 ALOGW("Attempt to set active config %d for virtual display", mode);
987 return;
988 }
989 int currentDisplayPowerMode = display->getPowerMode();
990 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
991 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700992 return;
993 }
994
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995 // Don't check against the current mode yet. Worst case we set the desired
996 // config twice.
997 {
998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
1000 }
1001 // This will trigger HWC refresh without resetting the idle timer.
1002 repaintEverythingForHWC();
1003}
1004
1005status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1006 ATRACE_CALL();
1007 postMessageSync(new LambdaMessage(
1008 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1009 return NO_ERROR;
1010}
1011
1012void SurfaceFlinger::setActiveConfigInHWC() {
1013 ATRACE_CALL();
1014
1015 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1016 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001017 return;
1018 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001019 const auto displayId = display->getId();
1020 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1023 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1024 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1025 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1026}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001027
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028void SurfaceFlinger::setActiveConfigInternal() {
1029 ATRACE_CALL();
1030
1031 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1032 if (mUseScheduler) {
1033 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1034 }
1035
1036 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1037 display->setActiveConfig(mUpcomingActiveConfig.configId);
1038
1039 mSetActiveConfigState = SetActiveConfigState::NONE;
1040 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1041
Dominik Laskowski83b88212018-12-11 13:34:06 -08001042 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1044}
1045
1046bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1047 // Store the local variable to release the lock.
1048 ActiveConfigInfo desiredActiveConfig;
1049 {
1050 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1051 desiredActiveConfig = mDesiredActiveConfig;
1052 }
1053
1054 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1055 if (display) {
1056 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1057 display->getActiveConfig() != desiredActiveConfig.configId) {
1058 // Step 1) Desired active config was set, it is different than the
1059 // config currently in use. Notify HWC.
1060 mUpcomingActiveConfig = desiredActiveConfig;
1061 setActiveConfigInHWC();
1062 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1063 // Step 2) HWC was notified and we received refresh from it.
1064 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1065 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1066 repaintEverythingForHWC();
1067 // We do not want to give another frame to HWC while we are transitioning.
1068 return false;
1069 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1070 !(mPreviousPresentFence != Fence::NO_FENCE &&
1071 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1072 // Step 3) We received the present fence from the HWC, so we assume it
1073 // successfully updated the config, hence we update SF.
1074 setActiveConfigInternal();
1075 // If the config changed again while we were transitioning, restart the
1076 // process.
1077 if (desiredActiveConfig != mUpcomingActiveConfig) {
1078 mUpcomingActiveConfig = desiredActiveConfig;
1079 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1080 }
1081 }
1082 }
1083 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001084}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1087 Vector<ColorMode>* outColorModes) {
1088 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001089 return BAD_VALUE;
1090 }
1091
Peiyong Lina52f0292018-03-14 17:26:31 -07001092 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001093 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001094 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1095
1096 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1097 if (!displayId) {
1098 return NAME_NOT_FOUND;
1099 }
1100
Dominik Laskowski075d3172018-05-24 15:50:06 -07001101 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001102 }
Michael Wright28f24d02016-07-12 13:30:53 -07001103 outColorModes->clear();
1104 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1105
1106 return NO_ERROR;
1107}
1108
Daniel Solomon42d04562019-01-20 21:03:19 -08001109status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1110 ui::DisplayPrimaries &primaries) {
1111 if (!displayToken) {
1112 return BAD_VALUE;
1113 }
1114
1115 // Currently we only support this API for a single internal display.
1116 if (getInternalDisplayToken() != displayToken) {
1117 return BAD_VALUE;
1118 }
1119
1120 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1121 return NO_ERROR;
1122}
1123
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1125 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001126 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001127 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001128 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001129}
1130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001132 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133 Vector<ColorMode> modes;
1134 getDisplayColorModes(displayToken, &modes);
1135 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1136 if (mode < ColorMode::NATIVE || !exists) {
1137 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1138 decodeColorMode(mode).c_str(), mode, displayToken.get());
1139 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001140 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001141 const auto display = getDisplayDevice(displayToken);
1142 if (!display) {
1143 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1144 decodeColorMode(mode).c_str(), mode, displayToken.get());
1145 } else if (display->isVirtual()) {
1146 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1147 decodeColorMode(mode).c_str(), mode);
1148 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001149 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1150 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001151 }
1152 }));
1153
Michael Wright28f24d02016-07-12 13:30:53 -07001154 return NO_ERROR;
1155}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001156
Svetoslavd85084b2014-03-20 10:28:31 -07001157status_t SurfaceFlinger::clearAnimationFrameStats() {
1158 Mutex::Autolock _l(mStateLock);
1159 mAnimFrameTracker.clearStats();
1160 return NO_ERROR;
1161}
1162
1163status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1164 Mutex::Autolock _l(mStateLock);
1165 mAnimFrameTracker.getStats(outStats);
1166 return NO_ERROR;
1167}
1168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1170 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001171 Mutex::Autolock _l(mStateLock);
1172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173 const auto display = getDisplayDeviceLocked(displayToken);
1174 if (!display) {
1175 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001176 return BAD_VALUE;
1177 }
1178
Peiyong Linfb069302018-04-25 14:34:31 -07001179 // At this point the DisplayDeivce should already be set up,
1180 // meaning the luminance information is already queried from
1181 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001182 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001183 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1184 capabilities.getDesiredMaxLuminance(),
1185 capabilities.getDesiredMaxAverageLuminance(),
1186 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001187
1188 return NO_ERROR;
1189}
1190
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001191status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1192 ui::PixelFormat* outFormat,
1193 ui::Dataspace* outDataspace,
1194 uint8_t* outComponentMask) const {
1195 if (!outFormat || !outDataspace || !outComponentMask) {
1196 return BAD_VALUE;
1197 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001198 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001199 if (!display || !display->getId()) {
1200 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1201 return BAD_VALUE;
1202 }
1203 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1204 outDataspace, outComponentMask);
1205}
1206
Kevin DuBois74e53772018-11-19 10:52:38 -08001207status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1208 bool enable, uint8_t componentMask,
1209 uint64_t maxFrames) const {
1210 const auto display = getDisplayDevice(displayToken);
1211 if (!display || !display->getId()) {
1212 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1213 return BAD_VALUE;
1214 }
1215
1216 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1217 componentMask, maxFrames);
1218}
1219
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001220status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1221 uint64_t maxFrames, uint64_t timestamp,
1222 DisplayedFrameStats* outStats) const {
1223 const auto display = getDisplayDevice(displayToken);
1224 if (!display || !display->getId()) {
1225 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1226 return BAD_VALUE;
1227 }
1228
1229 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1230 outStats);
1231}
1232
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001233status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1234 if (!outSupported) {
1235 return BAD_VALUE;
1236 }
1237 *outSupported = getRenderEngine().supportsProtectedContent();
1238 return NO_ERROR;
1239}
1240
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001241status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1242 bool* outIsWideColorDisplay) const {
1243 if (!displayToken || !outIsWideColorDisplay) {
1244 return BAD_VALUE;
1245 }
1246 Mutex::Autolock _l(mStateLock);
1247 const auto display = getDisplayDeviceLocked(displayToken);
1248 if (!display) {
1249 return BAD_VALUE;
1250 }
1251 *outIsWideColorDisplay = display->hasWideColorGamut();
1252 return NO_ERROR;
1253}
1254
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001255status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001256 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258
Chia-I Wu90f669f2017-10-05 14:24:41 -07001259 if (mInjectVSyncs == enable) {
1260 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001261 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001262
Dominik Laskowski83b88212018-12-11 13:34:06 -08001263 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001264
Ana Krulec98b5b242018-08-10 15:03:23 -07001265 // TODO(akrulec): Part of the Injector should be refactored, so that it
1266 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001267 if (enable) {
1268 ALOGV("VSync Injections enabled");
1269 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001270 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001271 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001272 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001273 impl::EventThread::InterceptVSyncsCallback(),
1274 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001276 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277 } else {
1278 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001279 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001280 }
1281
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001282 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001283 }));
1284
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001285 return NO_ERROR;
1286}
1287
1288status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001289 Mutex::Autolock _l(mStateLock);
1290
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001291 if (!mInjectVSyncs) {
1292 ALOGE("VSync Injections not enabled");
1293 return BAD_VALUE;
1294 }
1295 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1296 ALOGV("Injecting VSync inside SurfaceFlinger");
1297 mVSyncInjector->onInjectSyncEvent(when);
1298 }
1299 return NO_ERROR;
1300}
1301
Lloyd Pique755e3192018-01-31 16:46:15 -08001302status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1303 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001304 // Try to acquire a lock for 1s, fail gracefully
1305 const status_t err = mStateLock.timedLock(s2ns(1));
1306 const bool locked = (err == NO_ERROR);
1307 if (!locked) {
1308 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1309 return TIMED_OUT;
1310 }
1311
1312 outLayers->clear();
1313 mCurrentState.traverseInZOrder([&](Layer* layer) {
1314 outLayers->push_back(layer->getLayerDebugInfo());
1315 });
1316
1317 mStateLock.unlock();
1318 return NO_ERROR;
1319}
1320
Peiyong Linc6780972018-10-28 15:24:08 -07001321status_t SurfaceFlinger::getCompositionPreference(
1322 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1323 Dataspace* outWideColorGamutDataspace,
1324 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001325 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001326 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001327 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001328 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001329 return NO_ERROR;
1330}
1331
Dan Stoza84ab9372018-12-17 15:27:57 -08001332status_t SurfaceFlinger::addRegionSamplingListener(
1333 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1334 const sp<IRegionSamplingListener>& /*listener*/) {
1335 return NO_ERROR;
1336}
1337
1338status_t SurfaceFlinger::removeRegionSamplingListener(
1339 const sp<IRegionSamplingListener>& /*listener*/) {
1340 return NO_ERROR;
1341}
1342
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001343// ----------------------------------------------------------------------------
1344
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001345sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1346 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001347 auto resyncCallback = makeResyncCallback([this] {
1348 Mutex::Autolock lock(mStateLock);
1349 return getVsyncPeriod();
1350 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001351
Ana Krulec98b5b242018-08-10 15:03:23 -07001352 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001353 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1354 : mAppConnectionHandle;
1355
Ady Abrahama1a49af2019-02-07 14:36:55 -08001356 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001357 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001358 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001359 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001360 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001361 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001362 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001363 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001364}
1365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001366// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367
1368void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001369 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001370}
1371
1372void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001373 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001374}
1375
1376void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001377 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001378}
1379
1380void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001381 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001382 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001383}
1384
1385status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001386 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001387 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001388}
1389
1390status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001391 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001392 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001393 if (res == NO_ERROR) {
1394 msg->wait();
1395 }
1396 return res;
1397}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001398
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001399void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001400 do {
1401 waitForEvent();
1402 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001403}
1404
Dominik Laskowski83b88212018-12-11 13:34:06 -08001405nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001406 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001407 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1408 return 0;
1409 }
1410
1411 const auto config = getHwComposer().getActiveConfig(*displayId);
1412 return config ? config->getVsyncPeriod() : 0;
1413}
1414
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001415void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001416 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001417 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001418 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001419 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001420 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001421 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001422 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001423}
1424
Dominik Laskowski83b88212018-12-11 13:34:06 -08001425void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001426 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001427 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1428 if (mUseScheduler) {
1429 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001430 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001431 } else if (!mScheduler->getHWSyncAvailable()) {
1432 // Hardware vsync is not currently available, so abort the resync
1433 // attempt for now
1434 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001435 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001436 } else {
1437 if (makeAvailable) {
1438 mHWVsyncAvailable = true;
1439 } else if (!mHWVsyncAvailable) {
1440 // Hardware vsync is not currently available, so abort the resync
1441 // attempt for now
1442 return;
1443 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001444 }
1445
Dominik Laskowski83b88212018-12-11 13:34:06 -08001446 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001447 return;
1448 }
1449
Ana Krulece588e312018-09-18 12:32:24 -07001450 if (mUseScheduler) {
1451 mScheduler->setVsyncPeriod(period);
1452 } else {
1453 mPrimaryDispSync->reset();
1454 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001455
Ana Krulece588e312018-09-18 12:32:24 -07001456 if (!mPrimaryHWVsyncEnabled) {
1457 mPrimaryDispSync->beginResync();
1458 mEventControlThread->setVsyncEnabled(true);
1459 mPrimaryHWVsyncEnabled = true;
1460 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001461 }
1462}
1463
Jesse Hall948fe0c2013-10-14 12:56:09 -07001464void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001465 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001466 Mutex::Autolock _l(mHWVsyncLock);
1467 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001468 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001469 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001470 mPrimaryHWVsyncEnabled = false;
1471 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001472 if (makeUnavailable) {
1473 mHWVsyncAvailable = false;
1474 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001475}
1476
Dominik Laskowski83b88212018-12-11 13:34:06 -08001477void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001478 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001479
Dan Stoza57164302017-05-08 14:03:54 -07001480 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001481 const nsecs_t last = lastResyncTime.exchange(now);
1482
1483 if (now - last > kIgnoreDelay) {
1484 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001485 }
1486}
1487
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001488void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1489 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001490 ATRACE_NAME("SF onVsync");
1491
Steven Thomas3cfac282017-02-06 12:29:30 -08001492 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001494 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001495 return;
1496 }
1497
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001499 return;
1500 }
1501
Dominik Laskowski075d3172018-05-24 15:50:06 -07001502 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001503 // For now, we don't do anything with external display vsyncs.
1504 return;
1505 }
1506
Ana Krulece588e312018-09-18 12:32:24 -07001507 if (mUseScheduler) {
1508 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001509 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001510 bool needsHwVsync = false;
1511 { // Scope for the lock
1512 Mutex::Autolock _l(mHWVsyncLock);
1513 if (mPrimaryHWVsyncEnabled) {
1514 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1515 }
1516 }
1517
1518 if (needsHwVsync) {
1519 enableHardwareVsync();
1520 } else {
1521 disableHardwareVsync(false);
1522 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001523 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001524}
1525
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001526void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001527 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1528 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001529}
1530
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001531void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1532 mPhaseOffsets->setRefreshRateType(refreshRate);
1533
1534 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1535 mVsyncModulator.setPhaseOffsets(early, gl, late);
1536
1537 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001538 return;
1539 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001540
Ana Krulec7d1d6832018-12-27 11:10:09 -08001541 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1542 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1543 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1544 // refresh cycle.
1545
1546 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001547 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001548 if (currentVsyncPeriod == 0) {
1549 return;
1550 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001551
Ana Krulec7d1d6832018-12-27 11:10:09 -08001552 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1553 // floating numbers.
1554 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001555 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1556 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001557 if (std::abs(currentFps - newFps) <= 1) {
1558 return;
1559 }
1560
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001561 const auto displayId = getInternalDisplayIdLocked();
1562 LOG_ALWAYS_FATAL_IF(!displayId);
1563
1564 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001565 for (int i = 0; i < configs.size(); i++) {
1566 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1567 if (vsyncPeriod == 0) {
1568 continue;
1569 }
1570 const float fps = 1e9 / vsyncPeriod;
1571 // TODO(b/113612090): There should be a better way at determining which config
1572 // has the right refresh rate.
1573 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001574 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001575 }
1576 }
1577}
1578
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001579void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001580 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001581 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001582 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001583
Lloyd Piqueba04e622017-12-14 17:11:26 -08001584 // Ignore events that do not have the right sequenceId.
1585 if (sequenceId != getBE().mComposerSequenceId) {
1586 return;
1587 }
1588
Steven Thomasb02664d2017-07-26 18:48:28 -07001589 // Only lock if we're not on the main thread. This function is normally
1590 // called on a hwbinder thread, but for the primary display it's called on
1591 // the main thread with the state lock already held, so don't attempt to
1592 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001593 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001594
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001595 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001596
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001597 if (std::this_thread::get_id() == mMainThreadId) {
1598 // Process all pending hot plug events immediately if we are on the main thread.
1599 processDisplayHotplugEventsLocked();
1600 }
1601
Lloyd Piqueba04e622017-12-14 17:11:26 -08001602 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001603}
1604
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001605void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001606 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001607 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001608 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001609 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001610 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001611}
1612
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001613void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001614 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001616 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001617 getHwComposer().setVsyncEnabled(*displayId,
1618 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1619 }
Mathias Agopian86303202012-07-24 22:46:10 -07001620}
1621
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001623void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001624 if (mUseScheduler) {
1625 mScheduler->disableHardwareVsync(true);
1626 } else {
1627 disableHardwareVsync(true);
1628 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001629 // Clear the drawing state so that the logic inside of
1630 // handleTransactionLocked will fire. It will determine the delta between
1631 // mCurrentState and mDrawingState and re-apply all changes when we make the
1632 // transition.
1633 mDrawingState.displays.clear();
1634 mDisplays.clear();
1635}
1636
Steven Thomas050b2c82017-03-06 11:45:16 -08001637void SurfaceFlinger::updateVrFlinger() {
1638 if (!mVrFlinger)
1639 return;
1640 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001641 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001642 return;
1643 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001644
Lloyd Pique441d5042018-10-18 16:49:51 -07001645 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001646 ALOGE("Vr flinger is only supported for remote hardware composer"
1647 " service connections. Ignoring request to transition to vr"
1648 " flinger.");
1649 mVrFlingerRequestsDisplay = false;
1650 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001651 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001652
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001653 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001654
Steven Thomas0123ac62018-07-12 11:32:34 -07001655 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001656 LOG_ALWAYS_FATAL_IF(!display);
1657 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001658 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1659 // called below. Clear the reference now so we don't accidentally use it
1660 // later.
1661 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001662
Steven Thomasb02664d2017-07-26 18:48:28 -07001663 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001665 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001666
Steven Thomasb02664d2017-07-26 18:48:28 -07001667 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001668 // Delete the current instance before creating the new one
1669 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1670 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1671 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1672 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001673
Lloyd Pique441d5042018-10-18 16:49:51 -07001674 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001675 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001676
1677 if (vrFlingerRequestsDisplay) {
1678 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001679 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001680
1681 mVisibleRegionsDirty = true;
1682 invalidateHwcGeometry();
1683
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001684 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001685 display = getDefaultDisplayDeviceLocked();
1686 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001687 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001688
Steven Thomasb02664d2017-07-26 18:48:28 -07001689 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001690 const nsecs_t vsyncPeriod = getVsyncPeriod();
1691 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001692
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001693 // The present fences returned from vr_hwc are not an accurate
1694 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001695 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001696 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1697 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001698 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001699 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001700 !hasSyncFramework);
1701 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001702
Steven Thomasb02664d2017-07-26 18:48:28 -07001703 // Use phase of 0 since phase is not known.
1704 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001705 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001706 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001707
Dominik Laskowski83b88212018-12-11 13:34:06 -08001708 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001709
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001710 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001711 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001712}
1713
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001715 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001716 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001717 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001718 if (!updateSetActiveConfigStateMachine()) {
1719 break;
1720 }
1721
Ana Krulec3084c052018-11-21 20:27:17 +01001722 if (mUseScheduler) {
1723 // This call is made each time SF wakes up and creates a new frame.
1724 mScheduler->incrementFrameCounter();
1725 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001726 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1727 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001728 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001729 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001730 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001731 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001732 if (mPropagateBackpressure) {
1733 signalLayerUpdate();
1734 break;
1735 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001736 }
Dan Stoza50182882016-07-08 12:02:20 -07001737
Steven Thomas050b2c82017-03-06 11:45:16 -08001738 // Now that we're going to make it to the handleMessageTransaction()
1739 // call below it's safe to call updateVrFlinger(), which will
1740 // potentially trigger a display handoff.
1741 updateVrFlinger();
1742
Dan Stoza6b9454d2014-11-07 16:00:59 -08001743 bool refreshNeeded = handleMessageTransaction();
1744 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001745
1746 updateCursorAsync();
1747 updateInputFlinger();
1748
Dan Stoza58784442014-12-02 16:58:17 -08001749 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001750 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001751 // Signal a refresh if a transaction modified the window state,
1752 // a new buffer was latched, or if HWC has requested a full
1753 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001754 signalRefresh();
1755 }
1756 break;
1757 }
1758 case MessageQueue::REFRESH: {
1759 handleMessageRefresh();
1760 break;
1761 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001762 }
1763}
1764
Dan Stoza6b9454d2014-11-07 16:00:59 -08001765bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001766 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001767
1768 // Apply any ready transactions in the queues if there are still transactions that have not been
1769 // applied, wake up during the next vsync period and check again
1770 bool transactionNeeded = false;
1771 if (!flushTransactionQueues()) {
1772 transactionNeeded = true;
1773 }
1774
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001776 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001777 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001778
1779 if (transactionNeeded) {
1780 setTransactionFlags(eTransactionNeeded);
1781 }
1782
1783 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001784}
1785
Mathias Agopian4fec8732012-06-29 14:12:52 -07001786void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001787 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001788
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001789 mRefreshPending = false;
1790
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001791 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001792 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001793 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001794 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001795 for (const auto& [token, display] : mDisplays) {
1796 beginFrame(display);
1797 prepareFrame(display);
1798 doDebugFlashRegions(display, repaintEverything);
1799 doComposition(display, repaintEverything);
1800 }
1801
Adrian Roos1e1a1282017-11-01 19:05:31 +01001802 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001803 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001804
1805 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001806 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001807
Dan Stozabfbffeb2016-07-21 14:49:33 -07001808 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809 for (const auto& [token, displayDevice] : mDisplays) {
1810 auto display = displayDevice->getCompositionDisplay();
1811 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001812 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001813 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001814 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001815
Alec Mouri86770e52018-09-24 22:40:58 +00001816 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001817 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001818 if (mHadClientComposition) {
1819 base::unique_fd flushFence(getRenderEngine().flush());
1820 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1821 getBE().flushFence = new Fence(std::move(flushFence));
1822 } else {
1823 // Cleanup for hygiene.
1824 getBE().flushFence = Fence::NO_FENCE;
1825 }
1826 }
1827
Jorim Jaggi90535212018-05-23 23:44:06 +02001828 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001829
David Sodman7e4ae112018-02-09 15:02:28 -08001830 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001831
1832 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001834
David Sodmanfa9b2af2017-12-24 13:28:59 -08001835
1836bool SurfaceFlinger::handleMessageInvalidate() {
1837 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001838 bool refreshNeeded = handlePageFlip();
1839
Vishnu Nair4351ad52019-02-11 14:13:02 -08001840 if (mVisibleRegionsDirty) {
1841 computeLayerBounds();
1842 }
1843
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001844 for (auto& layer : mLayersPendingRefresh) {
1845 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001846 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001847 invalidateLayerStack(layer, visibleReg);
1848 }
1849 mLayersPendingRefresh.clear();
1850 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001851}
1852
David Sodman79bba0e2018-08-05 18:07:49 -07001853void SurfaceFlinger::calculateWorkingSet() {
1854 ATRACE_CALL();
1855 ALOGV(__FUNCTION__);
1856
David Sodman79bba0e2018-08-05 18:07:49 -07001857 // build the h/w work list
1858 if (CC_UNLIKELY(mGeometryInvalid)) {
1859 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001860 for (const auto& [token, displayDevice] : mDisplays) {
1861 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001862 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001863 if (!displayId) {
1864 continue;
1865 }
David Sodman79bba0e2018-08-05 18:07:49 -07001866
Lloyd Pique32cbe282018-10-19 13:09:22 -07001867 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001868 for (size_t i = 0; i < currentLayers.size(); i++) {
1869 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001870
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001871 if (!layer->hasHwcLayer(displayDevice)) {
1872 if (!layer->createHwcLayer(&getHwComposer(), displayDevice)) {
1873 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001874 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001875 }
1876 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001877
Lloyd Pique32cbe282018-10-19 13:09:22 -07001878 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001879 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001880 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001881 }
David Sodman79bba0e2018-08-05 18:07:49 -07001882 }
1883 }
1884 }
1885
1886 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001887 for (const auto& [token, displayDevice] : mDisplays) {
1888 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001889 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001890 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001891 continue;
1892 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001893 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001894
1895 if (mDrawingState.colorMatrixChanged) {
1896 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001897 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001898 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001899 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001900 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001901 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1902 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001903 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001904 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001905 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1906 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001907 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001908 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001909 }
1910
Peiyong Lind3788632018-09-18 16:01:31 -07001911 // TODO(b/111562338) remove when composer 2.3 is shipped.
1912 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001913 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001914 }
1915
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001916 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001917 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001918 }
1919
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001920 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001921 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001922 layer->setCompositionType(displayDevice,
1923 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001924 continue;
1925 }
1926
Lloyd Pique32cbe282018-10-19 13:09:22 -07001927 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001928 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001929 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001930 }
1931
Peiyong Lin13effd12018-07-24 17:01:47 -07001932 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001933 ColorMode colorMode;
1934 Dataspace dataSpace;
1935 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001936 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001937 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001938 }
1939 }
1940
1941 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001942
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001943 for (const auto& [token, displayDevice] : mDisplays) {
1944 auto display = displayDevice->getCompositionDisplay();
1945 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001946 const auto displayId = display->getId();
Lloyd Pique0b785d82018-12-04 17:25:27 -08001947 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1948 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1949 layer->getCompositionType(displayDevice));
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001950 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001951 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001952 }
1953 }
David Sodman79bba0e2018-08-05 18:07:49 -07001954}
1955
Lloyd Pique32cbe282018-10-19 13:09:22 -07001956void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1957 bool repaintEverything) {
1958 auto display = displayDevice->getCompositionDisplay();
1959 const auto& displayState = display->getState();
1960
Mathias Agopiancd60f992012-08-16 16:28:27 -07001961 // is debugging enabled
1962 if (CC_LIKELY(!mDebugRegion))
1963 return;
1964
Lloyd Pique32cbe282018-10-19 13:09:22 -07001965 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001966 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001967 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001968 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001969 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001970 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001971 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001972
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001973 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974 }
1975 }
1976
Lloyd Pique32cbe282018-10-19 13:09:22 -07001977 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978
1979 if (mDebugRegion > 1) {
1980 usleep(mDebugRegion * 1000);
1981 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001982
Lloyd Pique32cbe282018-10-19 13:09:22 -07001983 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001984}
1985
Adrian Roos1e1a1282017-11-01 19:05:31 +01001986void SurfaceFlinger::doTracing(const char* where) {
1987 ATRACE_CALL();
1988 ATRACE_NAME(where);
1989 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001990 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001991 }
1992}
1993
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001994void SurfaceFlinger::logLayerStats() {
1995 ATRACE_CALL();
1996 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001997 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001998 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001999 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002000 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002001 }
2002 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002003
2004 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002005 }
2006}
2007
David Sodman2b406362017-12-15 13:33:47 -08002008void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ATRACE_CALL();
2011 ALOGV("preComposition");
2012
David Sodman2b406362017-12-15 13:33:47 -08002013 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002016 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002017 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018 needExtraInvalidate = true;
2019 }
Robert Carr2047fae2016-11-28 14:09:09 -08002020 });
2021
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 if (needExtraInvalidate) {
2023 signalLayerUpdate();
2024 }
2025}
2026
Ana Krulece588e312018-09-18 12:32:24 -07002027void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2028 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002029 // Update queue of past composite+present times and determine the
2030 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002031 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002033 while (!getBE().mCompositePresentTimes.empty()) {
2034 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002035 // Cached values should have been updated before calling this method,
2036 // which helps avoid duplicate syscalls.
2037 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2038 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2039 break;
2040 }
2041 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002042 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043 }
2044
2045 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002046 while (getBE().mCompositePresentTimes.size() > 16) {
2047 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 }
2049
Ana Krulece588e312018-09-18 12:32:24 -07002050 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002051}
2052
Ana Krulece588e312018-09-18 12:32:24 -07002053void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2054 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055 // Integer division and modulo round toward 0 not -inf, so we need to
2056 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002057 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2058 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2059 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002060
Ana Krulec757f63a2019-01-25 10:46:18 -08002061 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002062 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002063 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002064 }
2065
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066 // Snap the latency to a value that removes scheduling jitter from the
2067 // composition and present times, which often have >1ms of jitter.
2068 // Reducing jitter is important if an app attempts to extrapolate
2069 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002070 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002071 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002072 nsecs_t bias = stats.vsyncPeriod / 2;
2073 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2074 nsecs_t snappedCompositeToPresentLatency =
2075 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076
David Sodman99974d22017-11-28 12:04:33 -08002077 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002078 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2079 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002080 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081}
2082
Ady Abraham8164d482019-01-11 14:47:59 -08002083// debug patch for b/119477596 - add stack guards to catch stack
2084// corruptions and disable clang optimizations.
2085// The code below is temporary and planned to be removed once stack
2086// corruptions are found.
2087#pragma clang optimize off
2088class StackGuard {
2089public:
2090 StackGuard(const char* name, const char* func, int line) {
2091 guarders.reserve(MIN_CAPACITY);
2092 guarders.push_back({this, name, func, line});
2093 validate();
2094 }
2095 ~StackGuard() {
2096 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2097 if (i->guard == this) {
2098 guarders.erase(i);
2099 break;
2100 }
2101 }
2102 }
2103
2104 static void validate() {
2105 for (const auto& guard : guarders) {
2106 if (guard.guard->cookie != COOKIE_VALUE) {
2107 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2108 CallStack stack(LOG_TAG);
2109 abort();
2110 }
2111 }
2112 }
2113
2114private:
2115 uint64_t cookie = COOKIE_VALUE;
2116 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2117 static constexpr size_t MIN_CAPACITY = 16;
2118
2119 struct GuarderElement {
2120 StackGuard* guard;
2121 const char* name;
2122 const char* func;
2123 int line;
2124 };
2125
2126 static std::vector<GuarderElement> guarders;
2127};
2128std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2129
2130#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2131
2132#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002133void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002134{
Ady Abraham8164d482019-01-11 14:47:59 -08002135 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 ATRACE_CALL();
2137 ALOGV("postComposition");
2138
Brian Anderson3546a3f2016-07-14 11:51:14 -07002139 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002140 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002141 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002142 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002143 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002144 }
Ady Abraham8164d482019-01-11 14:47:59 -08002145 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002146
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002147 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002148 const auto displayDevice = getDefaultDisplayDeviceLocked();
2149 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002150
David Sodman73beded2017-11-15 11:56:06 -08002151 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002152 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002153 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2154
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002157 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2158 ->getRenderSurface()
2159 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002160 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002161 } else {
2162 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2163 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002164
Ady Abraham8164d482019-01-11 14:47:59 -08002165 ASSERT_ON_STACK_GUARD();
2166
David Sodman73beded2017-11-15 11:56:06 -08002167 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002168 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2169 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002170 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002171 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002172 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002173
Ana Krulece588e312018-09-18 12:32:24 -07002174 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002175 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002176 if (mUseScheduler) {
2177 mScheduler->getDisplayStatInfo(&stats);
2178 } else {
2179 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2180 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2181 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002182
Ady Abraham8164d482019-01-11 14:47:59 -08002183 ASSERT_ON_STACK_GUARD();
2184
David Sodman2b406362017-12-15 13:33:47 -08002185 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186 // when we started doing work for this frame, but that should be okay
2187 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002188 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002189 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002190 DEFINE_STACK_GUARD(compositorTiming);
2191
Brian Andersond0010582017-03-07 13:20:31 -08002192 {
David Sodman99974d22017-11-28 12:04:33 -08002193 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002194 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002195 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002196
2197 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002198 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002199
Robert Carr2047fae2016-11-28 14:09:09 -08002200 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002201 bool frameLatched =
2202 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2203 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002204 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002205 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002206 recordBufferingStats(layer->getName().string(),
2207 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002208 }
Ady Abraham8164d482019-01-11 14:47:59 -08002209 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002210 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002211
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002212 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002213 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002214 if (mUseScheduler) {
2215 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002216 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002217 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002218 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2219 enableHardwareVsync();
2220 } else {
2221 disableHardwareVsync(false);
2222 }
Ady Abraham8164d482019-01-11 14:47:59 -08002223 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002224 }
2225 }
2226
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002227 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002228 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2229 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002230 if (mUseScheduler) {
2231 mScheduler->enableHardwareVsync();
2232 } else {
2233 enableHardwareVsync();
2234 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002235 }
2236 }
2237
Ady Abraham8164d482019-01-11 14:47:59 -08002238 ASSERT_ON_STACK_GUARD();
2239
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002240 if (mAnimCompositionPending) {
2241 mAnimCompositionPending = false;
2242
Brian Anderson4e606e32017-03-16 15:34:57 -07002243 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002244 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002245 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002246
2247 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002248 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002249 // The HWC doesn't support present fences, so use the refresh
2250 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002251 const nsecs_t presentTime =
2252 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002253 DEFINE_STACK_GUARD(presentTime);
2254
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002255 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002256 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002257 }
2258 mAnimFrameTracker.advanceFrame();
2259 }
Dan Stozab90cf072015-03-05 11:05:59 -08002260
Ady Abraham8164d482019-01-11 14:47:59 -08002261 ASSERT_ON_STACK_GUARD();
2262
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002263 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002264 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002265 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002266 }
2267
Ady Abraham8164d482019-01-11 14:47:59 -08002268 ASSERT_ON_STACK_GUARD();
2269
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002270 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002271
Ady Abraham8164d482019-01-11 14:47:59 -08002272 ASSERT_ON_STACK_GUARD();
2273
Lloyd Pique32cbe282018-10-19 13:09:22 -07002274 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2275 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002276 return;
2277 }
2278
2279 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002280 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002281 if (mHasPoweredOff) {
2282 mHasPoweredOff = false;
2283 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002284 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002285 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002286 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002287 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002288 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2289 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002290 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002291 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002292 }
David Sodman4a36e932017-11-07 14:29:47 -08002293 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002294
2295 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002296 }
David Sodman4a36e932017-11-07 14:29:47 -08002297 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002298 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002299
2300 {
2301 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002302 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002303 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002304 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002305 if (refillCount > 0) {
2306 const size_t offset = mTexturePool.size();
2307 mTexturePool.resize(mTexturePoolSize);
2308 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2309 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2310 }
Ady Abraham8164d482019-01-11 14:47:59 -08002311 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002312 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002313
Marissa Wallfda30bb2018-10-12 11:34:28 -07002314 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002315 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002316
2317 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002318}
Ady Abraham8164d482019-01-11 14:47:59 -08002319#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002320
Vishnu Nair4351ad52019-02-11 14:13:02 -08002321void SurfaceFlinger::computeLayerBounds() {
2322 for (const auto& pair : mDisplays) {
2323 const auto& displayDevice = pair.second;
2324 const auto display = displayDevice->getCompositionDisplay();
2325 for (const auto& layer : mDrawingState.layersSortedByZ) {
2326 // only consider the layers on the given layer stack
2327 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002328 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002329 }
2330
2331 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2332 }
2333 }
2334}
2335
Mathias Agopiancd60f992012-08-16 16:28:27 -07002336void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337 ATRACE_CALL();
2338 ALOGV("rebuildLayerStacks");
2339
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002340 // We need to clear these out now as these may be holding on to a
2341 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2342 // also holds a reference. When the set of visible layers is recomputed,
2343 // some layers may be destroyed if the only thing keeping them alive was
2344 // that list of visible layers associated with each display. The layer
2345 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2346 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2347 for (const auto& [token, display] : mDisplays) {
2348 getBE().mCompositionInfo[token].clear();
2349 }
2350
Mathias Agopiancd60f992012-08-16 16:28:27 -07002351 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002352 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002353 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002354 mVisibleRegionsDirty = false;
2355 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002356
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002357 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002358 const auto& displayDevice = pair.second;
2359 auto display = displayDevice->getCompositionDisplay();
2360 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002361 Region opaqueRegion;
2362 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002363 compositionengine::Output::OutputLayers layersSortedByZ;
2364 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002365 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002366 const ui::Transform& tr = displayState.transform;
2367 const Rect bounds = displayState.bounds;
2368 if (displayState.isEnabled) {
2369 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002370
Jeff Sharkey76488112017-02-27 14:15:18 -07002371 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002372 auto compositionLayer = layer->getCompositionLayer();
2373 if (compositionLayer == nullptr) {
2374 return;
2375 }
2376
Chia-I Wu83806892017-11-16 10:50:20 -08002377 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002378 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002379 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2380 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2381
Lloyd Piqueef36b002019-01-23 17:52:04 -08002382 if (display->belongsInOutput(layer->getLayerStack(),
2383 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002384 Region drawRegion(tr.transform(
2385 layer->visibleNonTransparentRegion));
2386 drawRegion.andSelf(bounds);
2387 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002388 layersSortedByZ.emplace_back(
2389 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2390 layerFE));
2391
2392 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002393 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002394 // Clear out the HWC layer if this layer was
2395 // previously visible, but no longer is
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002396 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(displayDevice);
Jeff Sharkey76488112017-02-27 14:15:18 -07002397 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002398 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002399 // WM changes display->layerStack upon sleep/awake.
2400 // Here we make sure we delete the HWC layers even if
2401 // WM changed their layer stack.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002402 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(displayDevice);
Chia-I Wu83806892017-11-16 10:50:20 -08002403 }
2404
2405 // If a layer is not going to get a release fence because
2406 // it is invisible, but it is also going to release its
2407 // old buffer, add it to the list of layers needing
2408 // fences.
2409 if (hwcLayerDestroyed) {
2410 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2411 mLayersWithQueuedFrames.cend(), layer);
2412 if (found != mLayersWithQueuedFrames.cend()) {
2413 layersNeedingFences.add(layer);
2414 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002415 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002416 });
2417 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002418
2419 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2420
2421 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 displayDevice->setLayersNeedingFences(layersNeedingFences);
2423
2424 Region undefinedRegion{bounds};
2425 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2426
2427 display->editState().undefinedRegion = undefinedRegion;
2428 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002429 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002430 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002431}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002432
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002433// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002434// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002435// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002436// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002437// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002438// The returned HDR data space is one of
2439// - Dataspace::UNKNOWN
2440// - Dataspace::BT2020_HLG
2441// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2443 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002444 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002445 *outHdrDataSpace = Dataspace::UNKNOWN;
2446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002448 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002449 case Dataspace::V0_SCRGB:
2450 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002451 case Dataspace::BT2020:
2452 case Dataspace::BT2020_ITU:
2453 case Dataspace::BT2020_LINEAR:
2454 case Dataspace::DISPLAY_BT2020:
2455 bestDataSpace = Dataspace::DISPLAY_BT2020;
2456 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002457 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002458 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002459 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002460 case Dataspace::BT2020_PQ:
2461 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002462 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002463 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002464 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002465 case Dataspace::BT2020_HLG:
2466 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002467 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002468 // When there's mixed PQ content and HLG content, we set the HDR
2469 // data space to be BT2020_PQ and convert HLG to PQ.
2470 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2471 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002472 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002473 break;
2474 default:
2475 break;
2476 }
Romain Guy54f154a2017-10-24 21:40:32 +01002477 }
2478
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002479 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002480}
2481
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002482// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2484 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002485 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2486 *outMode = ColorMode::NATIVE;
2487 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002488 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002489 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002490 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002491
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002492 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002493 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002494
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002495 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2496
Peiyong Lina3ea5592019-02-10 14:45:00 -08002497 switch (mForceColorMode) {
2498 case ColorMode::SRGB:
2499 bestDataSpace = Dataspace::V0_SRGB;
2500 break;
2501 case ColorMode::DISPLAY_P3:
2502 bestDataSpace = Dataspace::DISPLAY_P3;
2503 break;
2504 default:
2505 break;
2506 }
2507
Peiyong Lindfde5112018-06-05 10:58:41 -07002508 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002509 const bool isHdr =
2510 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002511 if (isHdr) {
2512 bestDataSpace = hdrDataSpace;
2513 }
2514
Chia-I Wu0d711262018-05-21 15:19:35 -07002515 RenderIntent intent;
2516 switch (mDisplayColorSetting) {
2517 case DisplayColorSetting::MANAGED:
2518 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002519 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002520 break;
2521 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002522 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002523 break;
2524 default: // vendor display color setting
2525 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2526 break;
2527 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002528
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002529 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002530}
2531
Lloyd Pique32cbe282018-10-19 13:09:22 -07002532void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2533 auto display = displayDevice->getCompositionDisplay();
2534 const auto& displayState = display->getState();
2535
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002536 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002537 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2538 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002539
David Sodmanfa9b2af2017-12-24 13:28:59 -08002540 // If nothing has changed (!dirty), don't recompose.
2541 // If something changed, but we don't currently have any visible layers,
2542 // and didn't when we last did a composition, then skip it this time.
2543 // The second rule does two things:
2544 // - When all layers are removed from a display, we'll emit one black
2545 // frame, then nothing more until we get new layers.
2546 // - When a display is created with a private layer stack, we won't
2547 // emit any black frames until a layer is added to the layer stack.
2548 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002549
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 const char flagPrefix[] = {'-', '+'};
2551 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002552 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2553 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2554 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2555 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002556
Lloyd Pique31cb2942018-10-19 17:23:03 -07002557 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002558
David Sodmanfa9b2af2017-12-24 13:28:59 -08002559 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002560 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002561 }
2562}
2563
Lloyd Pique32cbe282018-10-19 13:09:22 -07002564void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2565 auto display = displayDevice->getCompositionDisplay();
2566 const auto& displayState = display->getState();
2567
2568 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002569 return;
David Sodman2b406362017-12-15 13:33:47 -08002570 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002571
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002572 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002573 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002574 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002575}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002576
Lloyd Pique32cbe282018-10-19 13:09:22 -07002577void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002578 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 ALOGV("doComposition");
2580
Lloyd Pique32cbe282018-10-19 13:09:22 -07002581 auto display = displayDevice->getCompositionDisplay();
2582 const auto& displayState = display->getState();
2583
2584 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002585 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002586 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002587
David Sodmanfa9b2af2017-12-24 13:28:59 -08002588 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002589 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002590
Lloyd Pique32cbe282018-10-19 13:09:22 -07002591 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002592 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002593 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002594 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002595}
2596
David Sodmanfa9b2af2017-12-24 13:28:59 -08002597void SurfaceFlinger::postFrame()
2598{
2599 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002600 const auto display = getDefaultDisplayDeviceLocked();
2601 if (display && getHwComposer().isConnected(*display->getId())) {
2602 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002603 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2604 logFrameStats();
2605 }
2606 }
2607}
2608
Lloyd Pique32cbe282018-10-19 13:09:22 -07002609void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002610 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002612
Lloyd Pique32cbe282018-10-19 13:09:22 -07002613 auto display = displayDevice->getCompositionDisplay();
2614 const auto& displayState = display->getState();
2615 const auto displayId = display->getId();
2616
David Sodmanfa9b2af2017-12-24 13:28:59 -08002617 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002618
Lloyd Pique32cbe282018-10-19 13:09:22 -07002619 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002620 if (displayId) {
2621 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002622 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002623 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002624 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002625 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002626
Chia-I Wu7b549592017-11-15 09:14:57 -08002627 // The layer buffer from the previous frame (if any) is released
2628 // by HWC only when the release fence from this frame (if any) is
2629 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002630 if (displayId && layer->hasHwcLayer(displayDevice)) {
2631 releaseFence =
2632 getHwComposer().getLayerReleaseFence(*displayId,
2633 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002634 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002635
2636 // If the layer was client composited in the previous frame, we
2637 // need to merge with the previous client target acquire fence.
2638 // Since we do not track that, always merge with the current
2639 // client target acquire fence when it is available, even though
2640 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002641 if (layer->getCompositionType(displayDevice) ==
2642 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002643 releaseFence =
2644 Fence::merge("LayerRelease", releaseFence,
2645 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002646 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002647
David Sodman15094112018-10-11 09:39:37 -07002648 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 }
Chia-I Wu83806892017-11-16 10:50:20 -08002650
2651 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002653 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002654 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002656 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002657 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002658 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002659 }
2660 }
2661
Dominik Laskowski075d3172018-05-24 15:50:06 -07002662 if (displayId) {
2663 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002664 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666}
2667
Mathias Agopian87baae12012-07-31 12:38:26 -07002668void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669{
Mathias Agopian841cde52012-03-01 15:44:37 -08002670 ATRACE_CALL();
2671
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002672 // here we keep a copy of the drawing state (that is the state that's
2673 // going to be overwritten by handleTransactionLocked()) outside of
2674 // mStateLock so that the side-effects of the State assignment
2675 // don't happen with mStateLock held (which can cause deadlocks).
2676 State drawingState(mDrawingState);
2677
Mathias Agopianca4d3602011-05-19 15:38:14 -07002678 Mutex::Autolock _l(mStateLock);
2679 const nsecs_t now = systemTime();
2680 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681
Mathias Agopianca4d3602011-05-19 15:38:14 -07002682 // Here we're guaranteed that some transaction flags are set
2683 // so we can call handleTransactionLocked() unconditionally.
2684 // We call getTransactionFlags(), which will also clear the flags,
2685 // with mStateLock held to guarantee that mCurrentState won't change
2686 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002687
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002688 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002689 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002690 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002691
Mathias Agopianca4d3602011-05-19 15:38:14 -07002692 mLastTransactionTime = systemTime() - now;
2693 mDebugInTransaction = 0;
2694 invalidateHwcGeometry();
2695 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002696}
2697
Lloyd Piqueba04e622017-12-14 17:11:26 -08002698void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2699 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002700 const std::optional<DisplayIdentificationInfo> info =
2701 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002702
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704 continue;
2705 }
2706
Lloyd Piqueba04e622017-12-14 17:11:26 -08002707 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002708 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002709 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002710 mPhysicalDisplayTokens[info->id] = new BBinder();
2711 DisplayDeviceState state;
2712 state.displayId = info->id;
2713 state.isSecure = true; // All physical displays are currently considered secure.
2714 state.displayName = info->name;
2715 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2716 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002717 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002718 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002719 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002720
Dominik Laskowski075d3172018-05-24 15:50:06 -07002721 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2722 if (index >= 0) {
2723 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2724 mInterceptor->saveDisplayDeletion(state.sequenceId);
2725 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002726 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002727 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002728 }
2729
2730 processDisplayChangesLocked();
2731 }
2732
2733 mPendingHotplugEvents.clear();
2734}
2735
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002736void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002737 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002738 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2739 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002740 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002741 mEventThread->onHotplugReceived(displayId, connected);
2742 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002743 }
2744}
2745
Lloyd Pique99d3da52018-01-22 17:48:03 -08002746sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002747 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002748 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002749 const sp<IGraphicBufferProducer>& producer) {
2750 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002751 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002752 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002753 creationArgs.isSecure = state.isSecure;
2754 creationArgs.displaySurface = dispSurface;
2755 creationArgs.hasWideColorGamut = false;
2756 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002757
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002758 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002759 creationArgs.isPrimary = isInternalDisplay;
2760
2761 if (useColorManagement && displayId) {
2762 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002763 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002764 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002765 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002766 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002767
Dominik Laskowski7e045462018-05-30 13:02:02 -07002768 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002770 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002771 }
tangrobin6753a022018-08-10 10:58:54 +08002772 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002773
Dominik Laskowski075d3172018-05-24 15:50:06 -07002774 if (displayId) {
2775 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002776 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002777 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002778 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002779
Lloyd Pique90c115d2018-09-18 21:39:42 -07002780 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002781 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002782 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002783
Lloyd Pique99d3da52018-01-22 17:48:03 -08002784 // Make sure that composition can never be stalled by a virtual display
2785 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002786 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002787 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002788 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2789 }
2790
Dominik Laskowski075d3172018-05-24 15:50:06 -07002791 creationArgs.displayInstallOrientation =
2792 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002793
Lloyd Pique99d3da52018-01-22 17:48:03 -08002794 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002795 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002796
Lloyd Pique90c115d2018-09-18 21:39:42 -07002797 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002798
2799 if (maxFrameBufferAcquiredBuffers >= 3) {
2800 nativeWindowSurface->preallocateBuffers();
2801 }
2802
2803 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002804 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002805 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002806 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002807 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002808 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002809 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2810 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002811 if (!state.isVirtual()) {
2812 LOG_ALWAYS_FATAL_IF(!displayId);
2813 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002814 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002815
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002816 display->setLayerStack(state.layerStack);
2817 display->setProjection(state.orientation, state.viewport, state.frame);
2818 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002819
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002820 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002821}
2822
Lloyd Pique347200f2017-12-14 17:00:15 -08002823void SurfaceFlinger::processDisplayChangesLocked() {
2824 // here we take advantage of Vector's copy-on-write semantics to
2825 // improve performance by skipping the transaction entirely when
2826 // know that the lists are identical
2827 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2828 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2829 if (!curr.isIdenticalTo(draw)) {
2830 mVisibleRegionsDirty = true;
2831 const size_t cc = curr.size();
2832 size_t dc = draw.size();
2833
2834 // find the displays that were removed
2835 // (ie: in drawing state but not in current state)
2836 // also handle displays that changed
2837 // (ie: displays that are in both lists)
2838 for (size_t i = 0; i < dc;) {
2839 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2840 if (j < 0) {
2841 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002842 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002843 // Save display ID before disconnecting.
2844 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002845 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002846
2847 if (!display->isVirtual()) {
2848 LOG_ALWAYS_FATAL_IF(!displayId);
2849 dispatchDisplayHotplugEvent(displayId->value, false);
2850 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002851 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002852
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002854 } else {
2855 // this display is in both lists. see if something changed.
2856 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002857 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002858 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2859 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2860 if (state_binder != draw_binder) {
2861 // changing the surface is like destroying and
2862 // recreating the DisplayDevice, so we just remove it
2863 // from the drawing state, so that it get re-added
2864 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002866 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002868 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002869 mDrawingState.displays.removeItemsAt(i);
2870 dc--;
2871 // at this point we must loop to the next item
2872 continue;
2873 }
2874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002875 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002876 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002877 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002878 }
2879 if ((state.orientation != draw[i].orientation) ||
2880 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002881 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002882 }
2883 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002884 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002885 }
2886 }
2887 }
2888 ++i;
2889 }
2890
2891 // find displays that were added
2892 // (ie: in current state but not in drawing state)
2893 for (size_t i = 0; i < cc; i++) {
2894 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2895 const DisplayDeviceState& state(curr[i]);
2896
Lloyd Pique542307f2018-10-19 13:24:08 -07002897 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002898 sp<IGraphicBufferProducer> producer;
2899 sp<IGraphicBufferProducer> bqProducer;
2900 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002901 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002902
Dominik Laskowski075d3172018-05-24 15:50:06 -07002903 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002904 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002905 // Virtual displays without a surface are dormant:
2906 // they have external state (layer stack, projection,
2907 // etc.) but no internal state (i.e. a DisplayDevice).
2908 if (state.surface != nullptr) {
2909 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002910 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002911 int width = 0;
2912 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2913 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2914 int height = 0;
2915 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2916 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2917 int intFormat = 0;
2918 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2919 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002920 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002921
Dominik Laskowski075d3172018-05-24 15:50:06 -07002922 displayId =
2923 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002924 }
2925
2926 // TODO: Plumb requested format back up to consumer
2927
2928 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002929 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002930 bqProducer, bqConsumer,
2931 state.displayName);
2932
2933 dispSurface = vds;
2934 producer = vds;
2935 }
2936 } else {
2937 ALOGE_IF(state.surface != nullptr,
2938 "adding a supported display, but rendering "
2939 "surface is provided (%p), ignoring it",
2940 state.surface.get());
2941
Dominik Laskowski075d3172018-05-24 15:50:06 -07002942 displayId = state.displayId;
2943 LOG_ALWAYS_FATAL_IF(!displayId);
2944 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002945 producer = bqProducer;
2946 }
2947
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002948 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002949 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002950 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002951 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002953 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002954 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002955 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002956 }
2957 }
2958 }
2959 }
2960 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002961
2962 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002963}
2964
Mathias Agopian87baae12012-07-31 12:38:26 -07002965void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002966{
Dan Stoza7dde5992015-05-22 09:51:44 -07002967 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002968 mCurrentState.traverseInZOrder([](Layer* layer) {
2969 layer->notifyAvailableFrames();
2970 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002971
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972 /*
2973 * Traversal of the children
2974 * (perform the transaction for each of them if needed)
2975 */
2976
Mathias Agopian3559b072012-08-15 13:46:03 -07002977 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002978 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002980 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981
2982 const uint32_t flags = layer->doTransaction(0);
2983 if (flags & Layer::eVisibleRegion)
2984 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002985
2986 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002987 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002988 }
Robert Carr2047fae2016-11-28 14:09:09 -08002989 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990 }
2991
2992 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002993 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994 */
2995
Mathias Agopiane57f2922012-08-09 16:29:12 -07002996 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002997 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002998 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002999 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003001 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08003002 // The transform hint might have changed for some layers
3003 // (either because a display has changed, or because a layer
3004 // as changed).
3005 //
3006 // Walk through all the layers in currentLayers,
3007 // and update their transform hint.
3008 //
3009 // If a layer is visible only on a single display, then that
3010 // display is used to calculate the hint, otherwise we use the
3011 // default display.
3012 //
3013 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
3014 // the hint is set before we acquire a buffer from the surface texture.
3015 //
3016 // NOTE: layer transactions have taken place already, so we use their
3017 // drawing state. However, SurfaceFlinger's own transaction has not
3018 // happened yet, so we must use the current state layer list
3019 // (soon to become the drawing state list).
3020 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003021 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08003022 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08003023 bool first = true;
3024 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08003025 // NOTE: we rely on the fact that layers are sorted by
3026 // layerStack first (so we don't have to traverse the list
3027 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07003028 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08003029 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08003030 currentlayerStack = layerStack;
3031 // figure out if this layerstack is mirrored
3032 // (more than one display) if so, pick the default display,
3033 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003034 hintDisplay = nullptr;
3035 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08003036 if (display->getCompositionDisplay()
3037 ->belongsInOutput(layer->getLayerStack(),
3038 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003039 if (hintDisplay) {
3040 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003041 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003043 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003044 }
3045 }
3046 }
3047 }
Chet Haase91d25932013-04-11 15:24:55 -07003048
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003049 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003050 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3051 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003052
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003053 // could be null when this layer is using a layerStack
3054 // that is not visible on any display. Also can occur at
3055 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003056 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003057 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003058
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003059 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003060 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003061 if (hintDisplay) {
3062 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003063 }
Robert Carr2047fae2016-11-28 14:09:09 -08003064
3065 first = false;
3066 });
Mathias Agopian84300952012-11-21 16:02:13 -08003067 }
3068
3069
Mathias Agopian3559b072012-08-15 13:46:03 -07003070 /*
3071 * Perform our own transaction if needed
3072 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073
3074 if (mLayersAdded) {
3075 mLayersAdded = false;
3076 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003077 mVisibleRegionsDirty = true;
3078 }
3079
3080 // some layers might have been removed, so
3081 // we need to update the regions they're exposing.
3082 if (mLayersRemoved) {
3083 mLayersRemoved = false;
3084 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003085 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003087 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003088 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003089 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003090 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003091 }
Robert Carr2047fae2016-11-28 14:09:09 -08003092 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093 }
3094
Vishnu Nairec0ab382019-02-13 15:32:56 -08003095 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003097}
3098
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003099void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003100 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003101 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003102 return;
3103 }
3104
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003105 if (mVisibleRegionsDirty || mInputInfoChanged) {
3106 mInputInfoChanged = false;
3107 updateInputWindowInfo();
3108 }
3109
3110 executeInputWindowCommands();
3111}
3112
3113void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003114 Vector<InputWindowInfo> inputHandles;
3115
3116 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3117 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003118 // When calculating the screen bounds we ignore the transparent region since it may
3119 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003120 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003121 }
3122 });
3123 mInputFlinger->setInputWindows(inputHandles);
3124}
3125
Vishnu Nairec0ab382019-02-13 15:32:56 -08003126void SurfaceFlinger::commitInputWindowCommands() {
3127 mInputWindowCommands.merge(mPendingInputWindowCommands);
3128 mPendingInputWindowCommands.clear();
3129}
3130
chaviwfbe5d9c2018-12-26 12:23:37 -08003131void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003132 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3133 if (transferTouchFocusCommand.fromToken != nullptr &&
3134 transferTouchFocusCommand.toToken != nullptr &&
3135 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3136 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3137 transferTouchFocusCommand.toToken);
3138 }
3139 }
3140
3141 mInputWindowCommands.clear();
3142}
3143
Riley Andrews03414a12014-07-01 14:22:59 -07003144void SurfaceFlinger::updateCursorAsync()
3145{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003146 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003147 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003148 continue;
3149 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003151 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3152 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003153 }
3154 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003155}
3156
chaviw61626f22018-11-15 16:26:27 -08003157void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3158 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003159 nsecs_t expectedPresentTime;
3160 if (mUseScheduler) {
3161 expectedPresentTime = mScheduler->expectedPresentTime();
3162 } else {
3163 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3164 }
chaviw61626f22018-11-15 16:26:27 -08003165 if (layer->shouldPresentNow(expectedPresentTime)) {
3166 bool ignored = false;
3167 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3168 }
3169 }
3170 layer->releasePendingBuffer(systemTime());
3171}
3172
Mathias Agopian4fec8732012-06-29 14:12:52 -07003173void SurfaceFlinger::commitTransaction()
3174{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003175 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003176 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 for (const auto& l : mLayersPendingRemoval) {
3178 recordBufferingStats(l->getName().string(),
3179 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003180
3181 // We need to release the HWC layers when the Layer is removed
3182 // from the current state otherwise the HWC layer just continues
3183 // showing at its last configured state until we eventually
3184 // abandon the buffer queue.
3185 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003186 l->destroyHwcLayersForAllDisplays();
3187 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003188 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003189 }
3190 mLayersPendingRemoval.clear();
3191 }
3192
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003193 // If this transaction is part of a window animation then the next frame
3194 // we composite should be considered an animation as well.
3195 mAnimCompositionPending = mAnimTransactionPending;
3196
Mathias Agopian4fec8732012-06-29 14:12:52 -07003197 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003198 // clear the "changed" flags in current state
3199 mCurrentState.colorMatrixChanged = false;
3200
Robert Carr1f0a16a2016-10-24 16:27:39 -07003201 mDrawingState.traverseInZOrder([](Layer* layer) {
3202 layer->commitChildList();
3203 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003204 mTransactionPending = false;
3205 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003206 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207}
3208
Lloyd Pique32cbe282018-10-19 13:09:22 -07003209void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003210 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003211 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003212 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003213
Lloyd Pique32cbe282018-10-19 13:09:22 -07003214 auto display = displayDevice->getCompositionDisplay();
3215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 Region aboveOpaqueLayers;
3217 Region aboveCoveredLayers;
3218 Region dirty;
3219
Mathias Agopian87baae12012-07-31 12:38:26 -07003220 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221
Robert Carr2047fae2016-11-28 14:09:09 -08003222 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003223 // start with the whole surface at its current location
3224 const Layer::State& s(layer->getDrawingState());
3225
Jesse Hall01e29052013-02-19 16:13:35 -08003226 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003227 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003228 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003229 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003230
Mathias Agopianab028732010-03-16 16:41:46 -07003231 /*
3232 * opaqueRegion: area of a surface that is fully opaque.
3233 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003235
3236 /*
3237 * visibleRegion: area of a surface that is visible on screen
3238 * and not fully transparent. This is essentially the layer's
3239 * footprint minus the opaque regions above it.
3240 * Areas covered by a translucent surface are considered visible.
3241 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003243
3244 /*
3245 * coveredRegion: area of a surface that is covered by all
3246 * visible regions above it (which includes the translucent areas).
3247 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003249
Jesse Halla8026d22012-09-25 13:25:04 -07003250 /*
3251 * transparentRegion: area of a surface that is hinted to be completely
3252 * transparent. This is only used to tell when the layer has no visible
3253 * non-transparent regions and can be removed from the layer list. It
3254 * does not affect the visibleRegion of this layer or any layers
3255 * beneath it. The hint may not be correct if apps don't respect the
3256 * SurfaceView restrictions (which, sadly, some don't).
3257 */
3258 Region transparentRegion;
3259
Mathias Agopianab028732010-03-16 16:41:46 -07003260
3261 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003262 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003263 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003264 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003267 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003268 if (!visibleRegion.isEmpty()) {
3269 // Remove the transparent area from the visible region
3270 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003271 if (tr.preserveRects()) {
3272 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003273 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003274 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003275 // transformation too complex, can't do the
3276 // transparent region optimization.
3277 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003278 }
Mathias Agopianab028732010-03-16 16:41:46 -07003279 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280
Mathias Agopianab028732010-03-16 16:41:46 -07003281 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003282 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003283 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003284 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003285 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003286 // the opaque region is the layer's footprint
3287 opaqueRegion = visibleRegion;
3288 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289 }
3290 }
3291
Robert Carre5f4f692018-01-12 13:12:28 -08003292 if (visibleRegion.isEmpty()) {
3293 layer->clearVisibilityRegions();
3294 return;
3295 }
3296
Mathias Agopianab028732010-03-16 16:41:46 -07003297 // Clip the covered region to the visible region
3298 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3299
3300 // Update aboveCoveredLayers for next (lower) layer
3301 aboveCoveredLayers.orSelf(visibleRegion);
3302
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303 // subtract the opaque region covered by the layers above us
3304 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305
3306 // compute this layer's dirty region
3307 if (layer->contentDirty) {
3308 // we need to invalidate the whole region
3309 dirty = visibleRegion;
3310 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003311 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003312 layer->contentDirty = false;
3313 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003314 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003315 * the exposed region consists of two components:
3316 * 1) what's VISIBLE now and was COVERED before
3317 * 2) what's EXPOSED now less what was EXPOSED before
3318 *
3319 * note that (1) is conservative, we start with the whole
3320 * visible region but only keep what used to be covered by
3321 * something -- which mean it may have been exposed.
3322 *
3323 * (2) handles areas that were not covered by anything but got
3324 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003325 */
Mathias Agopianab028732010-03-16 16:41:46 -07003326 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003327 const Region oldVisibleRegion = layer->visibleRegion;
3328 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003329 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3330 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 }
3332 dirty.subtractSelf(aboveOpaqueLayers);
3333
3334 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003335 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003336
Mathias Agopianab028732010-03-16 16:41:46 -07003337 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003338 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003339
Jesse Halla8026d22012-09-25 13:25:04 -07003340 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003341 layer->setVisibleRegion(visibleRegion);
3342 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003343 layer->setVisibleNonTransparentRegion(
3344 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003345 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346
Mathias Agopian87baae12012-07-31 12:38:26 -07003347 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003348}
3349
Chia-I Wuab0c3192017-08-01 11:29:00 -07003350void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003351 for (const auto& [token, displayDevice] : mDisplays) {
3352 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003353 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003354 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003355 }
3356 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003357}
3358
Daniel Solomon42d04562019-01-20 21:03:19 -08003359void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3360 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3361 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3362 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3363 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3364 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3365 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3366 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3367 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3368 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3369 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3370 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3371 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3372}
3373
Dan Stoza6b9454d2014-11-07 16:00:59 -08003374bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003376 ALOGV("handlePageFlip");
3377
Brian Andersond6927fb2016-07-23 23:37:30 -07003378 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003379
Mathias Agopian4fec8732012-06-29 14:12:52 -07003380 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003381 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003382 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003383
3384 // Store the set of layers that need updates. This set must not change as
3385 // buffers are being latched, as this could result in a deadlock.
3386 // Example: Two producers share the same command stream and:
3387 // 1.) Layer 0 is latched
3388 // 2.) Layer 0 gets a new frame
3389 // 2.) Layer 1 gets a new frame
3390 // 3.) Layer 1 is latched.
3391 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3392 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003393 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003394 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003395 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003396 nsecs_t expectedPresentTime;
3397 if (mUseScheduler) {
3398 expectedPresentTime = mScheduler->expectedPresentTime();
3399 } else {
3400 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3401 }
Ana Krulec010d2192018-10-08 06:29:54 -07003402 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003403 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003404 } else {
3405 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003406 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003407 } else {
3408 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003409 }
Robert Carr2047fae2016-11-28 14:09:09 -08003410 });
3411
Lloyd Piquef2c79392018-12-20 16:23:33 -08003412 if (!mLayersWithQueuedFrames.empty()) {
3413 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3414 // writes to Layer current state. See also b/119481871
3415 Mutex::Autolock lock(mStateLock);
3416
3417 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003418 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3419 mLayersPendingRefresh.push_back(layer);
3420 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003421 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003422 if (layer->isBufferLatched()) {
3423 newDataLatched = true;
3424 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003425 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003426 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003427
Alec Mouri86770e52018-09-24 22:40:58 +00003428 // Clear the renderengine fence here...
3429 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3430 // clear instead of sp::clear.
3431 getBE().flushFence = Fence::NO_FENCE;
3432
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003433 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003434
3435 // If we will need to wake up at some time in the future to deal with a
3436 // queued frame that shouldn't be displayed during this vsync period, wake
3437 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003438 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003439 signalLayerUpdate();
3440 }
3441
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003442 // enter boot animation on first buffer latch
3443 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3444 ALOGI("Enter boot animation");
3445 mBootStage = BootStage::BOOTANIMATION;
3446 }
3447
Dan Stoza6b9454d2014-11-07 16:00:59 -08003448 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003449 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003450}
3451
Mathias Agopianad456f92011-01-13 17:53:01 -08003452void SurfaceFlinger::invalidateHwcGeometry()
3453{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003454 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003455}
3456
Lloyd Pique32cbe282018-10-19 13:09:22 -07003457void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003458 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003459 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003460 // We only need to actually compose the display if:
3461 // 1) It is being handled by hardware composer, which may need this to
3462 // keep its virtual display state machine in sync, or
3463 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003464 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003465 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003466 return;
3467 }
3468
Dan Stoza9e56aa02015-11-02 13:00:03 -08003469 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003470 base::unique_fd readyFence;
3471 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003472
3473 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003474 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475}
3476
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003477bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3478 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003479 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003480 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003481
Lloyd Pique32cbe282018-10-19 13:09:22 -07003482 auto display = displayDevice->getCompositionDisplay();
3483 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003484 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003485
3486 const Region bounds(displayState.bounds);
3487 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003488 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003489 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003490
Peiyong Lind3788632018-09-18 16:01:31 -07003491 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003492 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003493
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003494 renderengine::DisplaySettings clientCompositionDisplay;
3495 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3496 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003497
Dan Stoza9e56aa02015-11-02 13:00:03 -08003498 if (hasClientComposition) {
3499 ALOGV("hasClientComposition");
3500
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003501 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003502
3503 if (buf == nullptr) {
3504 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3505 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003506 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003507 return false;
3508 }
3509
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003510 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3511 clientCompositionDisplay.clip = displayState.scissor;
3512 const ui::Transform& displayTransform = displayState.transform;
3513 mat4 m;
3514 m[0][0] = displayTransform[0][0];
3515 m[0][1] = displayTransform[0][1];
3516 m[0][3] = displayTransform[0][2];
3517 m[1][0] = displayTransform[1][0];
3518 m[1][1] = displayTransform[1][1];
3519 m[1][3] = displayTransform[1][2];
3520 m[3][0] = displayTransform[2][0];
3521 m[3][1] = displayTransform[2][1];
3522 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003523
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003524 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003525
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003526 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003527 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003528 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003529 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003530 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003531 clientCompositionDisplay.outputDataspace = outputDataspace;
3532 clientCompositionDisplay.maxLuminance =
3533 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003534
Lloyd Pique441d5042018-10-18 16:49:51 -07003535 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003536 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003537 getHwComposer()
3538 .hasDisplayCapability(displayId,
3539 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003540
Peiyong Lind3788632018-09-18 16:01:31 -07003541 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003542 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3543 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003544 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003545 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003546 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003547
Mathias Agopian85d751c2012-08-29 16:59:24 -07003548 /*
3549 * and then, render the layers targeted at the framebuffer
3550 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003551
Dan Stoza9e56aa02015-11-02 13:00:03 -08003552 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003553 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003554 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003555 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003556 const Region viewportRegion(displayState.viewport);
3557 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003558 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003559 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003560 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003561 switch (layer->getCompositionType(displayDevice)) {
3562 case Hwc2::IComposerClient::Composition::CURSOR:
3563 case Hwc2::IComposerClient::Composition::DEVICE:
3564 case Hwc2::IComposerClient::Composition::SIDEBAND:
3565 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003566 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003567 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003568 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003569 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003570 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003571 // never clear the very first layer since we're
3572 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003573 renderengine::LayerSettings layerSettings;
3574 Region dummyRegion;
3575 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3576 layerSettings);
3577
3578 if (prepared) {
3579 layerSettings.source.buffer.buffer = nullptr;
3580 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3581 layerSettings.alpha = half(0.0);
3582 layerSettings.disableBlending = true;
3583 clientCompositionLayers.push_back(layerSettings);
3584 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003585 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003586 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003587 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003588 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003589 renderengine::LayerSettings layerSettings;
3590 bool prepared =
3591 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3592 if (prepared) {
3593 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003594 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003595 break;
3596 }
3597 default:
3598 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003599 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003600 } else {
3601 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003602 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003603 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003604 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003605
Alec Mouri820c7402019-01-23 13:02:39 -08003606 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003607 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003608 clientCompositionDisplay.clearRegion = clearRegion;
3609 if (!debugRegion.isEmpty()) {
3610 Region::const_iterator it = debugRegion.begin();
3611 Region::const_iterator end = debugRegion.end();
3612 while (it != end) {
3613 const Rect& rect = *it++;
3614 renderengine::LayerSettings layerSettings;
3615 layerSettings.source.buffer.buffer = nullptr;
3616 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3617 layerSettings.geometry.boundaries = rect.toFloatRect();
3618 layerSettings.alpha = half(1.0);
3619 clientCompositionLayers.push_back(layerSettings);
3620 }
3621 }
3622 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3623 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003624 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003625 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626}
3627
Chia-I Wu28e3a252018-09-07 12:05:02 -07003628void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003629 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003630 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
Dan Stoza7d89d062015-04-30 13:29:25 -07003633status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003634 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003635 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003636 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003637 const sp<Layer>& parent,
3638 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003639{
Dan Stoza7d89d062015-04-30 13:29:25 -07003640 // add this layer to the current state list
3641 {
3642 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003643 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003644 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3645 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003646 return NO_MEMORY;
3647 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003648 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003649 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003650 } else if (parent == nullptr) {
3651 lbc->onRemovedFromCurrentState();
3652 } else if (parent->isRemovedFromCurrentState()) {
3653 parent->addChild(lbc);
3654 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003655 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003656 parent->addChild(lbc);
3657 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003658
Yiwei Zhang243b3782018-05-15 17:40:04 -07003659 if (gbc != nullptr) {
3660 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3661 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3662 mMaxGraphicBufferProducerListSize,
3663 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3664 mGraphicBufferProducerList.size(),
3665 mMaxGraphicBufferProducerListSize, mNumLayers);
3666 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003667 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003668 }
3669
Mathias Agopian96f08192010-06-02 23:28:45 -07003670 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003671 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003672
Dan Stoza7d89d062015-04-30 13:29:25 -07003673 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003674}
3675
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003676uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003677 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003678}
3679
Mathias Agopian3f844832013-08-07 21:24:32 -07003680uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003681 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003682}
3683
Mathias Agopian3f844832013-08-07 21:24:32 -07003684uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003685 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003686}
3687
3688uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003689 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003690 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003691 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003692 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003693 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 }
3695 return old;
3696}
3697
Marissa Wall713b63f2018-10-17 15:42:43 -07003698bool SurfaceFlinger::flushTransactionQueues() {
3699 Mutex::Autolock _l(mStateLock);
3700 auto it = mTransactionQueues.begin();
3701 while (it != mTransactionQueues.end()) {
3702 auto& [applyToken, transactionQueue] = *it;
3703
3704 while (!transactionQueue.empty()) {
Robert Carr14167e02019-02-13 13:50:55 -08003705 const auto& [states, displays, flags, desiredPresentTime, privileged] =
3706 transactionQueue.front();
Marissa Wall17b4e452018-12-26 16:32:34 -08003707 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003708 break;
3709 }
Robert Carr14167e02019-02-13 13:50:55 -08003710 applyTransactionState(states, displays, flags, mPendingInputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003711 transactionQueue.pop();
3712 }
3713
3714 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3715 }
3716 return mTransactionQueues.empty();
3717}
3718
chaviwca27f252018-02-06 16:46:39 -08003719bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3720 for (const ComposerState& state : states) {
3721 // Here we need to check that the interface we're given is indeed
3722 // one of our own. A malicious client could give us a nullptr
3723 // IInterface, or one of its own or even one of our own but a
3724 // different type. All these situations would cause us to crash.
3725 if (state.client == nullptr) {
3726 return true;
3727 }
3728
3729 sp<IBinder> binder = IInterface::asBinder(state.client);
3730 if (binder == nullptr) {
3731 return true;
3732 }
3733
3734 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3735 return true;
3736 }
3737 }
3738 return false;
3739}
3740
Marissa Wall17b4e452018-12-26 16:32:34 -08003741bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3742 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003743 nsecs_t expectedPresentTime;
3744 if (mUseScheduler) {
3745 expectedPresentTime = mScheduler->expectedPresentTime();
3746 } else {
3747 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3748 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003749 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3750 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3751 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3752 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3753 return false;
3754 }
3755
Marissa Wall713b63f2018-10-17 15:42:43 -07003756 for (const ComposerState& state : states) {
3757 const layer_state_t& s = state.state;
3758 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3759 continue;
3760 }
3761 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003762 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003763 }
3764 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003765 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003766}
3767
3768void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3769 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003770 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003771 const InputWindowCommands& inputWindowCommands,
3772 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003773 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003774
3775 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3776
Mathias Agopian698c0872011-06-28 19:09:31 -07003777 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003778
chaviwca27f252018-02-06 16:46:39 -08003779 if (containsAnyInvalidClientState(states)) {
3780 return;
3781 }
3782
Marissa Wall713b63f2018-10-17 15:42:43 -07003783 // If its TransactionQueue already has a pending TransactionState or if it is pending
3784 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003785 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003786 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3787 privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003788 setTransactionFlags(eTransactionNeeded);
3789 return;
3790 }
3791
Robert Carr14167e02019-02-13 13:50:55 -08003792 applyTransactionState(states, displays, flags, inputWindowCommands, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003793}
3794
3795void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003796 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003797 const InputWindowCommands& inputWindowCommands,
3798 bool privileged) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003799 uint32_t transactionFlags = 0;
3800
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003801 if (flags & eAnimation) {
3802 // For window updates that are part of an animation we must wait for
3803 // previous animation "frames" to be handled.
3804 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003805 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003806 if (CC_UNLIKELY(err != NO_ERROR)) {
3807 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003808 // caller after a few seconds.
3809 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3810 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003811 mAnimTransactionPending = false;
3812 break;
3813 }
3814 }
3815 }
3816
chaviwca27f252018-02-06 16:46:39 -08003817 for (const DisplayState& display : displays) {
3818 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003819 }
3820
Marissa Walle2ffb422018-10-12 11:33:52 -07003821 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003822 for (const ComposerState& state : states) {
Robert Carr14167e02019-02-13 13:50:55 -08003823 clientStateFlags |= setClientStateLocked(state, privileged);
chaviwca27f252018-02-06 16:46:39 -08003824 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003825 // If the state doesn't require a traversal and there are callbacks, send them now
3826 if (!(clientStateFlags & eTraversalNeeded)) {
3827 mTransactionCompletedThread.sendCallbacks();
3828 }
3829 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003830
chaviw273171b2018-12-26 11:46:30 -08003831 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3832
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003833 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3834 // anyway. This can be used as a flush mechanism for previous async transactions.
3835 // Empty animation transaction can be used to simulate back-pressure, so also force a
3836 // transaction for empty animation transactions.
3837 if (transactionFlags == 0 &&
3838 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003839 transactionFlags = eTransactionNeeded;
3840 }
3841
Mathias Agopian386aa982011-11-07 21:58:03 -08003842 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003843 if (mInterceptor->isEnabled()) {
3844 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003845 }
Irvel468051e2016-06-13 16:44:44 -07003846
Mathias Agopian386aa982011-11-07 21:58:03 -08003847 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003848 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3849 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003850 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003851
3852 // if this is a synchronous transaction, wait for it to take effect
3853 // before returning.
3854 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003855 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003856 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003857 if (flags & eAnimation) {
3858 mAnimTransactionPending = true;
3859 }
3860 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003861 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3862 if (CC_UNLIKELY(err != NO_ERROR)) {
3863 // just in case something goes wrong in SF, return to the
3864 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003865 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3866 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003867 break;
3868 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003869 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003870 }
3871}
3872
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003873uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3874 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3875 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003876
Mathias Agopiane57f2922012-08-09 16:29:12 -07003877 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003878 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3879
3880 const uint32_t what = s.what;
3881 if (what & DisplayState::eSurfaceChanged) {
3882 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3883 state.surface = s.surface;
3884 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003885 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003886 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003887 if (what & DisplayState::eLayerStackChanged) {
3888 if (state.layerStack != s.layerStack) {
3889 state.layerStack = s.layerStack;
3890 flags |= eDisplayTransactionNeeded;
3891 }
3892 }
3893 if (what & DisplayState::eDisplayProjectionChanged) {
3894 if (state.orientation != s.orientation) {
3895 state.orientation = s.orientation;
3896 flags |= eDisplayTransactionNeeded;
3897 }
3898 if (state.frame != s.frame) {
3899 state.frame = s.frame;
3900 flags |= eDisplayTransactionNeeded;
3901 }
3902 if (state.viewport != s.viewport) {
3903 state.viewport = s.viewport;
3904 flags |= eDisplayTransactionNeeded;
3905 }
3906 }
3907 if (what & DisplayState::eDisplaySizeChanged) {
3908 if (state.width != s.width) {
3909 state.width = s.width;
3910 flags |= eDisplayTransactionNeeded;
3911 }
3912 if (state.height != s.height) {
3913 state.height = s.height;
3914 flags |= eDisplayTransactionNeeded;
3915 }
3916 }
3917
Mathias Agopiane57f2922012-08-09 16:29:12 -07003918 return flags;
3919}
3920
Robert Carr14167e02019-02-13 13:50:55 -08003921bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003922 IPCThreadState* ipc = IPCThreadState::self();
3923 const int pid = ipc->getCallingPid();
3924 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003925 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003926 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003927 return false;
3928 }
3929 return true;
3930}
3931
Robert Carr14167e02019-02-13 13:50:55 -08003932uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState,
3933 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003934 const layer_state_t& s = composerState.state;
3935 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3936
Mathias Agopian13127d82013-03-05 17:47:11 -08003937 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003938 if (layer == nullptr) {
3939 return 0;
3940 }
3941
chaviw8b3871a2017-11-01 17:41:01 -07003942 uint32_t flags = 0;
3943
Garfield Tan8a3083e2018-12-03 13:21:07 -08003944 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003945 bool geometryAppliesWithResize =
3946 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003947
3948 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3949 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003950 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003951 layer->pushPendingState();
3952 }
3953
chaviw8b3871a2017-11-01 17:41:01 -07003954 if (what & layer_state_t::ePositionChanged) {
3955 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3956 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003957 }
chaviw8b3871a2017-11-01 17:41:01 -07003958 }
3959 if (what & layer_state_t::eLayerChanged) {
3960 // NOTE: index needs to be calculated before we update the state
3961 const auto& p = layer->getParent();
3962 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003963 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003964 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003965 mCurrentState.layersSortedByZ.removeAt(idx);
3966 mCurrentState.layersSortedByZ.add(layer);
3967 // we need traversal (state changed)
3968 // AND transaction (list changed)
3969 flags |= eTransactionNeeded|eTraversalNeeded;
3970 }
chaviw8b3871a2017-11-01 17:41:01 -07003971 } else {
3972 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003973 flags |= eTransactionNeeded|eTraversalNeeded;
3974 }
3975 }
chaviw8b3871a2017-11-01 17:41:01 -07003976 }
3977 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003978 // NOTE: index needs to be calculated before we update the state
3979 const auto& p = layer->getParent();
3980 if (p == nullptr) {
3981 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3982 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3983 mCurrentState.layersSortedByZ.removeAt(idx);
3984 mCurrentState.layersSortedByZ.add(layer);
3985 // we need traversal (state changed)
3986 // AND transaction (list changed)
3987 flags |= eTransactionNeeded|eTraversalNeeded;
3988 }
3989 } else {
3990 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3991 flags |= eTransactionNeeded|eTraversalNeeded;
3992 }
chaviw8b3871a2017-11-01 17:41:01 -07003993 }
3994 }
3995 if (what & layer_state_t::eSizeChanged) {
3996 if (layer->setSize(s.w, s.h)) {
3997 flags |= eTraversalNeeded;
3998 }
3999 }
4000 if (what & layer_state_t::eAlphaChanged) {
4001 if (layer->setAlpha(s.alpha))
4002 flags |= eTraversalNeeded;
4003 }
4004 if (what & layer_state_t::eColorChanged) {
4005 if (layer->setColor(s.color))
4006 flags |= eTraversalNeeded;
4007 }
Peiyong Lind3788632018-09-18 16:01:31 -07004008 if (what & layer_state_t::eColorTransformChanged) {
4009 if (layer->setColorTransform(s.colorTransform)) {
4010 flags |= eTraversalNeeded;
4011 }
4012 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004013 if (what & layer_state_t::eBackgroundColorChanged) {
4014 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4015 flags |= eTraversalNeeded;
4016 }
4017 }
chaviw8b3871a2017-11-01 17:41:01 -07004018 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004019 // TODO: b/109894387
4020 //
4021 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4022 // rotation. To see the problem observe that if we have a square parent, and a child
4023 // of the same size, then we rotate the child 45 degrees around it's center, the child
4024 // must now be cropped to a non rectangular 8 sided region.
4025 //
4026 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4027 // private API, and the WindowManager only uses rotation in one case, which is on a top
4028 // level layer in which cropping is not an issue.
4029 //
4030 // However given that abuse of rotation matrices could lead to surfaces extending outside
4031 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4032 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4033 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004034 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004035 flags |= eTraversalNeeded;
4036 }
4037 if (what & layer_state_t::eTransparentRegionChanged) {
4038 if (layer->setTransparentRegionHint(s.transparentRegion))
4039 flags |= eTraversalNeeded;
4040 }
4041 if (what & layer_state_t::eFlagsChanged) {
4042 if (layer->setFlags(s.flags, s.mask))
4043 flags |= eTraversalNeeded;
4044 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004045 if (what & layer_state_t::eCropChanged_legacy) {
4046 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004047 flags |= eTraversalNeeded;
4048 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004049 if (what & layer_state_t::eCornerRadiusChanged) {
4050 if (layer->setCornerRadius(s.cornerRadius))
4051 flags |= eTraversalNeeded;
4052 }
chaviw8b3871a2017-11-01 17:41:01 -07004053 if (what & layer_state_t::eLayerStackChanged) {
4054 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4055 // We only allow setting layer stacks for top level layers,
4056 // everything else inherits layer stack from its parent.
4057 if (layer->hasParent()) {
4058 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4059 layer->getName().string());
4060 } else if (idx < 0) {
4061 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4062 "that also does not appear in the top level layer list. Something"
4063 " has gone wrong.", layer->getName().string());
4064 } else if (layer->setLayerStack(s.layerStack)) {
4065 mCurrentState.layersSortedByZ.removeAt(idx);
4066 mCurrentState.layersSortedByZ.add(layer);
4067 // we need traversal (state changed)
4068 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004069 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004070 }
4071 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004072 if (what & layer_state_t::eDeferTransaction_legacy) {
4073 if (s.barrierHandle_legacy != nullptr) {
4074 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4075 } else if (s.barrierGbp_legacy != nullptr) {
4076 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004077 if (authenticateSurfaceTextureLocked(gbp)) {
4078 const auto& otherLayer =
4079 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004080 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004081 } else {
4082 ALOGE("Attempt to defer transaction to to an"
4083 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004084 }
4085 }
chaviw8b3871a2017-11-01 17:41:01 -07004086 // We don't trigger a traversal here because if no other state is
4087 // changed, we don't want this to cause any more work
4088 }
4089 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004090 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004091 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004092 if (!hadParent) {
4093 mCurrentState.layersSortedByZ.remove(layer);
4094 }
chaviw8b3871a2017-11-01 17:41:01 -07004095 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004096 }
chaviw8b3871a2017-11-01 17:41:01 -07004097 }
4098 if (what & layer_state_t::eReparentChildren) {
4099 if (layer->reparentChildren(s.reparentHandle)) {
4100 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004101 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004102 }
chaviw8b3871a2017-11-01 17:41:01 -07004103 if (what & layer_state_t::eDetachChildren) {
4104 layer->detachChildren();
4105 }
4106 if (what & layer_state_t::eOverrideScalingModeChanged) {
4107 layer->setOverrideScalingMode(s.overrideScalingMode);
4108 // We don't trigger a traversal here because if no other state is
4109 // changed, we don't want this to cause any more work
4110 }
Marissa Wall61c58622018-07-18 10:12:20 -07004111 if (what & layer_state_t::eTransformChanged) {
4112 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4113 }
4114 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4115 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4116 flags |= eTraversalNeeded;
4117 }
4118 if (what & layer_state_t::eCropChanged) {
4119 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4120 }
Marissa Wall861616d2018-10-22 12:52:23 -07004121 if (what & layer_state_t::eFrameChanged) {
4122 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4123 }
Marissa Wall61c58622018-07-18 10:12:20 -07004124 if (what & layer_state_t::eAcquireFenceChanged) {
4125 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4126 }
4127 if (what & layer_state_t::eDataspaceChanged) {
4128 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4129 }
4130 if (what & layer_state_t::eHdrMetadataChanged) {
4131 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4132 }
4133 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4134 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4135 }
4136 if (what & layer_state_t::eApiChanged) {
4137 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4138 }
4139 if (what & layer_state_t::eSidebandStreamChanged) {
4140 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4141 }
Robert Carr720e5062018-07-30 17:45:14 -07004142 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004143 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4144 layer->setInputInfo(s.inputInfo);
4145 flags |= eTraversalNeeded;
4146 } else {
4147 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4148 }
Robert Carr720e5062018-07-30 17:45:14 -07004149 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004150 if (what & layer_state_t::eMetadataChanged) {
4151 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4152 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004153 std::vector<sp<CallbackHandle>> callbackHandles;
4154 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4155 mTransactionCompletedThread.run();
4156 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4157 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4158 }
4159 }
Marissa Wall73411622019-01-25 10:45:41 -08004160
4161 if (what & layer_state_t::eBufferChanged) {
4162 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4163 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4164 s.buffer);
4165 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004166 if (what & layer_state_t::eCachedBufferChanged) {
4167 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004168 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4169 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004170 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4171 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004172 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4173 // Do not put anything that updates layer state or modifies flags after
4174 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004175 return flags;
4176}
4177
chaviw273171b2018-12-26 11:46:30 -08004178uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4179 uint32_t flags = 0;
4180 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4181 flags |= eTraversalNeeded;
4182 }
4183
Vishnu Nairec0ab382019-02-13 15:32:56 -08004184 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004185 return flags;
4186}
4187
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004188status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4189 uint32_t h, PixelFormat format, uint32_t flags,
4190 LayerMetadata metadata, sp<IBinder>* handle,
4191 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004192 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004193 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004194 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004195 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004196 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004197
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004198 status_t result = NO_ERROR;
4199
4200 sp<Layer> layer;
4201
Cody Northropbc755282017-03-31 12:00:08 -06004202 String8 uniqueName = getUniqueLayerName(name);
4203
Mathias Agopian3165cc22012-08-08 19:42:09 -07004204 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004205 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004206 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4207 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004210 case ISurfaceComposerClient::eFXSurfaceBufferState:
4211 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4212 break;
chaviw13fdc492017-06-27 12:40:18 -07004213 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004214 // check if buffer size is set for color layer.
4215 if (w > 0 || h > 0) {
4216 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4217 int(w), int(h));
4218 return BAD_VALUE;
4219 }
4220
chaviw13fdc492017-06-27 12:40:18 -07004221 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004222 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004223 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004224 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004225 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004226 // check if buffer size is set for container layer.
4227 if (w > 0 || h > 0) {
4228 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4229 int(w), int(h));
4230 return BAD_VALUE;
4231 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004232 result = createContainerLayer(client,
4233 uniqueName, w, h, flags,
4234 handle, &layer);
4235 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004236 default:
4237 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004238 break;
4239 }
4240
Dan Stoza7d89d062015-04-30 13:29:25 -07004241 if (result != NO_ERROR) {
4242 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004244
Chia-I Wuab0c3192017-08-01 11:29:00 -07004245 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4246 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004247 if (metadata.has(METADATA_WINDOW_TYPE)) {
4248 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4249 if (windowType == 441731) {
4250 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4251 layer->setPrimaryDisplayOnly();
4252 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004253 }
4254
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004255 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004256
Robert Carrb89ea9d2018-12-10 13:01:14 -08004257 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4258 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4259 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004260 if (result != NO_ERROR) {
4261 return result;
4262 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004263 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004264
4265 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004266 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004267}
4268
Cody Northropbc755282017-03-31 12:00:08 -06004269String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4270{
4271 bool matchFound = true;
4272 uint32_t dupeCounter = 0;
4273
4274 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4275 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4276
Dan Stoza436ccf32018-06-21 12:10:12 -07004277 // Grab the state lock since we're accessing mCurrentState
4278 Mutex::Autolock lock(mStateLock);
4279
Cody Northropbc755282017-03-31 12:00:08 -06004280 // Loop over layers until we're sure there is no matching name
4281 while (matchFound) {
4282 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004283 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004284 if (layer->getName() == uniqueName) {
4285 matchFound = true;
4286 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4287 }
4288 });
4289 }
4290
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004291 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4292 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004293
4294 return uniqueName;
4295}
4296
Marissa Wallfd668622018-05-10 10:21:13 -07004297status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4298 uint32_t w, uint32_t h, uint32_t flags,
4299 PixelFormat& format, sp<IBinder>* handle,
4300 sp<IGraphicBufferProducer>* gbp,
4301 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004303 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004304 case PIXEL_FORMAT_TRANSPARENT:
4305 case PIXEL_FORMAT_TRANSLUCENT:
4306 format = PIXEL_FORMAT_RGBA_8888;
4307 break;
4308 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004309 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004310 break;
4311 }
4312
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004313 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004314 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004315 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004316 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004317 *handle = layer->getHandle();
4318 *gbp = layer->getProducer();
4319 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004320 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004321
Marissa Wallfd668622018-05-10 10:21:13 -07004322 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004323 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004324}
4325
Marissa Wall61c58622018-07-18 10:12:20 -07004326status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4327 uint32_t w, uint32_t h, uint32_t flags,
4328 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004329 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004330 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004331 *handle = layer->getHandle();
4332 *outLayer = layer;
4333
4334 return NO_ERROR;
4335}
4336
chaviw13fdc492017-06-27 12:40:18 -07004337status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004338 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004339 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004340{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004341 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004342 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004343 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004344}
4345
Robert Carr6b3f6c52018-08-13 13:05:17 -07004346status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4347 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4348 sp<IBinder>* handle, sp<Layer>* outLayer)
4349{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004350 *outLayer =
4351 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004352 *handle = (*outLayer)->getHandle();
4353 return NO_ERROR;
4354}
4355
4356
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004357void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004358 mLayersPendingRemoval.add(layer);
4359 mLayersRemoved = true;
4360 setTransactionFlags(eTransactionNeeded);
4361}
4362
Robert Carr695d5282018-12-18 15:27:58 -08004363void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004364{
Robert Carr2e102c92018-10-23 12:11:15 -07004365 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004366 // If a layer has a parent, we allow it to out-live it's handle
4367 // with the idea that the parent holds a reference and will eventually
4368 // be cleaned up. However no one cleans up the top-level so we do so
4369 // here.
4370 if (layer->getParent() == nullptr) {
4371 mCurrentState.layersSortedByZ.remove(layer);
4372 }
4373 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004374 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004375}
4376
Mathias Agopianb60314a2012-04-10 22:09:54 -07004377// ---------------------------------------------------------------------------
4378
Andy McFadden13a082e2012-08-24 10:16:42 -07004379void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004380 const auto display = getDefaultDisplayDeviceLocked();
4381 if (!display) return;
4382
4383 const sp<IBinder> token = display->getDisplayToken().promote();
4384 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004385
Jesse Hall01e29052013-02-19 16:13:35 -08004386 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004387 Vector<ComposerState> state;
4388 Vector<DisplayState> displays;
4389 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004390 d.what = DisplayState::eDisplayProjectionChanged |
4391 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004392 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004393 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004394 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004395 d.frame.makeInvalid();
4396 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004397 d.width = 0;
4398 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004399 displays.add(d);
Vishnu Nairec0ab382019-02-13 15:32:56 -08004400 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004401
Dominik Laskowskie9774092018-12-11 10:04:24 -08004402 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004403
Dominik Laskowski83b88212018-12-11 13:34:06 -08004404 const nsecs_t vsyncPeriod = getVsyncPeriod();
4405 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004406
Brian Andersond0010582017-03-07 13:20:31 -08004407 // Use phase of 0 since phase is not known.
4408 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004409 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004410 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004411}
4412
4413void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004414 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004415 postMessageAsync(
4416 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004417}
4418
Dominik Laskowskie9774092018-12-11 10:04:24 -08004419void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004420 if (display->isVirtual()) {
4421 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004422 return;
4423 }
4424
Dominik Laskowski075d3172018-05-24 15:50:06 -07004425 const auto displayId = display->getId();
4426 LOG_ALWAYS_FATAL_IF(!displayId);
4427
Dominik Laskowski34157762018-10-31 13:07:19 -07004428 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004429
4430 int currentMode = display->getPowerMode();
4431 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004432 return;
4433 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004434
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004435 display->setPowerMode(mode);
4436
Lloyd Pique4dccc412018-01-22 17:21:36 -08004437 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004438 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004439 }
4440
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004441 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004442 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004443 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004444 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004445 if (mUseScheduler) {
4446 mScheduler->onScreenAcquired(mAppConnectionHandle);
4447 } else {
4448 mEventThread->onScreenAcquired();
4449 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004450 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004452
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004453 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004454 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004455 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004456
4457 struct sched_param param = {0};
4458 param.sched_priority = 1;
4459 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4460 ALOGW("Couldn't set SCHED_FIFO on display on");
4461 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004462 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004463 // Turn off the display
4464 struct sched_param param = {0};
4465 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4466 ALOGW("Couldn't set SCHED_OTHER on display off");
4467 }
4468
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004469 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004470 if (mUseScheduler) {
4471 mScheduler->disableHardwareVsync(true);
4472 } else {
4473 disableHardwareVsync(true); // also cancels any in-progress resync
4474 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004475 if (mUseScheduler) {
4476 mScheduler->onScreenReleased(mAppConnectionHandle);
4477 } else {
4478 mEventThread->onScreenReleased();
4479 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004480 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004481
Dominik Laskowski075d3172018-05-24 15:50:06 -07004482 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004483 mVisibleRegionsDirty = true;
4484 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004485 } else if (mode == HWC_POWER_MODE_DOZE ||
4486 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004487 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004488 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004489 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004490 if (mUseScheduler) {
4491 mScheduler->onScreenAcquired(mAppConnectionHandle);
4492 } else {
4493 mEventThread->onScreenAcquired();
4494 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004495 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004496 }
4497 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4498 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004499 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004500 if (mUseScheduler) {
4501 mScheduler->disableHardwareVsync(true);
4502 } else {
4503 disableHardwareVsync(true); // also cancels any in-progress resync
4504 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004505 if (mUseScheduler) {
4506 mScheduler->onScreenReleased(mAppConnectionHandle);
4507 } else {
4508 mEventThread->onScreenReleased();
4509 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004510 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004511 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004512 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004513 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004514 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004515 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004516
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004517 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004518 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004519 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004520 // Update refresh rate stats.
4521 mRefreshRateStats->setPowerMode(mode);
4522 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004523 }
4524
Dominik Laskowski34157762018-10-31 13:07:19 -07004525 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004526}
4527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004528void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004529 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004530 const auto display = getDisplayDevice(displayToken);
4531 if (!display) {
4532 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4533 displayToken.get());
4534 } else if (display->isVirtual()) {
4535 ALOGW("Attempt to set power mode %d for virtual display", mode);
4536 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004537 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004538 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004539 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004540}
4541
4542// ---------------------------------------------------------------------------
4543
Dominik Laskowskic2867142019-01-21 11:33:38 -08004544status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4545 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004547
Mathias Agopianbd115332013-04-18 16:41:04 -07004548 IPCThreadState* ipc = IPCThreadState::self();
4549 const int pid = ipc->getCallingPid();
4550 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004551
Mathias Agopianbd115332013-04-18 16:41:04 -07004552 if ((uid != AID_SHELL) &&
4553 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004554 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4555 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004557 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004558 // (this would indicate SF is stuck, but we want to be able to
4559 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004560 status_t err = mStateLock.timedLock(s2ns(1));
4561 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004562 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004563 StringAppendF(&result,
4564 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4565 "(no locks held)\n",
4566 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004567 }
4568
Dominik Laskowskic2867142019-01-21 11:33:38 -08004569 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004570
Dominik Laskowskic2867142019-01-21 11:33:38 -08004571 static const std::unordered_map<std::string, Dumper> dumpers = {
4572 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4573 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4574 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004575 {"--dispsync"s, dumper([this](std::string& s) {
4576 if (mUseScheduler) {
4577 mScheduler->dumpPrimaryDispSync(s);
4578 } else {
4579 mPrimaryDispSync->dump(s);
4580 }
4581 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004582 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4583 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004584 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4585 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4586 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4587 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4588 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4589 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004590 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004591 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4592 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004593
Dominik Laskowskic2867142019-01-21 11:33:38 -08004594 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004595
Dominik Laskowskic2867142019-01-21 11:33:38 -08004596 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4597 (it->second)(args, asProto, result);
4598 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004599 if (asProto) {
4600 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4601 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4602 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004603 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004604 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004605 }
4606
Mathias Agopian9795c422009-08-26 16:36:26 -07004607 if (locked) {
4608 mStateLock.unlock();
4609 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004610 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004611 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 return NO_ERROR;
4613}
4614
Dominik Laskowskic2867142019-01-21 11:33:38 -08004615void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 mCurrentState.traverseInZOrder(
4617 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004618}
4619
Dominik Laskowskic2867142019-01-21 11:33:38 -08004620void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004621 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004622
Dominik Laskowskic2867142019-01-21 11:33:38 -08004623 if (args.size() > 1) {
4624 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004625 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004626 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004627 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004628 }
Robert Carr2047fae2016-11-28 14:09:09 -08004629 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004630 } else {
4631 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632 }
4633}
4634
Dominik Laskowskic2867142019-01-21 11:33:38 -08004635void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004636 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004637 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004638 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004639 }
Robert Carr2047fae2016-11-28 14:09:09 -08004640 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004641
Svetoslavd85084b2014-03-20 10:28:31 -07004642 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004643}
4644
Dominik Laskowskic2867142019-01-21 11:33:38 -08004645void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4646 mTimeStats->parseArgs(asProto, args, result);
4647}
4648
Jamie Gennis6547ff42013-07-16 20:12:42 -07004649// This should only be called from the main thread. Otherwise it would need
4650// the lock and should use mCurrentState rather than mDrawingState.
4651void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004652 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004653 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004654 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004655
4656 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4657}
4658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004660 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004661
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004662 if (isLayerTripleBufferingDisabled())
4663 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004664
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4666 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4667 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4668 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4669 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4670 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004671 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004672}
4673
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004674void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004675 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004676 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004677 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004678 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004679
4680 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4681
4682 if (mUseScheduler) {
4683 mScheduler->dump(mAppConnectionHandle, result);
4684 } else {
4685 mEventThread->dump(result);
4686 }
4687}
4688
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4690 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004691 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4692 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004693 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004694 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004696 }
David Sodman4a36e932017-11-07 14:29:47 -08004697 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004698 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004699 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4701 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004702}
4703
Dan Stozae77c7662016-05-13 11:37:28 -07004704void SurfaceFlinger::recordBufferingStats(const char* layerName,
4705 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004706 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4707 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004708 for (const auto& segment : history) {
4709 if (!segment.usedThirdBuffer) {
4710 stats.twoBufferTime += segment.totalTime;
4711 }
4712 if (segment.occupancyAverage < 1.0f) {
4713 stats.doubleBufferedTime += segment.totalTime;
4714 } else if (segment.occupancyAverage < 2.0f) {
4715 stats.tripleBufferedTime += segment.totalTime;
4716 }
4717 ++stats.numSegments;
4718 stats.totalTime += segment.totalTime;
4719 }
4720}
4721
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4723 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004724
4725 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4726 const size_t count = currentLayers.size();
4727 for (size_t i=0 ; i<count ; i++) {
4728 currentLayers[i]->dumpFrameEvents(result);
4729 }
4730}
4731
Yiwei Zhang5434a782018-12-05 18:06:32 -08004732void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004733 result.append("Buffering stats:\n");
4734 result.append(" [Layer name] <Active time> <Two buffer> "
4735 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004736 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004737 typedef std::tuple<std::string, float, float, float> BufferTuple;
4738 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004739 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004740 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004741 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004742 if (stats.numSegments == 0) {
4743 continue;
4744 }
4745 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4746 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4747 stats.totalTime;
4748 float doubleBufferRatio = static_cast<float>(
4749 stats.doubleBufferedTime) / stats.totalTime;
4750 float tripleBufferRatio = static_cast<float>(
4751 stats.tripleBufferedTime) / stats.totalTime;
4752 sorted.insert({activeTime, {name, twoBufferRatio,
4753 doubleBufferRatio, tripleBufferRatio}});
4754 }
4755 for (const auto& sortedPair : sorted) {
4756 float activeTime = sortedPair.first;
4757 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4759 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004760 }
4761 result.append("\n");
4762}
4763
Yiwei Zhang5434a782018-12-05 18:06:32 -08004764void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004765 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004766 const auto displayId = display->getId();
4767 if (!displayId) {
4768 continue;
4769 }
4770 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004771 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004772 continue;
4773 }
4774
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result,
4776 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4777 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004778 uint8_t port;
4779 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004780 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004781 result.append("no identification data\n");
4782 continue;
4783 }
4784
4785 if (!isEdid(data)) {
4786 result.append("unknown identification data: ");
4787 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004789 }
4790 result.append("\n");
4791 continue;
4792 }
4793
4794 const auto edid = parseEdid(data);
4795 if (!edid) {
4796 result.append("invalid EDID: ");
4797 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004799 }
4800 result.append("\n");
4801 continue;
4802 }
4803
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004805 result.append(edid->displayName.data(), edid->displayName.length());
4806 result.append("\"\n");
4807 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004808}
4809
Yiwei Zhang5434a782018-12-05 18:06:32 -08004810void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4811 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4812 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4813 StringAppendF(&result, "DisplayColorSetting: %s\n",
4814 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004815
4816 // TODO: print out if wide-color mode is active or not
4817
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004818 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004819 const auto displayId = display->getId();
4820 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004821 continue;
4822 }
4823
Yiwei Zhang5434a782018-12-05 18:06:32 -08004824 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004826 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004828 }
4829
Lloyd Pique32cbe282018-10-19 13:09:22 -07004830 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831 StringAppendF(&result, " Current color mode: %s (%d)\n",
4832 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004833 }
4834 result.append("\n");
4835}
4836
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004837LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004838 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004839 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4840 const State& state = useDrawing ? mDrawingState : mCurrentState;
4841 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004842 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004843 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004844 });
4845
4846 return layersProto;
4847}
4848
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004849LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4850 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004851 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004852
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004853 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004854 resolution->set_w(displayDevice->getWidth());
4855 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004856
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004857 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004858 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004859
Lloyd Pique32cbe282018-10-19 13:09:22 -07004860 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4861 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4862 layersProto.set_global_transform(displayState.orientation);
4863
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004864 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004865 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004866 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004867 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004868 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004869 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004870 }
4871 });
4872
4873 return layersProto;
4874}
4875
Dominik Laskowskic2867142019-01-21 11:33:38 -08004876void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4877 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004878 Colorizer colorizer(colorize);
4879
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004880 // figure out if we're stuck somewhere
4881 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004882 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004883 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4884
4885 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004886 * Dump library configuration.
4887 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004888
4889 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004890 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004891 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004892 appendSfConfigString(result);
4893 appendUiConfigString(result);
4894 appendGuiConfigString(result);
4895 result.append("\n");
4896
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004897 result.append("\nDisplay identification data:\n");
4898 dumpDisplayIdentificationData(result);
4899
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004900 result.append("\nWide-Color information:\n");
4901 dumpWideColorInfo(result);
4902
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004903 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004904 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004905 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004906 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004907 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004908
Andy McFadden41d67d72014-04-25 16:58:34 -07004909 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004910 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004911 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004912 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004913 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004914
Dan Stozab90cf072015-03-05 11:05:59 -08004915 dumpStaticScreenStats(result);
4916 result.append("\n");
4917
Yiwei Zhang5434a782018-12-05 18:06:32 -08004918 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004919
Dan Stozae77c7662016-05-13 11:37:28 -07004920 dumpBufferingStats(result);
4921
Andy McFadden4803b742012-09-24 19:07:20 -07004922 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004923 * Dump the visible layer list
4924 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004925 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004926 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4927 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4928 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004929 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004930
Chia-I Wu2f884132018-09-13 15:17:58 -07004931 {
4932 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4933 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004934 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004935 result.append("\n");
4936 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004937
4938 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004939 * Dump Display state
4940 */
4941
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004942 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004943 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004944 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004945 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004946 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004947 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004948 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004949
4950 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004951 * Dump SurfaceFlinger global state
4952 */
4953
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004954 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004955 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004956 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004957
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004958 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004959
Dominik Laskowski075d3172018-05-24 15:50:06 -07004960 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004961 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4962 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004963 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4964 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004965 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004966 StringAppendF(&result,
4967 " transaction-flags : %08x\n"
4968 " gpu_to_cpu_unsupported : %d\n",
4969 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004970
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004971 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004972 displayId && getHwComposer().isConnected(*displayId)) {
4973 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004974 StringAppendF(&result,
4975 " refresh-rate : %f fps\n"
4976 " x-dpi : %f\n"
4977 " y-dpi : %f\n",
4978 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4979 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004980 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004981
Yiwei Zhang5434a782018-12-05 18:06:32 -08004982 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004983
Dan Stozae22aec72016-08-01 13:20:59 -07004984 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004985 * Tracing state
4986 */
4987 mTracing.dump(result);
4988 result.append("\n");
4989
4990 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004991 * HWC layer minidump
4992 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004993 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004994 const auto displayId = display->getId();
4995 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004996 continue;
4997 }
4998
Yiwei Zhang5434a782018-12-05 18:06:32 -08004999 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005000 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005001 const sp<DisplayDevice> displayDevice = display;
5002 mCurrentState.traverseInZOrder(
5003 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005004 result.append("\n");
5005 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005006
5007 /*
5008 * Dump HWComposer state
5009 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005010 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005011 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005012 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005013 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005014 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005015 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005016
5017 /*
5018 * Dump gralloc state
5019 */
5020 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5021 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005022
5023 /*
5024 * Dump VrFlinger state if in use.
5025 */
5026 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5027 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005028 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005029 result.append("\n");
5030 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005031
5032 /**
5033 * Scheduler dump state.
5034 */
5035 if (mUseScheduler) {
5036 result.append("\nScheduler state:\n");
5037 result.append(mScheduler->doDump() + "\n");
5038 result.append(mRefreshRateStats->doDump() + "\n");
5039 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005040}
5041
Dominik Laskowski075d3172018-05-24 15:50:06 -07005042const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005043 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005044 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005045 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005046 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005047 }
5048 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005049
Dominik Laskowski34157762018-10-31 13:07:19 -07005050 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005051 static const Vector<sp<Layer>> empty;
5052 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005053}
5054
Chia-I Wu28f320b2018-05-03 11:02:56 -07005055void SurfaceFlinger::updateColorMatrixLocked() {
5056 mat4 colorMatrix;
5057 if (mGlobalSaturationFactor != 1.0f) {
5058 // Rec.709 luma coefficients
5059 float3 luminance{0.213f, 0.715f, 0.072f};
5060 luminance *= 1.0f - mGlobalSaturationFactor;
5061 mat4 saturationMatrix = mat4(
5062 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5063 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5064 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5065 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5066 );
5067 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5068 } else {
5069 colorMatrix = mClientColorMatrix * mDaltonizer();
5070 }
5071
5072 if (mCurrentState.colorMatrix != colorMatrix) {
5073 mCurrentState.colorMatrix = colorMatrix;
5074 mCurrentState.colorMatrixChanged = true;
5075 setTransactionFlags(eTransactionNeeded);
5076 }
5077}
5078
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005079status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005080#pragma clang diagnostic push
5081#pragma clang diagnostic error "-Wswitch-enum"
5082 switch (static_cast<ISurfaceComposerTag>(code)) {
5083 // These methods should at minimum make sure that the client requested
5084 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005085 case BOOT_FINISHED:
5086 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005087 case CREATE_DISPLAY:
5088 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005089 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005090 case GET_ACTIVE_COLOR_MODE:
5091 case GET_ANIMATION_FRAME_STATS:
5092 case GET_HDR_CAPABILITIES:
5093 case SET_ACTIVE_CONFIG:
5094 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005095 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005096 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005097 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005098 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5099 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005100 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5101 IPCThreadState* ipc = IPCThreadState::self();
5102 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5103 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005104 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005105 }
Robert Carr1db73f62016-12-21 12:58:51 -08005106 return OK;
5107 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005108 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005109 IPCThreadState* ipc = IPCThreadState::self();
5110 const int pid = ipc->getCallingPid();
5111 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005112 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5113 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005114 return PERMISSION_DENIED;
5115 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005116 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005117 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005118 // Used by apps to hook Choreographer to SurfaceFlinger.
5119 case CREATE_DISPLAY_EVENT_CONNECTION:
5120 // The following calls are currently used by clients that do not
5121 // request necessary permissions. However, they do not expose any secret
5122 // information, so it is OK to pass them.
5123 case AUTHENTICATE_SURFACE:
5124 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005125 case GET_PHYSICAL_DISPLAY_IDS:
5126 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005127 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005128 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005129 case GET_DISPLAY_CONFIGS:
5130 case GET_DISPLAY_STATS:
5131 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5132 // Calling setTransactionState is safe, because you need to have been
5133 // granted a reference to Client* and Handle* to do anything with it.
5134 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005135 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005136 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005137 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005138 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005139 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005140 return OK;
5141 }
5142 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005143 case CAPTURE_SCREEN:
5144 case ADD_REGION_SAMPLING_LISTENER:
5145 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005146 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005147 IPCThreadState* ipc = IPCThreadState::self();
5148 const int pid = ipc->getCallingPid();
5149 const int uid = ipc->getCallingUid();
5150 if ((uid != AID_GRAPHICS) &&
5151 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5152 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5153 return PERMISSION_DENIED;
5154 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005155 return OK;
5156 }
5157 // The following codes are deprecated and should never be allowed to access SF.
5158 case CONNECT_DISPLAY_UNUSED:
5159 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5160 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5161 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005162 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005163 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005164
5165 // These codes are used for the IBinder protocol to either interrogate the recipient
5166 // side of the transaction for its canonical interface descriptor or to dump its state.
5167 // We let them pass by default.
5168 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5169 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5170 code == IBinder::SYSPROPS_TRANSACTION) {
5171 return OK;
5172 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005173 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005174 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005175 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005176 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5177 return OK;
5178 }
5179 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5180 return PERMISSION_DENIED;
5181#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005182}
5183
Ana Krulec13be8ad2018-08-21 02:43:56 +00005184status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5185 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005186 status_t credentialCheck = CheckTransactCodeCredentials(code);
5187 if (credentialCheck != OK) {
5188 return credentialCheck;
5189 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005190
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005191 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5192 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005193 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005194 IPCThreadState* ipc = IPCThreadState::self();
5195 const int uid = ipc->getCallingUid();
5196 if (CC_UNLIKELY(uid != AID_SYSTEM
5197 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005198 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005199 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005200 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005201 return PERMISSION_DENIED;
5202 }
5203 int n;
5204 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005205 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005206 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005207 return NO_ERROR;
5208 case 1002: // SHOW_UPDATES
5209 n = data.readInt32();
5210 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005211 invalidateHwcGeometry();
5212 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005213 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005214 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005215 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005216 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005217 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005218 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005219 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005220 setTransactionFlags(
5221 eTransactionNeeded|
5222 eDisplayTransactionNeeded|
5223 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005224 return NO_ERROR;
5225 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005226 case 1006:{ // send empty update
5227 signalRefresh();
5228 return NO_ERROR;
5229 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005230 case 1008: // toggle use of hw composer
5231 n = data.readInt32();
5232 mDebugDisableHWC = n ? 1 : 0;
5233 invalidateHwcGeometry();
5234 repaintEverything();
5235 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005236 case 1009: // toggle use of transform hint
5237 n = data.readInt32();
5238 mDebugDisableTransformHint = n ? 1 : 0;
5239 invalidateHwcGeometry();
5240 repaintEverything();
5241 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005242 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005243 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005244 reply->writeInt32(0);
5245 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005246 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005247 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005248 return NO_ERROR;
5249 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005250 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005251 if (!display) {
5252 return NAME_NOT_FOUND;
5253 }
5254
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005255 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005256 return NO_ERROR;
5257 }
5258 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005259 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005260 // daltonize
5261 n = data.readInt32();
5262 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005263 case 1:
5264 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5265 break;
5266 case 2:
5267 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5268 break;
5269 case 3:
5270 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5271 break;
5272 default:
5273 mDaltonizer.setType(ColorBlindnessType::None);
5274 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005275 }
5276 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005277 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005278 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005279 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005280 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005281
5282 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005283 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005284 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005285 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005286 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005287 // apply a color matrix
5288 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005289 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005290 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005291 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005292 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005293 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005294 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005295 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005296 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005297 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005298 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005299
5300 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5301 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005302 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005303 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5304 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5305 }
5306
Chia-I Wu28f320b2018-05-03 11:02:56 -07005307 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005308 return NO_ERROR;
5309 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005310 // This is an experimental interface
5311 // Needs to be shifted to proper binder interface when we productize
5312 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005313 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005314 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005315 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005316 return NO_ERROR;
5317 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005318 case 1017: {
5319 n = data.readInt32();
5320 mForceFullDamage = static_cast<bool>(n);
5321 return NO_ERROR;
5322 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005323 case 1018: { // Modify Choreographer's phase offset
5324 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005325 if (mUseScheduler) {
5326 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5327 } else {
5328 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5329 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005330 return NO_ERROR;
5331 }
5332 case 1019: { // Modify SurfaceFlinger's phase offset
5333 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005334 if (mUseScheduler) {
5335 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5336 } else {
5337 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5338 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005339 return NO_ERROR;
5340 }
Irvel468051e2016-06-13 16:44:44 -07005341 case 1020: { // Layer updates interceptor
5342 n = data.readInt32();
5343 if (n) {
5344 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005345 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005346 }
5347 else{
5348 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005349 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005350 }
5351 return NO_ERROR;
5352 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005353 case 1021: { // Disable HWC virtual displays
5354 n = data.readInt32();
5355 mUseHwcVirtualDisplays = !n;
5356 return NO_ERROR;
5357 }
Romain Guy0147a172017-06-01 13:53:56 -07005358 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005359 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005360 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005361
Chia-I Wu28f320b2018-05-03 11:02:56 -07005362 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005363 return NO_ERROR;
5364 }
Romain Guy54f154a2017-10-24 21:40:32 +01005365 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005366 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005367 invalidateHwcGeometry();
5368 repaintEverything();
5369 return NO_ERROR;
5370 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005371 // Deprecate, use 1030 to check whether the device is color managed.
5372 case 1024: {
5373 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005374 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005375 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005376 n = data.readInt32();
5377 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005378 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005379 mTracing.enable();
5380 doTracing("tracing.enable");
5381 reply->writeInt32(NO_ERROR);
5382 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005383 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005384 status_t err = mTracing.disable();
5385 reply->writeInt32(err);
5386 }
5387 return NO_ERROR;
5388 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005389 case 1026: { // Get layer tracing status
5390 reply->writeBool(mTracing.isEnabled());
5391 return NO_ERROR;
5392 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005393 // Is a DisplayColorSetting supported?
5394 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005395 const auto display = getDefaultDisplayDevice();
5396 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005397 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005398 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005399
5400 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5401 switch (setting) {
5402 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005403 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005404 break;
5405 case DisplayColorSetting::UNMANAGED:
5406 reply->writeBool(true);
5407 break;
5408 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005409 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005410 break;
5411 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005412 reply->writeBool(
5413 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005414 break;
5415 }
5416 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005417 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005418 // Is VrFlinger active?
5419 case 1028: {
5420 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005421 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005422 return NO_ERROR;
5423 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005424 // Is device color managed?
5425 case 1030: {
5426 reply->writeBool(useColorManagement);
5427 return NO_ERROR;
5428 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005429 // Override default composition data space
5430 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5431 // && adb shell stop zygote && adb shell start zygote
5432 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5433 // adb shell stop zygote && adb shell start zygote
5434 case 1031: {
5435 Mutex::Autolock _l(mStateLock);
5436 n = data.readInt32();
5437 if (n) {
5438 n = data.readInt32();
5439 if (n) {
5440 Dataspace dataspace = static_cast<Dataspace>(n);
5441 if (!validateCompositionDataspace(dataspace)) {
5442 return BAD_VALUE;
5443 }
5444 mDefaultCompositionDataspace = dataspace;
5445 }
5446 n = data.readInt32();
5447 if (n) {
5448 Dataspace dataspace = static_cast<Dataspace>(n);
5449 if (!validateCompositionDataspace(dataspace)) {
5450 return BAD_VALUE;
5451 }
5452 mWideColorGamutCompositionDataspace = dataspace;
5453 }
5454 } else {
5455 // restore composition data space.
5456 mDefaultCompositionDataspace = defaultCompositionDataspace;
5457 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5458 }
5459 return NO_ERROR;
5460 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005461 }
5462 }
5463 return err;
5464}
5465
Steven Thomas6d8110b2017-08-31 18:24:21 -07005466void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005467 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005468 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005469}
5470
Ana Krulec7d1d6832018-12-27 11:10:09 -08005471void SurfaceFlinger::repaintEverythingForHWC() {
5472 mRepaintEverything = true;
5473 mEventQueue->invalidateForHWC();
5474}
5475
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005476// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5477class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005478public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005479 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5480 ~WindowDisconnector() {
5481 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005482 }
5483
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484private:
5485 ANativeWindow* mWindow;
5486 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005487};
5488
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005489status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005490 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5491 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005492 uint32_t reqWidth, uint32_t reqHeight,
5493 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005494 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005495 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005496
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005497 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005498
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005499 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5500
Chia-I Wu20261cb2018-08-23 12:55:44 -07005501 sp<DisplayDevice> display;
5502 {
5503 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005504
Chia-I Wu20261cb2018-08-23 12:55:44 -07005505 display = getDisplayDeviceLocked(displayToken);
5506 if (!display) return BAD_VALUE;
5507
Chia-I Wucb023152018-08-28 12:57:23 -07005508 // set the requested width/height to the logical display viewport size
5509 // by default
5510 if (reqWidth == 0 || reqHeight == 0) {
5511 reqWidth = uint32_t(display->getViewport().width());
5512 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005513 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005514 }
5515
Peiyong Lin0e003c92018-09-17 11:09:51 -07005516 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5517 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005518
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005519 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5520 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005521 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5522 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005523}
5524
5525status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005526 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5527 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005528 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005529 ATRACE_CALL();
5530
5531 class LayerRenderArea : public RenderArea {
5532 public:
Robert Carr578038f2018-03-09 12:25:24 -08005533 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005534 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5535 bool childrenOnly)
5536 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005537 mLayer(layer),
5538 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005539 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005540 mFlinger(flinger),
5541 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005542 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005543 Rect getBounds() const override {
5544 const Layer::State& layerState(mLayer->getDrawingState());
5545 return mLayer->getBufferSize(layerState);
5546 }
Marissa Wall61c58622018-07-18 10:12:20 -07005547 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005548 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005549 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005550 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005551 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005552 }
chaviwa76b2712017-09-20 12:02:26 -07005553 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005554 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005555 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005556 Rect getSourceCrop() const override {
5557 if (mCrop.isEmpty()) {
5558 return getBounds();
5559 } else {
5560 return mCrop;
5561 }
5562 }
Robert Carr578038f2018-03-09 12:25:24 -08005563 class ReparentForDrawing {
5564 public:
5565 const sp<Layer>& oldParent;
5566 const sp<Layer>& newParent;
5567
Vishnu Nair4351ad52019-02-11 14:13:02 -08005568 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5569 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005570 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005571 // Compute and cache the bounds for the new parent layer.
5572 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005573 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005574 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005575 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005576 };
5577
5578 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005579 const Rect sourceCrop = getSourceCrop();
5580 // no need to check rotation because there is none
5581 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5582 sourceCrop.height() != getReqHeight();
5583
Robert Carr578038f2018-03-09 12:25:24 -08005584 if (!mChildrenOnly) {
5585 mTransform = mLayer->getTransform().inverse();
5586 drawLayers();
5587 } else {
5588 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005589 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005590 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5591 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005592
Vishnu Nair4351ad52019-02-11 14:13:02 -08005593 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005594 drawLayers();
5595 }
5596 }
chaviwa76b2712017-09-20 12:02:26 -07005597
chaviwa76b2712017-09-20 12:02:26 -07005598 private:
chaviw7206d492017-11-10 16:16:12 -08005599 const sp<Layer> mLayer;
5600 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005601
5602 // In the "childrenOnly" case we reparent the children to a screenshot
5603 // layer which has no properties set and which does not draw.
5604 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005605 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005606 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005607
5608 SurfaceFlinger* mFlinger;
5609 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005610 };
5611
5612 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5613 auto parent = layerHandle->owner.promote();
5614
Robert Carr2e102c92018-10-23 12:11:15 -07005615 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005616 ALOGE("captureLayers called with a removed parent");
5617 return NAME_NOT_FOUND;
5618 }
5619
Robert Carr578038f2018-03-09 12:25:24 -08005620 const int uid = IPCThreadState::self()->getCallingUid();
5621 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005622 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005623 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5624 return PERMISSION_DENIED;
5625 }
5626
chaviw7206d492017-11-10 16:16:12 -08005627 Rect crop(sourceCrop);
5628 if (sourceCrop.width() <= 0) {
5629 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005630 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005631 }
5632
5633 if (sourceCrop.height() <= 0) {
5634 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005635 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005636 }
5637
5638 int32_t reqWidth = crop.width() * frameScale;
5639 int32_t reqHeight = crop.height() * frameScale;
5640
Chia-I Wu20261cb2018-08-23 12:55:44 -07005641 // really small crop or frameScale
5642 if (reqWidth <= 0) {
5643 reqWidth = 1;
5644 }
5645 if (reqHeight <= 0) {
5646 reqHeight = 1;
5647 }
5648
Peiyong Lin0e003c92018-09-17 11:09:51 -07005649 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005650
Robert Carr578038f2018-03-09 12:25:24 -08005651 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005652 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5653 if (!layer->isVisible()) {
5654 return;
Robert Carr578038f2018-03-09 12:25:24 -08005655 } else if (childrenOnly && layer == parent.get()) {
5656 return;
chaviwa76b2712017-09-20 12:02:26 -07005657 }
5658 visitor(layer);
5659 });
5660 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005661 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005662}
5663
5664status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5665 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005666 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005667 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005668 bool useIdentityTransform) {
5669 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005670
Peiyong Lin0e003c92018-09-17 11:09:51 -07005671 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005672 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5673 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005674 *outBuffer =
5675 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5676 static_cast<android_pixel_format>(reqPixelFormat), 1,
5677 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005678
5679 // This mutex protects syncFd and captureResult for communication of the return values from the
5680 // main thread back to this Binder thread
5681 std::mutex captureMutex;
5682 std::condition_variable captureCondition;
5683 std::unique_lock<std::mutex> captureLock(captureMutex);
5684 int syncFd = -1;
5685 std::optional<status_t> captureResult;
5686
Robert Carr03480e22018-01-04 16:02:06 -08005687 const int uid = IPCThreadState::self()->getCallingUid();
5688 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5689
Dominik Laskowski8c001672018-05-30 16:52:06 -07005690 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005691 // If there is a refresh pending, bug out early and tell the binder thread to try again
5692 // after the refresh.
5693 if (mRefreshPending) {
5694 ATRACE_NAME("Skipping screenshot for now");
5695 std::unique_lock<std::mutex> captureLock(captureMutex);
5696 captureResult = std::make_optional<status_t>(EAGAIN);
5697 captureCondition.notify_one();
5698 return;
5699 }
5700
5701 status_t result = NO_ERROR;
5702 int fd = -1;
5703 {
5704 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005705 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005706 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5707 useIdentityTransform, forSystem, &fd);
5708 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005709 }
5710
5711 {
5712 std::unique_lock<std::mutex> captureLock(captureMutex);
5713 syncFd = fd;
5714 captureResult = std::make_optional<status_t>(result);
5715 captureCondition.notify_one();
5716 }
5717 });
5718
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005719 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005720 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005721 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005722 while (*captureResult == EAGAIN) {
5723 captureResult.reset();
5724 result = postMessageAsync(message);
5725 if (result != NO_ERROR) {
5726 return result;
5727 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005728 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005729 }
5730 result = *captureResult;
5731 }
5732
5733 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005734 sync_wait(syncFd, -1);
5735 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005736 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005737
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005738 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005739}
5740
chaviwa76b2712017-09-20 12:02:26 -07005741void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005742 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005743 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5744 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005745 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005746
chaviwa76b2712017-09-20 12:02:26 -07005747 const auto reqWidth = renderArea.getReqWidth();
5748 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005749 const auto sourceCrop = renderArea.getSourceCrop();
5750 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005751
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005752 renderengine::DisplaySettings clientCompositionDisplay;
5753 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005754
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005755 // assume that bounds are never offset, and that they are the same as the
5756 // buffer bounds.
5757 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5758 ui::Transform transform = renderArea.getTransform();
5759 mat4 m;
5760 m[0][0] = transform[0][0];
5761 m[0][1] = transform[0][1];
5762 m[0][3] = transform[0][2];
5763 m[1][0] = transform[1][0];
5764 m[1][1] = transform[1][1];
5765 m[1][3] = transform[1][2];
5766 m[3][0] = transform[2][0];
5767 m[3][1] = transform[2][1];
5768 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005769
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005770 clientCompositionDisplay.globalTransform = m;
5771 mat4 rotMatrix;
5772 // Displacement for repositioning the clipping rectangle after rotating it
5773 // with the rotation hint.
5774 int displacementX = 0;
5775 int displacementY = 0;
5776 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5777 switch (rotation) {
5778 case ui::Transform::ROT_90:
5779 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5780 displacementX = reqWidth;
5781 break;
5782 case ui::Transform::ROT_180:
5783 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5784 displacementX = reqWidth;
5785 displacementY = reqHeight;
5786 break;
5787 case ui::Transform::ROT_270:
5788 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5789 displacementY = reqHeight;
5790 break;
5791 default:
5792 break;
5793 }
5794 // We need to transform the clipping window into the right spot.
5795 // First, rotate the clipping rectangle by the rotation hint to get the
5796 // right orientation
5797 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5798 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5799 const vec4 rotClipTL = rotMatrix * clipTL;
5800 const vec4 rotClipBR = rotMatrix * clipBR;
5801 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5802 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5803 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5804 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5805
5806 // Now reposition the clipping rectangle with the displacement vector
5807 // computed above.
5808 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5809
5810 clientCompositionDisplay.clip =
5811 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5812 newClipRight + displacementX, newClipBottom + displacementY);
5813
5814 // We need to perform the same transformation in layer space, so propagate
5815 // it to the global transform.
5816 mat4 clipTransform = displacementMat * rotMatrix;
5817 clientCompositionDisplay.globalTransform *= clipTransform;
5818 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5819 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005820
chaviw50da5042018-04-09 13:49:37 -07005821 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005822
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005823 renderengine::LayerSettings fillLayer;
5824 fillLayer.source.buffer.buffer = nullptr;
5825 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5826 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5827 fillLayer.alpha = half(alpha);
5828 clientCompositionLayers.push_back(fillLayer);
5829
5830 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005831 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005832 renderengine::LayerSettings layerSettings;
5833 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5834 layerSettings);
5835 if (prepared) {
5836 clientCompositionLayers.push_back(layerSettings);
5837 }
chaviwa76b2712017-09-20 12:02:26 -07005838 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005839
5840 clientCompositionDisplay.clearRegion = clearRegion;
5841 base::unique_fd drawFence;
5842 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5843 &drawFence);
5844
5845 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005846}
5847
chaviwa76b2712017-09-20 12:02:26 -07005848status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5849 TraverseLayersFunction traverseLayers,
5850 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005851 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005852 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005853 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005854 ATRACE_CALL();
5855
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005856 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005857
5858 traverseLayers([&](Layer* layer) {
5859 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5860 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005861
Robert Carr03480e22018-01-04 16:02:06 -08005862 // We allow the system server to take screenshots of secure layers for
5863 // use in situations like the Screen-rotation animation and place
5864 // the impetus on WindowManager to not persist them.
5865 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005866 ALOGW("FB is protected: PERMISSION_DENIED");
5867 return PERMISSION_DENIED;
5868 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005869 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005870 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005871}
5872
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005873// ---------------------------------------------------------------------------
5874
Dan Stoza412903f2017-04-27 13:42:17 -07005875void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5876 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005877}
5878
Dan Stoza412903f2017-04-27 13:42:17 -07005879void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5880 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005881}
5882
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005883void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005884 const LayerVector::Visitor& visitor) {
5885 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005886 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005887 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005888 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005889 continue;
5890 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005891 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005892 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005893 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005894 return;
5895 }
chaviwa76b2712017-09-20 12:02:26 -07005896 if (!layer->isVisible()) {
5897 return;
5898 }
5899 visitor(layer);
5900 });
5901 }
5902}
5903
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005904}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005905
Lloyd Pique074e8122018-07-26 12:57:23 -07005906
Mathias Agopian3f844832013-08-07 21:24:32 -07005907#if defined(__gl_h_)
5908#error "don't include gl/gl.h in this file"
5909#endif
5910
5911#if defined(__gl2_h_)
5912#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005913#endif