blob: 37f763178eb0c065524b872ac5d0c083c5e739dc [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 Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080047#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070049#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080052#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080053#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080054#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070055#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070056#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070057#include <ui/ColorSpace.h>
58#include <ui/DebugUtils.h>
59#include <ui/DisplayInfo.h>
60#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <ui/GraphicBufferAllocator.h>
62#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070063#include <ui/UiConfig.h>
Ady Abraham8164d482019-01-11 14:47:59 -080064#include <utils/CallStack.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070087#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090
Steven Thomasb02664d2017-07-26 18:48:28 -070091#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070092#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070093#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070094#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070095#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070096#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070097#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070098#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/EventControlThread.h"
100#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700101#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700102#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700103#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800104#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700105
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700107
David Sodman7e4ae112018-02-09 15:02:28 -0800108#include "android-base/stringprintf.h"
109
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900110#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800111#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700112#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800113#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900114#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115
chaviw1d044282017-09-27 12:19:28 -0700116#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900117#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800119namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700120
Jaesoo Lee43518572017-01-23 19:03:16 +0900121using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900122using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800124
Yiwei Zhang5434a782018-12-05 18:06:32 -0800125using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700126using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700127using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800128using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700129using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700130using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900131
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800132using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
133
Steven Thomasb02664d2017-07-26 18:48:28 -0700134namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700135
136#pragma clang diagnostic push
137#pragma clang diagnostic error "-Wswitch-enum"
138
139bool isWideColorMode(const ColorMode colorMode) {
140 switch (colorMode) {
141 case ColorMode::DISPLAY_P3:
142 case ColorMode::ADOBE_RGB:
143 case ColorMode::DCI_P3:
144 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700145 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700146 case ColorMode::BT2100_PQ:
147 case ColorMode::BT2100_HLG:
148 return true;
149 case ColorMode::NATIVE:
150 case ColorMode::STANDARD_BT601_625:
151 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
152 case ColorMode::STANDARD_BT601_525:
153 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
154 case ColorMode::STANDARD_BT709:
155 case ColorMode::SRGB:
156 return false;
157 }
158 return false;
159}
160
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700161ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
162 switch (rotation) {
163 case ISurfaceComposer::eRotateNone:
164 return ui::Transform::ROT_0;
165 case ISurfaceComposer::eRotate90:
166 return ui::Transform::ROT_90;
167 case ISurfaceComposer::eRotate180:
168 return ui::Transform::ROT_180;
169 case ISurfaceComposer::eRotate270:
170 return ui::Transform::ROT_270;
171 }
172 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
173 return ui::Transform::ROT_0;
174}
175
Peiyong Linfca547f2018-07-09 13:03:33 -0700176#pragma clang diagnostic pop
177
Steven Thomasb02664d2017-07-26 18:48:28 -0700178class ConditionalLock {
179public:
180 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
181 if (lock) {
182 mMutex.lock();
183 }
184 }
185 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
186private:
187 Mutex& mMutex;
188 bool mLocked;
189};
Peiyong Linfca547f2018-07-09 13:03:33 -0700190
Peiyong Lin9d846a52018-11-05 13:18:20 -0800191// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
192bool validateCompositionDataspace(Dataspace dataspace) {
193 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
194}
195
Steven Thomasb02664d2017-07-26 18:48:28 -0700196} // namespace anonymous
197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198// ---------------------------------------------------------------------------
199
Mathias Agopian99b49842011-06-27 16:05:52 -0700200const String16 sHardwareTest("android.permission.HARDWARE_TEST");
201const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
202const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
203const String16 sDump("android.permission.DUMP");
204
Daniel Solomon42d04562019-01-20 21:03:19 -0800205constexpr float kSrgbRedX = 0.4123f;
206constexpr float kSrgbRedY = 0.2126f;
207constexpr float kSrgbRedZ = 0.0193f;
208constexpr float kSrgbGreenX = 0.3576f;
209constexpr float kSrgbGreenY = 0.7152f;
210constexpr float kSrgbGreenZ = 0.1192f;
211constexpr float kSrgbBlueX = 0.1805f;
212constexpr float kSrgbBlueY = 0.0722f;
213constexpr float kSrgbBlueZ = 0.9506f;
214constexpr float kSrgbWhiteX = 0.9505f;
215constexpr float kSrgbWhiteY = 1.0000f;
216constexpr float kSrgbWhiteZ = 1.0891f;
217
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800218constexpr float kDefaultRefreshRate = 60.f;
219constexpr float kPerformanceRefreshRate = 90.f;
220
Mathias Agopian99b49842011-06-27 16:05:52 -0700221// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700222int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700223bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800224uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800225bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800226bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800227int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600228bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700229int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700230bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700231bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700232Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
233ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
234Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
235ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700236
Kalle Raitaa099a242017-01-11 11:17:29 -0800237std::string getHwcServiceName() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.hwc_service_name", value, "default");
240 ALOGI("Using HWComposer service: '%s'", value);
241 return std::string(value);
242}
243
244bool useTrebleTestingOverride() {
245 char value[PROPERTY_VALUE_MAX] = {};
246 property_get("debug.sf.treble_testing_override", value, "false");
247 ALOGI("Treble testing override: '%s'", value);
248 return std::string(value) == "true";
249}
250
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
252 switch(displayColorSetting) {
253 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700254 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700256 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700258 return std::string("Enhanced");
259 default:
260 return std::string("Unknown ") +
261 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263}
264
David Sodmanbc815282017-11-05 18:57:52 -0800265SurfaceFlingerBE::SurfaceFlingerBE()
266 : mHwcServiceName(getHwcServiceName()),
David Sodman4a36e932017-11-07 14:29:47 -0800267 mFrameBuckets(),
268 mTotalTime(0),
269 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800270 mComposerSequenceId(0) {
271}
272
Lloyd Pique90c115d2018-09-18 21:39:42 -0700273SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
274 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800275 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700276 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700277 mTransactionPending(false),
278 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700279 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700280 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 mBootTime(systemTime()),
Ana Krulec757f63a2019-01-25 10:46:18 -0800282 mPhaseOffsets{getFactory().createPhaseOffsets()},
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800283 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800284 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800285 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800286 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700288 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700289 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700290 mDebugInTransaction(0),
291 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700292 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800293 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700294 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700295 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800296 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800297 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800298 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700299 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700300 mMainThreadId(std::this_thread::get_id()),
301 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800302
Lloyd Pique90c115d2018-09-18 21:39:42 -0700303SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
304 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800305 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800306
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700310
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700312
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900313 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800314
Steven Thomas050b2c82017-03-06 11:45:16 -0800315 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700321
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600323
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900324 mDefaultCompositionDataspace =
325 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
326 mWideColorGamutCompositionDataspace =
327 static_cast<ui::Dataspace>(wcg_composition_dataspace(Dataspace::V0_SRGB));
328 defaultCompositionDataspace = mDefaultCompositionDataspace;
329 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
330 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
331 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
332 wideColorGamutCompositionPixelFormat =
333 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700334
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900335 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800336
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900337 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
338 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
339 switch (tmpPrimaryDisplayOrientation) {
340 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700341 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800342 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700344 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800345 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900346 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700347 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800348 break;
349 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700350 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800351 break;
352 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700353 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800354
Daniel Solomon42d04562019-01-20 21:03:19 -0800355 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
356 if (surfaceFlingerConfigsServiceV1_2) {
357 surfaceFlingerConfigsServiceV1_2->getDisplayNativePrimaries(
358 [&](auto tmpPrimaries) {
359 memcpy(&mInternalDisplayPrimaries, &tmpPrimaries, sizeof(ui::DisplayPrimaries));
360 });
361 } else {
362 initDefaultDisplayNativePrimaries();
363 }
364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365 // debugging stuff...
366 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700367
Mathias Agopianb4b17302013-03-20 18:36:41 -0700368 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700369 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371 property_get("debug.sf.showupdates", value, "0");
372 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700374 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000375
376 // DDMS debugging deprecated (b/120782499)
377 property_get("debug.sf.ddms", value, "0");
378 int debugDdms = atoi(value);
379 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700380
381 property_get("debug.sf.disable_backpressure", value, "0");
382 mPropagateBackpressure = !atoi(value);
383 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700384
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800385 property_get("debug.sf.enable_hwc_vds", value, "0");
386 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800387 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800388
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800389 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800390 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700392
Yiwei Zhang243b3782018-05-15 17:40:04 -0700393 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700394 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
395 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
396
Ana Krulec98b5b242018-08-10 15:03:23 -0700397 property_get("debug.sf.use_scheduler", value, "0");
398 mUseScheduler = atoi(value);
399
Ady Abrahamc3e21312019-02-07 14:30:23 -0800400 if (!mUseScheduler) {
401 mPrimaryDispSync =
402 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
403 SurfaceFlinger::dispSyncPresentTimeOffset);
404 }
405
Ana Krulec757f63a2019-01-25 10:46:18 -0800406 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
407 mVsyncModulator.setPhaseOffsets(early, gl, late);
Dan Stoza84d619e2018-03-28 17:07:36 -0700408
Romain Guy11d63f42017-07-20 12:47:14 -0700409 // We should be reading 'persist.sys.sf.color_saturation' here
410 // but since /data may be encrypted, we need to wait until after vold
411 // comes online to attempt to read the property. The property is
412 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800413
414 if (useTrebleTestingOverride()) {
415 // Without the override SurfaceFlinger cannot connect to HIDL
416 // services that are not listed in the manifests. Considered
417 // deriving the setting from the set service name, but it
418 // would be brittle if the name that's not 'default' is used
419 // for production purposes later on.
420 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422}
423
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424void SurfaceFlinger::onFirstRef()
425{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800426 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427}
428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800429SurfaceFlinger::~SurfaceFlinger()
430{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431}
432
Dan Stozac7014012014-02-14 15:03:43 -0800433void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434{
435 // the window manager died on us. prepare its eulogy.
436
Andy McFadden13a082e2012-08-24 10:16:42 -0700437 // restore initial conditions (default device unblank, etc)
438 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439
440 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700441 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442}
443
Robert Carr1db73f62016-12-21 12:58:51 -0800444static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700445 status_t err = client->initCheck();
446 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800447 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800448 }
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return nullptr;
450}
451
452sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
453 return initClient(new Client(this));
454}
455
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700456sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
457 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458{
459 class DisplayToken : public BBinder {
460 sp<SurfaceFlinger> flinger;
461 virtual ~DisplayToken() {
462 // no more references, this display must be terminated
463 Mutex::Autolock _l(flinger->mStateLock);
464 flinger->mCurrentState.displays.removeItem(this);
465 flinger->setTransactionFlags(eDisplayTransactionNeeded);
466 }
467 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700468 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700469 : flinger(flinger) {
470 }
471 };
472
473 sp<BBinder> token = new DisplayToken(this);
474
475 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 // Display ID is assigned when virtual display is allocated by HWC.
477 DisplayDeviceState state;
478 state.isSecure = secure;
479 state.displayName = displayName;
480 mCurrentState.displays.add(token, state);
481 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700482 return token;
483}
484
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 Mutex::Autolock _l(mStateLock);
487
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
489 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700490 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 return;
492 }
493
Dominik Laskowski075d3172018-05-24 15:50:06 -0700494 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
495 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 ALOGE("destroyDisplay called for non-virtual display");
497 return;
498 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499 mInterceptor->saveDisplayDeletion(state.sequenceId);
500 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700501 setTransactionFlags(eDisplayTransactionNeeded);
502}
503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
505 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700506
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800507 const auto internalDisplayId = getInternalDisplayIdLocked();
508 if (!internalDisplayId) {
509 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510 }
511
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800512 std::vector<PhysicalDisplayId> displayIds;
513 displayIds.reserve(mPhysicalDisplayTokens.size());
514 displayIds.push_back(internalDisplayId->value);
515
516 for (const auto& [id, token] : mPhysicalDisplayTokens) {
517 if (id != *internalDisplayId) {
518 displayIds.push_back(id.value);
519 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700520 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700521
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800522 return displayIds;
523}
524
525sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
526 Mutex::Autolock lock(mStateLock);
527 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700528}
529
Ady Abraham37965d42018-11-01 13:43:32 -0700530status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
531 if (!outGetColorManagement) {
532 return BAD_VALUE;
533 }
534 *outGetColorManagement = useColorManagement;
535 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700536}
537
Lloyd Pique441d5042018-10-18 16:49:51 -0700538HWComposer& SurfaceFlinger::getHwComposer() const {
539 return mCompositionEngine->getHwComposer();
540}
541
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700542renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
543 return mCompositionEngine->getRenderEngine();
544}
545
Lloyd Pique70d91362018-10-18 16:02:55 -0700546compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
547 return *mCompositionEngine.get();
548}
549
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550void SurfaceFlinger::bootFinished()
551{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700552 if (mStartPropertySetThread->join() != NO_ERROR) {
553 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800554 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555 const nsecs_t now = systemTime();
556 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000557 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558
559 // wait patiently for the window manager death
560 const String16 name("window");
561 sp<IBinder> window(defaultServiceManager()->getService(name));
562 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700563 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700564 }
Robert Carr720e5062018-07-30 17:45:14 -0700565 sp<IBinder> input(defaultServiceManager()->getService(
566 String16("inputflinger")));
567 if (input == nullptr) {
568 ALOGE("Failed to link to input service");
569 } else {
570 mInputFlinger = interface_cast<IInputFlinger>(input);
571 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700572
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 if (mVrFlinger) {
574 mVrFlinger->OnBootFinished();
575 }
576
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700577 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700578 // formerly we would just kill the process, but we now ask it to exit so it
579 // can choose where to stop the animation.
580 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700581
582 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
583 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
584 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700585
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800586 postMessageAsync(new LambdaMessage([this] {
587 readPersistentProperties();
588 mBootStage = BootStage::FINISHED;
589 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800590}
591
Dan Stoza436ccf32018-06-21 12:10:12 -0700592uint32_t SurfaceFlinger::getNewTexture() {
593 {
594 std::lock_guard lock(mTexturePoolMutex);
595 if (!mTexturePool.empty()) {
596 uint32_t name = mTexturePool.back();
597 mTexturePool.pop_back();
598 ATRACE_INT("TexturePoolSize", mTexturePool.size());
599 return name;
600 }
601
602 // The pool was too small, so increase it for the future
603 ++mTexturePoolSize;
604 }
605
606 // The pool was empty, so we need to get a new texture name directly using a
607 // blocking call to the main thread
608 uint32_t name = 0;
609 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
610 return name;
611}
612
Mathias Agopian3f844832013-08-07 21:24:32 -0700613void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700614 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700615}
616
Wei Wangf9b05ee2017-07-19 20:59:39 -0700617// Do not call property_set on main thread which will be blocked by init
618// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700619void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700620 ALOGI( "SurfaceFlinger's main thread ready to run. "
621 "Initializing graphics H/W...");
622
Ana Krulec757f63a2019-01-25 10:46:18 -0800623 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626
Dominik Laskowski83b88212018-12-11 13:34:06 -0800627 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -0800628
Steven Thomasb02664d2017-07-26 18:48:28 -0700629 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700630 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800631 mScheduler = getFactory().createScheduler(
632 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
633
Ana Krulec757f63a2019-01-25 10:46:18 -0800634 // TODO(b/113612090): Currently we assume that if scheduler is turned on, then the refresh
635 // rate is 90. Once b/122905403 is completed, this should be updated accordingly.
636 mPhaseOffsets->setRefreshRateType(
637 scheduler::RefreshRateConfigs::RefreshRateType::PERFORMANCE);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700638
Ana Krulec98b5b242018-08-10 15:03:23 -0700639 mAppConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800640 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800641 resyncCallback,
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 impl::EventThread::InterceptVSyncsCallback());
643 mSfConnectionHandle =
Ady Abraham3aff9172019-02-07 19:10:26 -0800644 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abrahama1a49af2019-02-07 14:36:55 -0800645 resyncCallback, [this](nsecs_t timestamp) {
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 mInterceptor->saveVSyncEvent(timestamp);
647 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800648
Ana Krulec98b5b242018-08-10 15:03:23 -0700649 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700650 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
651 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700652 } else {
653 mEventThreadSource =
654 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800655 mPhaseOffsets->getCurrentAppOffset(), true, "app");
Ana Krulec98b5b242018-08-10 15:03:23 -0700656 mEventThread =
657 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700658 impl::EventThread::InterceptVSyncsCallback(),
659 "appEventThread");
660 mSfEventThreadSource =
661 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Ana Krulec757f63a2019-01-25 10:46:18 -0800662 mPhaseOffsets->getCurrentSfOffset(), true, "sf");
Ana Krulec98b5b242018-08-10 15:03:23 -0700663
664 mSFEventThread =
665 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Ana Krulec98b5b242018-08-10 15:03:23 -0700666 [this](nsecs_t timestamp) {
667 mInterceptor->saveVSyncEvent(timestamp);
668 },
669 "sfEventThread");
Dominik Laskowskif654d572018-12-20 11:03:06 -0800670 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Ana Krulec98b5b242018-08-10 15:03:23 -0700671 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673
Steven Thomasb02664d2017-07-26 18:48:28 -0700674 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700675 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700676 renderEngineFeature |= (useColorManagement ?
677 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700678 renderEngineFeature |= (useContextPriority ?
679 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700680
681 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700682 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700683 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700684 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700685
686 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
687 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700688 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
689 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800690 // Process any initial hotplug and resulting display changes.
691 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700692 const auto display = getDefaultDisplayDeviceLocked();
693 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700694 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700695 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800696
Steven Thomas050b2c82017-03-06 11:45:16 -0800697 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700698 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700699 // This callback is called from the vr flinger dispatch thread. We
700 // need to call signalTransaction(), which requires holding
701 // mStateLock when we're not on the main thread. Acquiring
702 // mStateLock from the vr flinger dispatch thread might trigger a
703 // deadlock in surface flinger (see b/66916578), so post a message
704 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700705 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700706 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
707 mVrFlingerRequestsDisplay = requestDisplay;
708 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700709 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800710 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700711 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
712 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700713 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700714 .value_or(0),
715 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800716 if (!mVrFlinger) {
717 ALOGE("Failed to start vrflinger");
718 }
719 }
720
Ady Abrahamc3e21312019-02-07 14:30:23 -0800721 if (!mUseScheduler) {
722 mEventControlThread = getFactory().createEventControlThread(
723 [this](bool enabled) { setPrimaryVsyncEnabled(enabled); });
724 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700725
Mathias Agopian92a979a2012-08-02 18:32:23 -0700726 // initialize our drawing state
727 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700728
Andy McFadden13a082e2012-08-24 10:16:42 -0700729 // set initial conditions (e.g. unblank default device)
730 initializeDisplays();
731
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700732 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700733
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700735
736 const bool presentFenceReliable =
737 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
738 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739
740 if (mStartPropertySetThread->Start() != NO_ERROR) {
741 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800742 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800743
Ana Krulec7d1d6832018-12-27 11:10:09 -0800744 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800745 mScheduler->setExpiredIdleTimerCallback([this] {
746 Mutex::Autolock lock(mStateLock);
747 setRefreshRateTo(RefreshRateType::DEFAULT);
Ana Krulec757f63a2019-01-25 10:46:18 -0800748 });
Ady Abrahama1a49af2019-02-07 14:36:55 -0800749 mScheduler->setResetIdleTimerCallback([this] {
750 Mutex::Autolock lock(mStateLock);
751 setRefreshRateTo(RefreshRateType::PERFORMANCE);
752 });
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800753
Alec Mourifb571ea2019-01-24 18:42:10 -0800754 mRefreshRateStats =
755 std::make_unique<scheduler::RefreshRateStats>(getHwComposer().getConfigs(
756 *display->getId()),
757 mTimeStats);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800758 }
759
Dan Stoza9e56aa02015-11-02 13:00:03 -0800760 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700761}
762
Romain Guy11d63f42017-07-20 12:47:14 -0700763void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700764 Mutex::Autolock _l(mStateLock);
765
Romain Guy11d63f42017-07-20 12:47:14 -0700766 char value[PROPERTY_VALUE_MAX];
767
768 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800769 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700770 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800771 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100772
773 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700774 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700775}
776
Mathias Agopiana67e4182012-06-19 17:26:12 -0700777void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800778 // Start boot animation service by setting a property mailbox
779 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700780 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800781 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700782 if (mStartPropertySetThread->join() != NO_ERROR) {
783 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800784 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
Mathias Agopian875d8e12013-06-07 15:35:48 -0700791size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700792 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700793}
794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800796
Jamie Gennis582270d2011-08-17 18:19:00 -0700797bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800798 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800799 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800800 return authenticateSurfaceTextureLocked(bufferProducer);
801}
802
803bool SurfaceFlinger::authenticateSurfaceTextureLocked(
804 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800805 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800806 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800807}
808
Brian Anderson6b376712017-04-04 10:51:39 -0700809status_t SurfaceFlinger::getSupportedFrameTimestamps(
810 std::vector<FrameEvent>* outSupported) const {
811 *outSupported = {
812 FrameEvent::REQUESTED_PRESENT,
813 FrameEvent::ACQUIRE,
814 FrameEvent::LATCH,
815 FrameEvent::FIRST_REFRESH_START,
816 FrameEvent::LAST_REFRESH_START,
817 FrameEvent::GPU_COMPOSITION_DONE,
818 FrameEvent::DEQUEUE_READY,
819 FrameEvent::RELEASE,
820 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700821 ConditionalLock _l(mStateLock,
822 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700823 if (!getHwComposer().hasCapability(
824 HWC2::Capability::PresentFenceIsNotReliable)) {
825 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
826 }
827 return NO_ERROR;
828}
829
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800830status_t SurfaceFlinger::getDisplayConfigsLocked(const sp<IBinder>& displayToken,
831 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700832 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 return BAD_VALUE;
834 }
835
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800836 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700837 if (!displayId) {
838 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700839 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 // TODO: Not sure if display density should handled by SF any longer
842 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700845 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800846 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700847 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700848 }
849 return density;
850 }
851 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700852 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700854 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700855 return getDensityFromProperty("ro.sf.lcd_density"); }
856 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700857
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700859
Dominik Laskowski075d3172018-05-24 15:50:06 -0700860 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 DisplayInfo info = DisplayInfo();
862
Dan Stoza9e56aa02015-11-02 13:00:03 -0800863 float xdpi = hwConfig->getDpiX();
864 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700865
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700866 info.w = hwConfig->getWidth();
867 info.h = hwConfig->getHeight();
868 // Default display viewport to display width and height
869 info.viewportW = info.w;
870 info.viewportH = info.h;
871
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800872 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700873 // The density of the device is provided by a build property
874 float density = Density::getBuildDensity() / 160.0f;
875 if (density == 0) {
876 // the build doesn't provide a density -- this is wrong!
877 // use xdpi instead
878 ALOGE("ro.sf.lcd_density must be defined as a build property");
879 density = xdpi / 160.0f;
880 }
881 if (Density::getEmuDensity()) {
882 // if "qemu.sf.lcd_density" is specified, it overrides everything
883 xdpi = ydpi = density = Density::getEmuDensity();
884 density /= 160.0f;
885 }
886 info.density = density;
887
888 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889 const auto display = getDefaultDisplayDeviceLocked();
890 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700891
892 // This is for screenrecord
893 const Rect viewport = display->getViewport();
894 if (viewport.isValid()) {
895 info.viewportW = uint32_t(viewport.getWidth());
896 info.viewportH = uint32_t(viewport.getHeight());
897 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 } else {
899 // TODO: where should this value come from?
900 static const int TV_DENSITY = 213;
901 info.density = TV_DENSITY / 160.0f;
902 info.orientation = 0;
903 }
904
Dan Stoza7f7da322014-05-02 15:26:25 -0700905 info.xdpi = xdpi;
906 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ana Krulec757f63a2019-01-25 10:46:18 -0800908 info.appVsyncOffset = mPhaseOffsets->getCurrentAppOffset();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909
Andy McFadden91b2ca82014-06-13 14:04:23 -0700910 // This is how far in advance a buffer must be queued for
911 // presentation at a given time. If you want a buffer to appear
912 // on the screen at time N, you must submit the buffer before
913 // (N - presentationDeadline).
914 //
915 // Normally it's one full refresh period (to give SF a chance to
916 // latch the buffer), but this can be reduced by configuring a
917 // DispSync offset. Any additional delays introduced by the hardware
918 // composer or panel must be accounted for here.
919 //
920 // We add an additional 1ms to allow for processing time and
921 // differences between the ideal and actual refresh rate.
Ana Krulec757f63a2019-01-25 10:46:18 -0800922 info.presentationDeadline =
923 hwConfig->getVsyncPeriod() - mPhaseOffsets->getCurrentSfOffset() + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700924
925 // All non-virtual displays are currently considered secure.
926 info.secure = true;
927
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800928 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700929 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800930 std::swap(info.w, info.h);
931 }
932
Michael Wright28f24d02016-07-12 13:30:53 -0700933 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700934 }
935
Dan Stoza7f7da322014-05-02 15:26:25 -0700936 return NO_ERROR;
937}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
940 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700941 return BAD_VALUE;
942 }
943
Ana Krulece588e312018-09-18 12:32:24 -0700944 if (mUseScheduler) {
945 mScheduler->getDisplayStatInfo(stats);
946 } else {
947 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
948 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
949 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700950 return NO_ERROR;
951}
952
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700953int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
954 const auto display = getDisplayDevice(displayToken);
955 if (!display) {
956 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800957 return BAD_VALUE;
958 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700961}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700962
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963void SurfaceFlinger::setDesiredActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800965
Ana Krulec7d1d6832018-12-27 11:10:09 -0800966 Vector<DisplayInfo> configs;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800967 // Lock is acquired by setRefreshRateTo.
968 getDisplayConfigsLocked(displayToken, &configs);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800969 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
970 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
971 return;
972 }
973
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 // Lock is acquired by setRefreshRateTo.
975 const auto display = getDisplayDeviceLocked(displayToken);
Ana Krulec7d1d6832018-12-27 11:10:09 -0800976 if (!display) {
977 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
978 displayToken.get());
979 return;
980 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700981 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800982 ALOGW("Attempt to set active config %d for virtual display", mode);
983 return;
984 }
985 int currentDisplayPowerMode = display->getPowerMode();
986 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
987 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 return;
989 }
990
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991 // Don't check against the current mode yet. Worst case we set the desired
992 // config twice.
993 {
994 std::lock_guard<std::mutex> lock(mActiveConfigLock);
995 mDesiredActiveConfig = ActiveConfigInfo{mode, displayToken};
996 }
997 // This will trigger HWC refresh without resetting the idle timer.
998 repaintEverythingForHWC();
999}
1000
1001status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1002 ATRACE_CALL();
1003 postMessageSync(new LambdaMessage(
1004 [&]() NO_THREAD_SAFETY_ANALYSIS { setDesiredActiveConfig(displayToken, mode); }));
1005 return NO_ERROR;
1006}
1007
1008void SurfaceFlinger::setActiveConfigInHWC() {
1009 ATRACE_CALL();
1010
1011 const auto display = getDisplayDevice(mUpcomingActiveConfig.displayToken);
1012 if (!display) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001013 return;
1014 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001015 const auto displayId = display->getId();
1016 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001017
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001018 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1019 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1020 mSetActiveConfigState = SetActiveConfigState::NOTIFIED_HWC;
1021 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1022}
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001023
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001024void SurfaceFlinger::setActiveConfigInternal() {
1025 ATRACE_CALL();
1026
1027 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1028 if (mUseScheduler) {
1029 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
1030 }
1031
1032 const auto display = getDisplayDeviceLocked(mUpcomingActiveConfig.displayToken);
1033 display->setActiveConfig(mUpcomingActiveConfig.configId);
1034
1035 mSetActiveConfigState = SetActiveConfigState::NONE;
1036 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1037
Dominik Laskowski83b88212018-12-11 13:34:06 -08001038 resyncToHardwareVsync(true, getVsyncPeriod());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
1040}
1041
1042bool SurfaceFlinger::updateSetActiveConfigStateMachine() NO_THREAD_SAFETY_ANALYSIS {
1043 // Store the local variable to release the lock.
1044 ActiveConfigInfo desiredActiveConfig;
1045 {
1046 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1047 desiredActiveConfig = mDesiredActiveConfig;
1048 }
1049
1050 const auto display = getDisplayDevice(desiredActiveConfig.displayToken);
1051 if (display) {
1052 if (mSetActiveConfigState == SetActiveConfigState::NONE &&
1053 display->getActiveConfig() != desiredActiveConfig.configId) {
1054 // Step 1) Desired active config was set, it is different than the
1055 // config currently in use. Notify HWC.
1056 mUpcomingActiveConfig = desiredActiveConfig;
1057 setActiveConfigInHWC();
1058 } else if (mSetActiveConfigState == SetActiveConfigState::NOTIFIED_HWC) {
1059 // Step 2) HWC was notified and we received refresh from it.
1060 mSetActiveConfigState = SetActiveConfigState::REFRESH_RECEIVED;
1061 ATRACE_INT("SetActiveConfigState", mSetActiveConfigState);
1062 repaintEverythingForHWC();
1063 // We do not want to give another frame to HWC while we are transitioning.
1064 return false;
1065 } else if (mSetActiveConfigState == SetActiveConfigState::REFRESH_RECEIVED &&
1066 !(mPreviousPresentFence != Fence::NO_FENCE &&
1067 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled))) {
1068 // Step 3) We received the present fence from the HWC, so we assume it
1069 // successfully updated the config, hence we update SF.
1070 setActiveConfigInternal();
1071 // If the config changed again while we were transitioning, restart the
1072 // process.
1073 if (desiredActiveConfig != mUpcomingActiveConfig) {
1074 mUpcomingActiveConfig = desiredActiveConfig;
1075 setActiveConfigInHWC(); // sets the state to NOTIFY_HWC
1076 }
1077 }
1078 }
1079 return true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001080}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1083 Vector<ColorMode>* outColorModes) {
1084 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001089 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001090 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1091
1092 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1093 if (!displayId) {
1094 return NAME_NOT_FOUND;
1095 }
1096
Dominik Laskowski075d3172018-05-24 15:50:06 -07001097 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001098 }
Michael Wright28f24d02016-07-12 13:30:53 -07001099 outColorModes->clear();
1100 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1101
1102 return NO_ERROR;
1103}
1104
Daniel Solomon42d04562019-01-20 21:03:19 -08001105status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1106 ui::DisplayPrimaries &primaries) {
1107 if (!displayToken) {
1108 return BAD_VALUE;
1109 }
1110
1111 // Currently we only support this API for a single internal display.
1112 if (getInternalDisplayToken() != displayToken) {
1113 return BAD_VALUE;
1114 }
1115
1116 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1117 return NO_ERROR;
1118}
1119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1121 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001122 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001123 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001124 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001125}
1126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001127status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001128 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129 Vector<ColorMode> modes;
1130 getDisplayColorModes(displayToken, &modes);
1131 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1132 if (mode < ColorMode::NATIVE || !exists) {
1133 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1134 decodeColorMode(mode).c_str(), mode, displayToken.get());
1135 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001136 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 const auto display = getDisplayDevice(displayToken);
1138 if (!display) {
1139 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1140 decodeColorMode(mode).c_str(), mode, displayToken.get());
1141 } else if (display->isVirtual()) {
1142 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1143 decodeColorMode(mode).c_str(), mode);
1144 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001145 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1146 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 }
1148 }));
1149
Michael Wright28f24d02016-07-12 13:30:53 -07001150 return NO_ERROR;
1151}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001152
Svetoslavd85084b2014-03-20 10:28:31 -07001153status_t SurfaceFlinger::clearAnimationFrameStats() {
1154 Mutex::Autolock _l(mStateLock);
1155 mAnimFrameTracker.clearStats();
1156 return NO_ERROR;
1157}
1158
1159status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1160 Mutex::Autolock _l(mStateLock);
1161 mAnimFrameTracker.getStats(outStats);
1162 return NO_ERROR;
1163}
1164
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1166 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001167 Mutex::Autolock _l(mStateLock);
1168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169 const auto display = getDisplayDeviceLocked(displayToken);
1170 if (!display) {
1171 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001172 return BAD_VALUE;
1173 }
1174
Peiyong Linfb069302018-04-25 14:34:31 -07001175 // At this point the DisplayDeivce should already be set up,
1176 // meaning the luminance information is already queried from
1177 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001178 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001179 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1180 capabilities.getDesiredMaxLuminance(),
1181 capabilities.getDesiredMaxAverageLuminance(),
1182 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001183
1184 return NO_ERROR;
1185}
1186
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001187status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1188 ui::PixelFormat* outFormat,
1189 ui::Dataspace* outDataspace,
1190 uint8_t* outComponentMask) const {
1191 if (!outFormat || !outDataspace || !outComponentMask) {
1192 return BAD_VALUE;
1193 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001194 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001195 if (!display || !display->getId()) {
1196 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1197 return BAD_VALUE;
1198 }
1199 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1200 outDataspace, outComponentMask);
1201}
1202
Kevin DuBois74e53772018-11-19 10:52:38 -08001203status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1204 bool enable, uint8_t componentMask,
1205 uint64_t maxFrames) const {
1206 const auto display = getDisplayDevice(displayToken);
1207 if (!display || !display->getId()) {
1208 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1209 return BAD_VALUE;
1210 }
1211
1212 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1213 componentMask, maxFrames);
1214}
1215
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001216status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1217 uint64_t maxFrames, uint64_t timestamp,
1218 DisplayedFrameStats* outStats) const {
1219 const auto display = getDisplayDevice(displayToken);
1220 if (!display || !display->getId()) {
1221 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1222 return BAD_VALUE;
1223 }
1224
1225 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1226 outStats);
1227}
1228
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001229status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1230 if (!outSupported) {
1231 return BAD_VALUE;
1232 }
1233 *outSupported = getRenderEngine().supportsProtectedContent();
1234 return NO_ERROR;
1235}
1236
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001237status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1238 bool* outIsWideColorDisplay) const {
1239 if (!displayToken || !outIsWideColorDisplay) {
1240 return BAD_VALUE;
1241 }
1242 Mutex::Autolock _l(mStateLock);
1243 const auto display = getDisplayDeviceLocked(displayToken);
1244 if (!display) {
1245 return BAD_VALUE;
1246 }
1247 *outIsWideColorDisplay = display->hasWideColorGamut();
1248 return NO_ERROR;
1249}
1250
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001252 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001253 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 if (mInjectVSyncs == enable) {
1256 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001258
Dominik Laskowski83b88212018-12-11 13:34:06 -08001259 auto resyncCallback = makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001260
Ana Krulec98b5b242018-08-10 15:03:23 -07001261 // TODO(akrulec): Part of the Injector should be refactored, so that it
1262 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001263 if (enable) {
1264 ALOGV("VSync Injections enabled");
1265 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001266 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001267 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001268 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001269 impl::EventThread::InterceptVSyncsCallback(),
1270 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001272 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273 } else {
1274 ALOGV("VSync Injections disabled");
Dominik Laskowskif654d572018-12-20 11:03:06 -08001275 mEventQueue->setEventThread(mSFEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001276 }
1277
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001278 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001279 }));
1280
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001281 return NO_ERROR;
1282}
1283
1284status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001285 Mutex::Autolock _l(mStateLock);
1286
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001287 if (!mInjectVSyncs) {
1288 ALOGE("VSync Injections not enabled");
1289 return BAD_VALUE;
1290 }
1291 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1292 ALOGV("Injecting VSync inside SurfaceFlinger");
1293 mVSyncInjector->onInjectSyncEvent(when);
1294 }
1295 return NO_ERROR;
1296}
1297
Lloyd Pique755e3192018-01-31 16:46:15 -08001298status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1299 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001300 // Try to acquire a lock for 1s, fail gracefully
1301 const status_t err = mStateLock.timedLock(s2ns(1));
1302 const bool locked = (err == NO_ERROR);
1303 if (!locked) {
1304 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1305 return TIMED_OUT;
1306 }
1307
1308 outLayers->clear();
1309 mCurrentState.traverseInZOrder([&](Layer* layer) {
1310 outLayers->push_back(layer->getLayerDebugInfo());
1311 });
1312
1313 mStateLock.unlock();
1314 return NO_ERROR;
1315}
1316
Peiyong Linc6780972018-10-28 15:24:08 -07001317status_t SurfaceFlinger::getCompositionPreference(
1318 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1319 Dataspace* outWideColorGamutDataspace,
1320 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001321 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001322 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001323 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001324 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001325 return NO_ERROR;
1326}
1327
Dan Stoza84ab9372018-12-17 15:27:57 -08001328status_t SurfaceFlinger::addRegionSamplingListener(
1329 const Rect& /*samplingArea*/, const sp<IBinder>& /*stopLayerHandle*/,
1330 const sp<IRegionSamplingListener>& /*listener*/) {
1331 return NO_ERROR;
1332}
1333
1334status_t SurfaceFlinger::removeRegionSamplingListener(
1335 const sp<IRegionSamplingListener>& /*listener*/) {
1336 return NO_ERROR;
1337}
1338
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001339// ----------------------------------------------------------------------------
1340
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001341sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1342 ISurfaceComposer::VsyncSource vsyncSource) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001343 auto resyncCallback = makeResyncCallback([this] {
1344 Mutex::Autolock lock(mStateLock);
1345 return getVsyncPeriod();
1346 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001347
Ana Krulec98b5b242018-08-10 15:03:23 -07001348 if (mUseScheduler) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001349 const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle
1350 : mAppConnectionHandle;
1351
Ady Abrahama1a49af2019-02-07 14:36:55 -08001352 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001353 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001354 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001355 return mSFEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001356 } else {
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001357 return mEventThread->createEventConnection(resyncCallback, ResetIdleTimerCallback());
Ana Krulec98b5b242018-08-10 15:03:23 -07001358 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001359 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001360}
1361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001362// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001363
1364void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001365 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001366}
1367
1368void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001369 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001370}
1371
1372void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001373 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001374}
1375
1376void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001377 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001378 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001379}
1380
1381status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001382 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001383 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001384}
1385
1386status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001387 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001388 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001389 if (res == NO_ERROR) {
1390 msg->wait();
1391 }
1392 return res;
1393}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001394
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001395void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001396 do {
1397 waitForEvent();
1398 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001399}
1400
Dominik Laskowski83b88212018-12-11 13:34:06 -08001401nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001402 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001403 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1404 return 0;
1405 }
1406
1407 const auto config = getHwComposer().getActiveConfig(*displayId);
1408 return config ? config->getVsyncPeriod() : 0;
1409}
1410
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001411void SurfaceFlinger::enableHardwareVsync() {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001412 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001413 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001414 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001415 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001416 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001417 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001418 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001419}
1420
Dominik Laskowski83b88212018-12-11 13:34:06 -08001421void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001422 Mutex::Autolock _l(mHWVsyncLock);
Ady Abraham3aff9172019-02-07 19:10:26 -08001423 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1424 if (mUseScheduler) {
1425 if (makeAvailable) {
Ana Krulec7ab56032018-11-02 20:51:06 +01001426 mScheduler->makeHWSyncAvailable(true);
Ady Abraham3aff9172019-02-07 19:10:26 -08001427 } else if (!mScheduler->getHWSyncAvailable()) {
1428 // Hardware vsync is not currently available, so abort the resync
1429 // attempt for now
1430 return;
Ana Krulec7ab56032018-11-02 20:51:06 +01001431 }
Ady Abraham3aff9172019-02-07 19:10:26 -08001432 } else {
1433 if (makeAvailable) {
1434 mHWVsyncAvailable = true;
1435 } else if (!mHWVsyncAvailable) {
1436 // Hardware vsync is not currently available, so abort the resync
1437 // attempt for now
1438 return;
1439 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001440 }
1441
Dominik Laskowski83b88212018-12-11 13:34:06 -08001442 if (period <= 0) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001443 return;
1444 }
1445
Ana Krulece588e312018-09-18 12:32:24 -07001446 if (mUseScheduler) {
1447 mScheduler->setVsyncPeriod(period);
1448 } else {
1449 mPrimaryDispSync->reset();
1450 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001451
Ana Krulece588e312018-09-18 12:32:24 -07001452 if (!mPrimaryHWVsyncEnabled) {
1453 mPrimaryDispSync->beginResync();
1454 mEventControlThread->setVsyncEnabled(true);
1455 mPrimaryHWVsyncEnabled = true;
1456 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001457 }
1458}
1459
Jesse Hall948fe0c2013-10-14 12:56:09 -07001460void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08001461 assert(!mUseScheduler);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001462 Mutex::Autolock _l(mHWVsyncLock);
1463 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001464 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001465 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001466 mPrimaryHWVsyncEnabled = false;
1467 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001468 if (makeUnavailable) {
1469 mHWVsyncAvailable = false;
1470 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001471}
1472
Dominik Laskowski83b88212018-12-11 13:34:06 -08001473void SurfaceFlinger::VsyncState::resync(const GetVsyncPeriod& getVsyncPeriod) {
Tim Murray4a4e4a22016-04-19 16:29:23 +00001474 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001475
Dan Stoza57164302017-05-08 14:03:54 -07001476 const nsecs_t now = systemTime();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001477 const nsecs_t last = lastResyncTime.exchange(now);
1478
1479 if (now - last > kIgnoreDelay) {
1480 flinger.resyncToHardwareVsync(false, getVsyncPeriod());
Tim Murray4a4e4a22016-04-19 16:29:23 +00001481 }
1482}
1483
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001484void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1485 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001486 ATRACE_NAME("SF onVsync");
1487
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001490 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 return;
1492 }
1493
Dominik Laskowski075d3172018-05-24 15:50:06 -07001494 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001495 return;
1496 }
1497
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001499 // For now, we don't do anything with external display vsyncs.
1500 return;
1501 }
1502
Ana Krulece588e312018-09-18 12:32:24 -07001503 if (mUseScheduler) {
1504 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001505 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001506 bool needsHwVsync = false;
1507 { // Scope for the lock
1508 Mutex::Autolock _l(mHWVsyncLock);
1509 if (mPrimaryHWVsyncEnabled) {
1510 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1511 }
1512 }
1513
1514 if (needsHwVsync) {
1515 enableHardwareVsync();
1516 } else {
1517 disableHardwareVsync(false);
1518 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001519 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001520}
1521
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001522void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001523 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1524 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001525}
1526
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001527void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate) {
1528 mPhaseOffsets->setRefreshRateType(refreshRate);
1529
1530 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
1531 mVsyncModulator.setPhaseOffsets(early, gl, late);
1532
1533 if (mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001534 return;
1535 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001536
Ana Krulec7d1d6832018-12-27 11:10:09 -08001537 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1538 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1539 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1540 // refresh cycle.
1541
1542 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001543 const nsecs_t currentVsyncPeriod = getVsyncPeriod();
Ana Krulec7d1d6832018-12-27 11:10:09 -08001544 if (currentVsyncPeriod == 0) {
1545 return;
1546 }
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001547
Ana Krulec7d1d6832018-12-27 11:10:09 -08001548 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1549 // floating numbers.
1550 const float currentFps = 1e9 / currentVsyncPeriod;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001551 const float newFps = refreshRate == RefreshRateType::PERFORMANCE ? kPerformanceRefreshRate
1552 : kDefaultRefreshRate;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001553 if (std::abs(currentFps - newFps) <= 1) {
1554 return;
1555 }
1556
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001557 const auto displayId = getInternalDisplayIdLocked();
1558 LOG_ALWAYS_FATAL_IF(!displayId);
1559
1560 auto configs = getHwComposer().getConfigs(*displayId);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001561 for (int i = 0; i < configs.size(); i++) {
1562 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1563 if (vsyncPeriod == 0) {
1564 continue;
1565 }
1566 const float fps = 1e9 / vsyncPeriod;
1567 // TODO(b/113612090): There should be a better way at determining which config
1568 // has the right refresh rate.
1569 if (std::abs(fps - newFps) <= 1) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001570 setDesiredActiveConfig(getInternalDisplayTokenLocked(), i);
Ana Krulec7d1d6832018-12-27 11:10:09 -08001571 }
1572 }
1573}
1574
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001575void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001576 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001577 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001578 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001579
Lloyd Piqueba04e622017-12-14 17:11:26 -08001580 // Ignore events that do not have the right sequenceId.
1581 if (sequenceId != getBE().mComposerSequenceId) {
1582 return;
1583 }
1584
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Only lock if we're not on the main thread. This function is normally
1586 // called on a hwbinder thread, but for the primary display it's called on
1587 // the main thread with the state lock already held, so don't attempt to
1588 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001589 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001590
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001591 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001592
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001593 if (std::this_thread::get_id() == mMainThreadId) {
1594 // Process all pending hot plug events immediately if we are on the main thread.
1595 processDisplayHotplugEventsLocked();
1596 }
1597
Lloyd Piqueba04e622017-12-14 17:11:26 -08001598 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001599}
1600
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001601void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001602 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001603 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001604 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001605 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001606 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001607}
1608
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001609void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001610 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001611 Mutex::Autolock lock(mStateLock);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001612 if (const auto displayId = getInternalDisplayIdLocked()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001613 getHwComposer().setVsyncEnabled(*displayId,
1614 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1615 }
Mathias Agopian86303202012-07-24 22:46:10 -07001616}
1617
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001618// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001619void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001620 if (mUseScheduler) {
1621 mScheduler->disableHardwareVsync(true);
1622 } else {
1623 disableHardwareVsync(true);
1624 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001625 // Clear the drawing state so that the logic inside of
1626 // handleTransactionLocked will fire. It will determine the delta between
1627 // mCurrentState and mDrawingState and re-apply all changes when we make the
1628 // transition.
1629 mDrawingState.displays.clear();
1630 mDisplays.clear();
1631}
1632
Steven Thomas050b2c82017-03-06 11:45:16 -08001633void SurfaceFlinger::updateVrFlinger() {
1634 if (!mVrFlinger)
1635 return;
1636 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001637 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001638 return;
1639 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001640
Lloyd Pique441d5042018-10-18 16:49:51 -07001641 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 ALOGE("Vr flinger is only supported for remote hardware composer"
1643 " service connections. Ignoring request to transition to vr"
1644 " flinger.");
1645 mVrFlingerRequestsDisplay = false;
1646 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001647 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001648
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001649 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650
Steven Thomas0123ac62018-07-12 11:32:34 -07001651 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001652 LOG_ALWAYS_FATAL_IF(!display);
1653 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001654 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1655 // called below. Clear the reference now so we don't accidentally use it
1656 // later.
1657 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001658
Steven Thomasb02664d2017-07-26 18:48:28 -07001659 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001660 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001661 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001662
Steven Thomasb02664d2017-07-26 18:48:28 -07001663 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001664 // Delete the current instance before creating the new one
1665 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1666 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1667 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1668 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001669
Lloyd Pique441d5042018-10-18 16:49:51 -07001670 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001671 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001672
1673 if (vrFlingerRequestsDisplay) {
1674 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001675 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676
1677 mVisibleRegionsDirty = true;
1678 invalidateHwcGeometry();
1679
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001680 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001681 display = getDefaultDisplayDeviceLocked();
1682 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001683 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001684
Steven Thomasb02664d2017-07-26 18:48:28 -07001685 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001686 const nsecs_t vsyncPeriod = getVsyncPeriod();
1687 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001688
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001689 // The present fences returned from vr_hwc are not an accurate
1690 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001691 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001692 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1693 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001694 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001695 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001696 !hasSyncFramework);
1697 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001698
Steven Thomasb02664d2017-07-26 18:48:28 -07001699 // Use phase of 0 since phase is not known.
1700 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001701 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001702 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001703
Dominik Laskowski83b88212018-12-11 13:34:06 -08001704 resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001705
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001706 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001707 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001708}
1709
Mathias Agopian4fec8732012-06-29 14:12:52 -07001710void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001711 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001712 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001713 case MessageQueue::INVALIDATE: {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001714 if (!updateSetActiveConfigStateMachine()) {
1715 break;
1716 }
1717
Ana Krulec3084c052018-11-21 20:27:17 +01001718 if (mUseScheduler) {
1719 // This call is made each time SF wakes up and creates a new frame.
1720 mScheduler->incrementFrameCounter();
1721 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001722 bool frameMissed = !mHadClientComposition && mPreviousPresentFence != Fence::NO_FENCE &&
1723 (mPreviousPresentFence->getStatus() == Fence::Status::Unsignaled);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001724 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001725 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001726 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001727 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001728 if (mPropagateBackpressure) {
1729 signalLayerUpdate();
1730 break;
1731 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001732 }
Dan Stoza50182882016-07-08 12:02:20 -07001733
Steven Thomas050b2c82017-03-06 11:45:16 -08001734 // Now that we're going to make it to the handleMessageTransaction()
1735 // call below it's safe to call updateVrFlinger(), which will
1736 // potentially trigger a display handoff.
1737 updateVrFlinger();
1738
Dan Stoza6b9454d2014-11-07 16:00:59 -08001739 bool refreshNeeded = handleMessageTransaction();
1740 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001741
1742 updateCursorAsync();
1743 updateInputFlinger();
1744
Dan Stoza58784442014-12-02 16:58:17 -08001745 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001746 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001747 // Signal a refresh if a transaction modified the window state,
1748 // a new buffer was latched, or if HWC has requested a full
1749 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001750 signalRefresh();
1751 }
1752 break;
1753 }
1754 case MessageQueue::REFRESH: {
1755 handleMessageRefresh();
1756 break;
1757 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001758 }
1759}
1760
Dan Stoza6b9454d2014-11-07 16:00:59 -08001761bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001762 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001763
1764 // Apply any ready transactions in the queues if there are still transactions that have not been
1765 // applied, wake up during the next vsync period and check again
1766 bool transactionNeeded = false;
1767 if (!flushTransactionQueues()) {
1768 transactionNeeded = true;
1769 }
1770
Mathias Agopian4fec8732012-06-29 14:12:52 -07001771 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001772 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001774
1775 if (transactionNeeded) {
1776 setTransactionFlags(eTransactionNeeded);
1777 }
1778
1779 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001780}
1781
Mathias Agopian4fec8732012-06-29 14:12:52 -07001782void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001783 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001784
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001785 mRefreshPending = false;
1786
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001787 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001788 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001789 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001790 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001791 for (const auto& [token, display] : mDisplays) {
1792 beginFrame(display);
1793 prepareFrame(display);
1794 doDebugFlashRegions(display, repaintEverything);
1795 doComposition(display, repaintEverything);
1796 }
1797
Adrian Roos1e1a1282017-11-01 19:05:31 +01001798 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001799 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001800
1801 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001802 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001803
Dan Stozabfbffeb2016-07-21 14:49:33 -07001804 mHadClientComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001805 for (const auto& [token, displayDevice] : mDisplays) {
1806 auto display = displayDevice->getCompositionDisplay();
1807 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001808 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001809 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001810 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001811
Alec Mouri86770e52018-09-24 22:40:58 +00001812 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001813 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001814 if (mHadClientComposition) {
1815 base::unique_fd flushFence(getRenderEngine().flush());
1816 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1817 getBE().flushFence = new Fence(std::move(flushFence));
1818 } else {
1819 // Cleanup for hygiene.
1820 getBE().flushFence = Fence::NO_FENCE;
1821 }
1822 }
1823
Jorim Jaggi90535212018-05-23 23:44:06 +02001824 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001825
David Sodman7e4ae112018-02-09 15:02:28 -08001826 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman7e4ae112018-02-09 15:02:28 -08001827
1828 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001830
David Sodmanfa9b2af2017-12-24 13:28:59 -08001831
1832bool SurfaceFlinger::handleMessageInvalidate() {
1833 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001834 bool refreshNeeded = handlePageFlip();
1835
Vishnu Nair4351ad52019-02-11 14:13:02 -08001836 if (mVisibleRegionsDirty) {
1837 computeLayerBounds();
1838 }
1839
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001840 for (auto& layer : mLayersPendingRefresh) {
1841 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001842 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001843 invalidateLayerStack(layer, visibleReg);
1844 }
1845 mLayersPendingRefresh.clear();
1846 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001847}
1848
David Sodman79bba0e2018-08-05 18:07:49 -07001849void SurfaceFlinger::calculateWorkingSet() {
1850 ATRACE_CALL();
1851 ALOGV(__FUNCTION__);
1852
David Sodman79bba0e2018-08-05 18:07:49 -07001853 // build the h/w work list
1854 if (CC_UNLIKELY(mGeometryInvalid)) {
1855 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001856 for (const auto& [token, displayDevice] : mDisplays) {
1857 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001858 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001859 if (!displayId) {
1860 continue;
1861 }
David Sodman79bba0e2018-08-05 18:07:49 -07001862
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863 const Vector<sp<Layer>>& currentLayers = displayDevice->getVisibleLayersSortedByZ();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001864 for (size_t i = 0; i < currentLayers.size(); i++) {
1865 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001866
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001867 if (!layer->hasHwcLayer(displayDevice)) {
1868 if (!layer->createHwcLayer(&getHwComposer(), displayDevice)) {
1869 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001870 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001871 }
1872 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001873
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 layer->setGeometry(displayDevice, i);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001875 if (mDebugDisableHWC || mDebugRegion) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001876 layer->forceClientComposition(displayDevice);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001877 }
David Sodman79bba0e2018-08-05 18:07:49 -07001878 }
1879 }
1880 }
1881
1882 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001883 for (const auto& [token, displayDevice] : mDisplays) {
1884 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001885 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001886 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001887 continue;
1888 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001889 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001890
1891 if (mDrawingState.colorMatrixChanged) {
1892 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001893 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001894 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001895 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001896 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001897 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1898 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001899 !profile->hasHDR10Support()) {
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_HLG ||
1902 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001903 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001904 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001905 }
1906
Peiyong Lind3788632018-09-18 16:01:31 -07001907 // TODO(b/111562338) remove when composer 2.3 is shipped.
1908 if (layer->hasColorTransform()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001909 layer->forceClientComposition(displayDevice);
Peiyong Lind3788632018-09-18 16:01:31 -07001910 }
1911
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001912 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001913 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001914 }
1915
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001916 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001917 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001918 layer->setCompositionType(displayDevice,
1919 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001920 continue;
1921 }
1922
Lloyd Pique32cbe282018-10-19 13:09:22 -07001923 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001924 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Lloyd Pique32cbe282018-10-19 13:09:22 -07001925 displayDevice->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001926 }
1927
Peiyong Lin13effd12018-07-24 17:01:47 -07001928 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001929 ColorMode colorMode;
1930 Dataspace dataSpace;
1931 RenderIntent renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001932 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
Lloyd Pique32cbe282018-10-19 13:09:22 -07001933 display->setColorMode(colorMode, dataSpace, renderIntent);
David Sodman79bba0e2018-08-05 18:07:49 -07001934 }
1935 }
1936
1937 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001938
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001939 for (const auto& [token, displayDevice] : mDisplays) {
1940 auto display = displayDevice->getCompositionDisplay();
1941 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001942 const auto displayId = display->getId();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001943 layer->getBE().compositionInfo.compositionType =
1944 static_cast<HWC2::Composition>(layer->getCompositionType(displayDevice));
1945 layer->getBE().compositionInfo.hwc.displayId = *displayId;
Dominik Laskowski05275f12018-11-01 15:03:24 -07001946 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001947 }
1948 }
David Sodman79bba0e2018-08-05 18:07:49 -07001949}
1950
Lloyd Pique32cbe282018-10-19 13:09:22 -07001951void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1952 bool repaintEverything) {
1953 auto display = displayDevice->getCompositionDisplay();
1954 const auto& displayState = display->getState();
1955
Mathias Agopiancd60f992012-08-16 16:28:27 -07001956 // is debugging enabled
1957 if (CC_LIKELY(!mDebugRegion))
1958 return;
1959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001961 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001962 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001963 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001964 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001965 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001966 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001967
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001968 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001969 }
1970 }
1971
Lloyd Pique32cbe282018-10-19 13:09:22 -07001972 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973
1974 if (mDebugRegion > 1) {
1975 usleep(mDebugRegion * 1000);
1976 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001977
Lloyd Pique32cbe282018-10-19 13:09:22 -07001978 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979}
1980
Adrian Roos1e1a1282017-11-01 19:05:31 +01001981void SurfaceFlinger::doTracing(const char* where) {
1982 ATRACE_CALL();
1983 ATRACE_NAME(where);
1984 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001985 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001986 }
1987}
1988
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001989void SurfaceFlinger::logLayerStats() {
1990 ATRACE_CALL();
1991 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001992 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001994 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001995 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001996 }
1997 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001998
1999 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002000 }
2001}
2002
David Sodman2b406362017-12-15 13:33:47 -08002003void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 ATRACE_CALL();
2006 ALOGV("preComposition");
2007
David Sodman2b406362017-12-15 13:33:47 -08002008 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2009
Mathias Agopiancd60f992012-08-16 16:28:27 -07002010 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002011 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002012 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013 needExtraInvalidate = true;
2014 }
Robert Carr2047fae2016-11-28 14:09:09 -08002015 });
2016
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017 if (needExtraInvalidate) {
2018 signalLayerUpdate();
2019 }
2020}
2021
Ana Krulece588e312018-09-18 12:32:24 -07002022void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2023 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002024 // Update queue of past composite+present times and determine the
2025 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002026 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002027 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002028 while (!getBE().mCompositePresentTimes.empty()) {
2029 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030 // Cached values should have been updated before calling this method,
2031 // which helps avoid duplicate syscalls.
2032 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2033 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2034 break;
2035 }
2036 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002037 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038 }
2039
2040 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002041 while (getBE().mCompositePresentTimes.size() > 16) {
2042 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043 }
2044
Ana Krulece588e312018-09-18 12:32:24 -07002045 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002046}
2047
Ana Krulece588e312018-09-18 12:32:24 -07002048void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2049 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 // Integer division and modulo round toward 0 not -inf, so we need to
2051 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002052 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2053 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2054 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055
Ana Krulec757f63a2019-01-25 10:46:18 -08002056 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002057 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002058 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002059 }
2060
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061 // Snap the latency to a value that removes scheduling jitter from the
2062 // composition and present times, which often have >1ms of jitter.
2063 // Reducing jitter is important if an app attempts to extrapolate
2064 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002065 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002067 nsecs_t bias = stats.vsyncPeriod / 2;
2068 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2069 nsecs_t snappedCompositeToPresentLatency =
2070 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002071
David Sodman99974d22017-11-28 12:04:33 -08002072 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002073 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2074 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002075 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076}
2077
Ady Abraham8164d482019-01-11 14:47:59 -08002078// debug patch for b/119477596 - add stack guards to catch stack
2079// corruptions and disable clang optimizations.
2080// The code below is temporary and planned to be removed once stack
2081// corruptions are found.
2082#pragma clang optimize off
2083class StackGuard {
2084public:
2085 StackGuard(const char* name, const char* func, int line) {
2086 guarders.reserve(MIN_CAPACITY);
2087 guarders.push_back({this, name, func, line});
2088 validate();
2089 }
2090 ~StackGuard() {
2091 for (auto i = guarders.end() - 1; i >= guarders.begin(); --i) {
2092 if (i->guard == this) {
2093 guarders.erase(i);
2094 break;
2095 }
2096 }
2097 }
2098
2099 static void validate() {
2100 for (const auto& guard : guarders) {
2101 if (guard.guard->cookie != COOKIE_VALUE) {
2102 ALOGE("%s:%d: Stack corruption detected at %s", guard.func, guard.line, guard.name);
2103 CallStack stack(LOG_TAG);
2104 abort();
2105 }
2106 }
2107 }
2108
2109private:
2110 uint64_t cookie = COOKIE_VALUE;
2111 static constexpr uint64_t COOKIE_VALUE = 0xc0febebedeadbeef;
2112 static constexpr size_t MIN_CAPACITY = 16;
2113
2114 struct GuarderElement {
2115 StackGuard* guard;
2116 const char* name;
2117 const char* func;
2118 int line;
2119 };
2120
2121 static std::vector<GuarderElement> guarders;
2122};
2123std::vector<StackGuard::GuarderElement> StackGuard::guarders;
2124
2125#define DEFINE_STACK_GUARD(__n) StackGuard __n##StackGuard(#__n, __FUNCTION__, __LINE__);
2126
2127#define ASSERT_ON_STACK_GUARD() StackGuard::validate();
David Sodman2b406362017-12-15 13:33:47 -08002128void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002129{
Ady Abraham8164d482019-01-11 14:47:59 -08002130 DEFINE_STACK_GUARD(begin);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 ATRACE_CALL();
2132 ALOGV("postComposition");
2133
Brian Anderson3546a3f2016-07-14 11:51:14 -07002134 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002135 nsecs_t dequeueReadyTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002136 DEFINE_STACK_GUARD(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002137 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002138 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002139 }
Ady Abraham8164d482019-01-11 14:47:59 -08002140 ASSERT_ON_STACK_GUARD();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002141
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002142 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002143 const auto displayDevice = getDefaultDisplayDeviceLocked();
2144 DEFINE_STACK_GUARD(displayDevice);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002145
David Sodman73beded2017-11-15 11:56:06 -08002146 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002147 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002148 DEFINE_STACK_GUARD(glCompositionDoneFenceTime);
2149
Lloyd Pique32cbe282018-10-19 13:09:22 -07002150 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002151 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002152 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2153 ->getRenderSurface()
2154 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002155 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002156 } else {
2157 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2158 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002159
Ady Abraham8164d482019-01-11 14:47:59 -08002160 ASSERT_ON_STACK_GUARD();
2161
David Sodman73beded2017-11-15 11:56:06 -08002162 getBE().mDisplayTimeline.updateSignalTimes();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002163 mPreviousPresentFence = displayDevice ? getHwComposer().getPresentFence(*displayDevice->getId())
2164 : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002165 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
Ady Abraham8164d482019-01-11 14:47:59 -08002166 DEFINE_STACK_GUARD(presentFenceTime);
David Sodman73beded2017-11-15 11:56:06 -08002167 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002168
Ana Krulece588e312018-09-18 12:32:24 -07002169 DisplayStatInfo stats;
Ady Abraham8164d482019-01-11 14:47:59 -08002170 DEFINE_STACK_GUARD(stats);
Ana Krulece588e312018-09-18 12:32:24 -07002171 if (mUseScheduler) {
2172 mScheduler->getDisplayStatInfo(&stats);
2173 } else {
2174 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
2175 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
2176 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002177
Ady Abraham8164d482019-01-11 14:47:59 -08002178 ASSERT_ON_STACK_GUARD();
2179
David Sodman2b406362017-12-15 13:33:47 -08002180 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002181 // when we started doing work for this frame, but that should be okay
2182 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002183 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002184 CompositorTiming compositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002185 DEFINE_STACK_GUARD(compositorTiming);
2186
Brian Andersond0010582017-03-07 13:20:31 -08002187 {
David Sodman99974d22017-11-28 12:04:33 -08002188 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ady Abraham8164d482019-01-11 14:47:59 -08002189 DEFINE_STACK_GUARD(lock);
David Sodman99974d22017-11-28 12:04:33 -08002190 compositorTiming = getBE().mCompositorTiming;
Ady Abraham8164d482019-01-11 14:47:59 -08002191
2192 ASSERT_ON_STACK_GUARD();
Brian Andersond0010582017-03-07 13:20:31 -08002193 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002194
Robert Carr2047fae2016-11-28 14:09:09 -08002195 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002196 bool frameLatched =
2197 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2198 presentFenceTime, compositorTiming);
Ady Abraham8164d482019-01-11 14:47:59 -08002199 DEFINE_STACK_GUARD(frameLatched);
Dan Stozae77c7662016-05-13 11:37:28 -07002200 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002201 recordBufferingStats(layer->getName().string(),
2202 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002203 }
Ady Abraham8164d482019-01-11 14:47:59 -08002204 ASSERT_ON_STACK_GUARD();
Robert Carr2047fae2016-11-28 14:09:09 -08002205 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002206
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002207 if (presentFenceTime->isValid()) {
Ady Abraham8164d482019-01-11 14:47:59 -08002208 ASSERT_ON_STACK_GUARD();
Ana Krulece588e312018-09-18 12:32:24 -07002209 if (mUseScheduler) {
2210 mScheduler->addPresentFence(presentFenceTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002211 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002212 } else {
Ana Krulece588e312018-09-18 12:32:24 -07002213 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2214 enableHardwareVsync();
2215 } else {
2216 disableHardwareVsync(false);
2217 }
Ady Abraham8164d482019-01-11 14:47:59 -08002218 ASSERT_ON_STACK_GUARD();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002219 }
2220 }
2221
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002222 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002223 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2224 displayDevice->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002225 if (mUseScheduler) {
2226 mScheduler->enableHardwareVsync();
2227 } else {
2228 enableHardwareVsync();
2229 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002230 }
2231 }
2232
Ady Abraham8164d482019-01-11 14:47:59 -08002233 ASSERT_ON_STACK_GUARD();
2234
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002235 if (mAnimCompositionPending) {
2236 mAnimCompositionPending = false;
2237
Brian Anderson4e606e32017-03-16 15:34:57 -07002238 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002239 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002240 std::move(presentFenceTime));
Ady Abraham8164d482019-01-11 14:47:59 -08002241
2242 ASSERT_ON_STACK_GUARD();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002243 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002244 // The HWC doesn't support present fences, so use the refresh
2245 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002246 const nsecs_t presentTime =
2247 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Ady Abraham8164d482019-01-11 14:47:59 -08002248 DEFINE_STACK_GUARD(presentTime);
2249
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002250 mAnimFrameTracker.setActualPresentTime(presentTime);
Ady Abraham8164d482019-01-11 14:47:59 -08002251 ASSERT_ON_STACK_GUARD();
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002252 }
2253 mAnimFrameTracker.advanceFrame();
2254 }
Dan Stozab90cf072015-03-05 11:05:59 -08002255
Ady Abraham8164d482019-01-11 14:47:59 -08002256 ASSERT_ON_STACK_GUARD();
2257
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002258 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002259 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002260 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002261 }
2262
Ady Abraham8164d482019-01-11 14:47:59 -08002263 ASSERT_ON_STACK_GUARD();
2264
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002265 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002266
Ady Abraham8164d482019-01-11 14:47:59 -08002267 ASSERT_ON_STACK_GUARD();
2268
Lloyd Pique32cbe282018-10-19 13:09:22 -07002269 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2270 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002271 return;
2272 }
2273
2274 nsecs_t currentTime = systemTime();
Ady Abraham8164d482019-01-11 14:47:59 -08002275 DEFINE_STACK_GUARD(currentTime);
Dan Stozab90cf072015-03-05 11:05:59 -08002276 if (mHasPoweredOff) {
2277 mHasPoweredOff = false;
2278 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002279 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002280 DEFINE_STACK_GUARD(elapsedTime);
Ana Krulece588e312018-09-18 12:32:24 -07002281 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
Ady Abraham8164d482019-01-11 14:47:59 -08002282 DEFINE_STACK_GUARD(numPeriods);
David Sodman4a36e932017-11-07 14:29:47 -08002283 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2284 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002285 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002286 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002287 }
David Sodman4a36e932017-11-07 14:29:47 -08002288 getBE().mTotalTime += elapsedTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002289
2290 ASSERT_ON_STACK_GUARD();
Dan Stozab90cf072015-03-05 11:05:59 -08002291 }
David Sodman4a36e932017-11-07 14:29:47 -08002292 getBE().mLastSwapTime = currentTime;
Ady Abraham8164d482019-01-11 14:47:59 -08002293 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002294
2295 {
2296 std::lock_guard lock(mTexturePoolMutex);
Ady Abraham8164d482019-01-11 14:47:59 -08002297 DEFINE_STACK_GUARD(lock);
Dan Stoza436ccf32018-06-21 12:10:12 -07002298 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Ady Abraham8164d482019-01-11 14:47:59 -08002299 DEFINE_STACK_GUARD(refillCount);
Dan Stoza436ccf32018-06-21 12:10:12 -07002300 if (refillCount > 0) {
2301 const size_t offset = mTexturePool.size();
2302 mTexturePool.resize(mTexturePoolSize);
2303 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2304 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2305 }
Ady Abraham8164d482019-01-11 14:47:59 -08002306 ASSERT_ON_STACK_GUARD();
Dan Stoza436ccf32018-06-21 12:10:12 -07002307 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002308
Marissa Wallfda30bb2018-10-12 11:34:28 -07002309 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002310 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002311
2312 ASSERT_ON_STACK_GUARD();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002313}
Ady Abraham8164d482019-01-11 14:47:59 -08002314#pragma clang optimize on // b/119477596
Mathias Agopiancd60f992012-08-16 16:28:27 -07002315
Vishnu Nair4351ad52019-02-11 14:13:02 -08002316void SurfaceFlinger::computeLayerBounds() {
2317 for (const auto& pair : mDisplays) {
2318 const auto& displayDevice = pair.second;
2319 const auto display = displayDevice->getCompositionDisplay();
2320 for (const auto& layer : mDrawingState.layersSortedByZ) {
2321 // only consider the layers on the given layer stack
2322 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002323 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002324 }
2325
2326 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2327 }
2328 }
2329}
2330
Mathias Agopiancd60f992012-08-16 16:28:27 -07002331void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 ATRACE_CALL();
2333 ALOGV("rebuildLayerStacks");
2334
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002335 // We need to clear these out now as these may be holding on to a
2336 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2337 // also holds a reference. When the set of visible layers is recomputed,
2338 // some layers may be destroyed if the only thing keeping them alive was
2339 // that list of visible layers associated with each display. The layer
2340 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2341 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2342 for (const auto& [token, display] : mDisplays) {
2343 getBE().mCompositionInfo[token].clear();
2344 }
2345
Mathias Agopiancd60f992012-08-16 16:28:27 -07002346 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002347 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002348 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002349 mVisibleRegionsDirty = false;
2350 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002351
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002352 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002353 const auto& displayDevice = pair.second;
2354 auto display = displayDevice->getCompositionDisplay();
2355 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002356 Region opaqueRegion;
2357 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002358 compositionengine::Output::OutputLayers layersSortedByZ;
2359 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002360 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002361 const ui::Transform& tr = displayState.transform;
2362 const Rect bounds = displayState.bounds;
2363 if (displayState.isEnabled) {
2364 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002365
Jeff Sharkey76488112017-02-27 14:15:18 -07002366 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002367 auto compositionLayer = layer->getCompositionLayer();
2368 if (compositionLayer == nullptr) {
2369 return;
2370 }
2371
Chia-I Wu83806892017-11-16 10:50:20 -08002372 bool hwcLayerDestroyed = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002373 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002374 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2375 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2376
Lloyd Piqueef36b002019-01-23 17:52:04 -08002377 if (display->belongsInOutput(layer->getLayerStack(),
2378 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002379 Region drawRegion(tr.transform(
2380 layer->visibleNonTransparentRegion));
2381 drawRegion.andSelf(bounds);
2382 if (!drawRegion.isEmpty()) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002383 layersSortedByZ.emplace_back(
2384 display->getOrCreateOutputLayer(layer->getCompositionLayer(),
2385 layerFE));
2386
2387 deprecated_layersSortedByZ.add(layer);
Jeff Sharkey76488112017-02-27 14:15:18 -07002388 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002389 // Clear out the HWC layer if this layer was
2390 // previously visible, but no longer is
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002391 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(displayDevice);
Jeff Sharkey76488112017-02-27 14:15:18 -07002392 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002393 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002394 // WM changes display->layerStack upon sleep/awake.
2395 // Here we make sure we delete the HWC layers even if
2396 // WM changed their layer stack.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002397 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(displayDevice);
Chia-I Wu83806892017-11-16 10:50:20 -08002398 }
2399
2400 // If a layer is not going to get a release fence because
2401 // it is invisible, but it is also going to release its
2402 // old buffer, add it to the list of layers needing
2403 // fences.
2404 if (hwcLayerDestroyed) {
2405 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2406 mLayersWithQueuedFrames.cend(), layer);
2407 if (found != mLayersWithQueuedFrames.cend()) {
2408 layersNeedingFences.add(layer);
2409 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002410 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002411 });
2412 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002413
2414 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2415
2416 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 displayDevice->setLayersNeedingFences(layersNeedingFences);
2418
2419 Region undefinedRegion{bounds};
2420 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2421
2422 display->editState().undefinedRegion = undefinedRegion;
2423 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002424 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002425 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002426}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002427
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002428// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002429// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002430// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002431// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002432// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002433// The returned HDR data space is one of
2434// - Dataspace::UNKNOWN
2435// - Dataspace::BT2020_HLG
2436// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2438 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002439 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002440 *outHdrDataSpace = Dataspace::UNKNOWN;
2441
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002442 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002443 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002444 case Dataspace::V0_SCRGB:
2445 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002446 case Dataspace::BT2020:
2447 case Dataspace::BT2020_ITU:
2448 case Dataspace::BT2020_LINEAR:
2449 case Dataspace::DISPLAY_BT2020:
2450 bestDataSpace = Dataspace::DISPLAY_BT2020;
2451 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002452 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002453 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002454 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002455 case Dataspace::BT2020_PQ:
2456 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002457 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002458 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002459 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002460 case Dataspace::BT2020_HLG:
2461 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002462 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002463 // When there's mixed PQ content and HLG content, we set the HDR
2464 // data space to be BT2020_PQ and convert HLG to PQ.
2465 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2466 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002467 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002468 break;
2469 default:
2470 break;
2471 }
Romain Guy54f154a2017-10-24 21:40:32 +01002472 }
2473
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002474 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002475}
2476
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002477// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002478void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2479 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002480 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2481 *outMode = ColorMode::NATIVE;
2482 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002483 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002484 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002485 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002486
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002487 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002489
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002490 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2491
Peiyong Lindfde5112018-06-05 10:58:41 -07002492 // respect hdrDataSpace only when there is no legacy HDR support
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002493 const bool isHdr =
2494 hdrDataSpace != Dataspace::UNKNOWN && !profile->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002495 if (isHdr) {
2496 bestDataSpace = hdrDataSpace;
2497 }
2498
Chia-I Wu0d711262018-05-21 15:19:35 -07002499 RenderIntent intent;
2500 switch (mDisplayColorSetting) {
2501 case DisplayColorSetting::MANAGED:
2502 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002503 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002504 break;
2505 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002506 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002507 break;
2508 default: // vendor display color setting
2509 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2510 break;
2511 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002512
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002513 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002514}
2515
Lloyd Pique32cbe282018-10-19 13:09:22 -07002516void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2517 auto display = displayDevice->getCompositionDisplay();
2518 const auto& displayState = display->getState();
2519
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002520 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002521 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2522 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002523
David Sodmanfa9b2af2017-12-24 13:28:59 -08002524 // If nothing has changed (!dirty), don't recompose.
2525 // If something changed, but we don't currently have any visible layers,
2526 // and didn't when we last did a composition, then skip it this time.
2527 // The second rule does two things:
2528 // - When all layers are removed from a display, we'll emit one black
2529 // frame, then nothing more until we get new layers.
2530 // - When a display is created with a private layer stack, we won't
2531 // emit any black frames until a layer is added to the layer stack.
2532 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002533
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 const char flagPrefix[] = {'-', '+'};
2535 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002536 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2537 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2538 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2539 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002540
Lloyd Pique31cb2942018-10-19 17:23:03 -07002541 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002542
David Sodmanfa9b2af2017-12-24 13:28:59 -08002543 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002544 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002545 }
2546}
2547
Lloyd Pique32cbe282018-10-19 13:09:22 -07002548void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2549 auto display = displayDevice->getCompositionDisplay();
2550 const auto& displayState = display->getState();
2551
2552 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002553 return;
David Sodman2b406362017-12-15 13:33:47 -08002554 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002555
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002556 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002557 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002558 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002559}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002560
Lloyd Pique32cbe282018-10-19 13:09:22 -07002561void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002562 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002563 ALOGV("doComposition");
2564
Lloyd Pique32cbe282018-10-19 13:09:22 -07002565 auto display = displayDevice->getCompositionDisplay();
2566 const auto& displayState = display->getState();
2567
2568 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002569 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002570 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002571
David Sodmanfa9b2af2017-12-24 13:28:59 -08002572 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002573 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002574
Lloyd Pique32cbe282018-10-19 13:09:22 -07002575 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002576 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002577 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002578 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002579}
2580
David Sodmanfa9b2af2017-12-24 13:28:59 -08002581void SurfaceFlinger::postFrame()
2582{
2583 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 const auto display = getDefaultDisplayDeviceLocked();
2585 if (display && getHwComposer().isConnected(*display->getId())) {
2586 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002587 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2588 logFrameStats();
2589 }
2590 }
2591}
2592
Lloyd Pique32cbe282018-10-19 13:09:22 -07002593void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002594 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002595 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002596
Lloyd Pique32cbe282018-10-19 13:09:22 -07002597 auto display = displayDevice->getCompositionDisplay();
2598 const auto& displayState = display->getState();
2599 const auto displayId = display->getId();
2600
David Sodmanfa9b2af2017-12-24 13:28:59 -08002601 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002602
Lloyd Pique32cbe282018-10-19 13:09:22 -07002603 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 if (displayId) {
2605 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002606 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002607 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002608 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002609 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002610
Chia-I Wu7b549592017-11-15 09:14:57 -08002611 // The layer buffer from the previous frame (if any) is released
2612 // by HWC only when the release fence from this frame (if any) is
2613 // signaled. Always get the release fence from HWC first.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002614 if (displayId && layer->hasHwcLayer(displayDevice)) {
2615 releaseFence =
2616 getHwComposer().getLayerReleaseFence(*displayId,
2617 layer->getHwcLayer(displayDevice));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002618 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002619
2620 // If the layer was client composited in the previous frame, we
2621 // need to merge with the previous client target acquire fence.
2622 // Since we do not track that, always merge with the current
2623 // client target acquire fence when it is available, even though
2624 // this is suboptimal.
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002625 if (layer->getCompositionType(displayDevice) ==
2626 Hwc2::IComposerClient::Composition::CLIENT) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002627 releaseFence =
2628 Fence::merge("LayerRelease", releaseFence,
2629 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002630 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002631
David Sodman15094112018-10-11 09:39:37 -07002632 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 }
Chia-I Wu83806892017-11-16 10:50:20 -08002634
2635 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002636 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002637 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002638 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002640 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002641 for (auto& layer : displayDevice->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002642 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002643 }
2644 }
2645
Dominik Laskowski075d3172018-05-24 15:50:06 -07002646 if (displayId) {
2647 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002648 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650}
2651
Mathias Agopian87baae12012-07-31 12:38:26 -07002652void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653{
Mathias Agopian841cde52012-03-01 15:44:37 -08002654 ATRACE_CALL();
2655
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002656 // here we keep a copy of the drawing state (that is the state that's
2657 // going to be overwritten by handleTransactionLocked()) outside of
2658 // mStateLock so that the side-effects of the State assignment
2659 // don't happen with mStateLock held (which can cause deadlocks).
2660 State drawingState(mDrawingState);
2661
Mathias Agopianca4d3602011-05-19 15:38:14 -07002662 Mutex::Autolock _l(mStateLock);
2663 const nsecs_t now = systemTime();
2664 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Mathias Agopianca4d3602011-05-19 15:38:14 -07002666 // Here we're guaranteed that some transaction flags are set
2667 // so we can call handleTransactionLocked() unconditionally.
2668 // We call getTransactionFlags(), which will also clear the flags,
2669 // with mStateLock held to guarantee that mCurrentState won't change
2670 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002671
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002672 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002673 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002674 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002675
Mathias Agopianca4d3602011-05-19 15:38:14 -07002676 mLastTransactionTime = systemTime() - now;
2677 mDebugInTransaction = 0;
2678 invalidateHwcGeometry();
2679 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002680}
2681
Lloyd Piqueba04e622017-12-14 17:11:26 -08002682void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2683 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002684 const std::optional<DisplayIdentificationInfo> info =
2685 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002686
Dominik Laskowski075d3172018-05-24 15:50:06 -07002687 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002688 continue;
2689 }
2690
Lloyd Piqueba04e622017-12-14 17:11:26 -08002691 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002692 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002693 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 mPhysicalDisplayTokens[info->id] = new BBinder();
2695 DisplayDeviceState state;
2696 state.displayId = info->id;
2697 state.isSecure = true; // All physical displays are currently considered secure.
2698 state.displayName = info->name;
2699 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2700 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002701 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002702 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002703 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002704
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2706 if (index >= 0) {
2707 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2708 mInterceptor->saveDisplayDeletion(state.sequenceId);
2709 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002710 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002711 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002712 }
2713
2714 processDisplayChangesLocked();
2715 }
2716
2717 mPendingHotplugEvents.clear();
2718}
2719
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002720void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002721 if (mUseScheduler) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002722 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2723 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002724 } else {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002725 mEventThread->onHotplugReceived(displayId, connected);
2726 mSFEventThread->onHotplugReceived(displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002727 }
2728}
2729
Lloyd Pique99d3da52018-01-22 17:48:03 -08002730sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002731 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002732 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002733 const sp<IGraphicBufferProducer>& producer) {
2734 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002735 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002736 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002737 creationArgs.isSecure = state.isSecure;
2738 creationArgs.displaySurface = dispSurface;
2739 creationArgs.hasWideColorGamut = false;
2740 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002741
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002742 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002743 creationArgs.isPrimary = isInternalDisplay;
2744
2745 if (useColorManagement && displayId) {
2746 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002747 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002748 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002749 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002750 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002751
Dominik Laskowski7e045462018-05-30 13:02:02 -07002752 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002753 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002754 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002755 }
tangrobin6753a022018-08-10 10:58:54 +08002756 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002757
Dominik Laskowski075d3172018-05-24 15:50:06 -07002758 if (displayId) {
2759 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002760 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002761 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002762 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002763
Lloyd Pique90c115d2018-09-18 21:39:42 -07002764 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002765 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002766 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002767
Lloyd Pique99d3da52018-01-22 17:48:03 -08002768 // Make sure that composition can never be stalled by a virtual display
2769 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002770 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002771 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002772 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2773 }
2774
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 creationArgs.displayInstallOrientation =
2776 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002777
Lloyd Pique99d3da52018-01-22 17:48:03 -08002778 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002779 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002780
Lloyd Pique90c115d2018-09-18 21:39:42 -07002781 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002782
2783 if (maxFrameBufferAcquiredBuffers >= 3) {
2784 nativeWindowSurface->preallocateBuffers();
2785 }
2786
2787 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002788 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002789 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002790 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002791 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002792 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002793 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2794 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 if (!state.isVirtual()) {
2796 LOG_ALWAYS_FATAL_IF(!displayId);
2797 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002798 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002800 display->setLayerStack(state.layerStack);
2801 display->setProjection(state.orientation, state.viewport, state.frame);
2802 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002803
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002804 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002805}
2806
Lloyd Pique347200f2017-12-14 17:00:15 -08002807void SurfaceFlinger::processDisplayChangesLocked() {
2808 // here we take advantage of Vector's copy-on-write semantics to
2809 // improve performance by skipping the transaction entirely when
2810 // know that the lists are identical
2811 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2812 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2813 if (!curr.isIdenticalTo(draw)) {
2814 mVisibleRegionsDirty = true;
2815 const size_t cc = curr.size();
2816 size_t dc = draw.size();
2817
2818 // find the displays that were removed
2819 // (ie: in drawing state but not in current state)
2820 // also handle displays that changed
2821 // (ie: displays that are in both lists)
2822 for (size_t i = 0; i < dc;) {
2823 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2824 if (j < 0) {
2825 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002826 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002827 // Save display ID before disconnecting.
2828 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002829 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002830
2831 if (!display->isVirtual()) {
2832 LOG_ALWAYS_FATAL_IF(!displayId);
2833 dispatchDisplayHotplugEvent(displayId->value, false);
2834 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002835 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002836
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002837 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002838 } else {
2839 // this display is in both lists. see if something changed.
2840 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002842 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2843 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2844 if (state_binder != draw_binder) {
2845 // changing the surface is like destroying and
2846 // recreating the DisplayDevice, so we just remove it
2847 // from the drawing state, so that it get re-added
2848 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002849 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002850 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002851 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002852 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002853 mDrawingState.displays.removeItemsAt(i);
2854 dc--;
2855 // at this point we must loop to the next item
2856 continue;
2857 }
2858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002860 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002861 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002862 }
2863 if ((state.orientation != draw[i].orientation) ||
2864 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002866 }
2867 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002868 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002869 }
2870 }
2871 }
2872 ++i;
2873 }
2874
2875 // find displays that were added
2876 // (ie: in current state but not in drawing state)
2877 for (size_t i = 0; i < cc; i++) {
2878 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2879 const DisplayDeviceState& state(curr[i]);
2880
Lloyd Pique542307f2018-10-19 13:24:08 -07002881 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002882 sp<IGraphicBufferProducer> producer;
2883 sp<IGraphicBufferProducer> bqProducer;
2884 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002885 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002886
Dominik Laskowski075d3172018-05-24 15:50:06 -07002887 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002888 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002889 // Virtual displays without a surface are dormant:
2890 // they have external state (layer stack, projection,
2891 // etc.) but no internal state (i.e. a DisplayDevice).
2892 if (state.surface != nullptr) {
2893 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002894 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002895 int width = 0;
2896 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2897 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2898 int height = 0;
2899 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2900 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2901 int intFormat = 0;
2902 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2903 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002904 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002905
Dominik Laskowski075d3172018-05-24 15:50:06 -07002906 displayId =
2907 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002908 }
2909
2910 // TODO: Plumb requested format back up to consumer
2911
2912 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002913 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002914 bqProducer, bqConsumer,
2915 state.displayName);
2916
2917 dispSurface = vds;
2918 producer = vds;
2919 }
2920 } else {
2921 ALOGE_IF(state.surface != nullptr,
2922 "adding a supported display, but rendering "
2923 "surface is provided (%p), ignoring it",
2924 state.surface.get());
2925
Dominik Laskowski075d3172018-05-24 15:50:06 -07002926 displayId = state.displayId;
2927 LOG_ALWAYS_FATAL_IF(!displayId);
2928 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002929 producer = bqProducer;
2930 }
2931
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002932 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002933 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002935 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002937 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002938 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002939 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002940 }
2941 }
2942 }
2943 }
2944 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002945
2946 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002947}
2948
Mathias Agopian87baae12012-07-31 12:38:26 -07002949void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002950{
Dan Stoza7dde5992015-05-22 09:51:44 -07002951 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002952 mCurrentState.traverseInZOrder([](Layer* layer) {
2953 layer->notifyAvailableFrames();
2954 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002955
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 /*
2957 * Traversal of the children
2958 * (perform the transaction for each of them if needed)
2959 */
2960
Mathias Agopian3559b072012-08-15 13:46:03 -07002961 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002962 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002964 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965
2966 const uint32_t flags = layer->doTransaction(0);
2967 if (flags & Layer::eVisibleRegion)
2968 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002969
2970 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002971 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002972 }
Robert Carr2047fae2016-11-28 14:09:09 -08002973 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 }
2975
2976 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002977 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 */
2979
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002981 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002982 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002983 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002985 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002986 // The transform hint might have changed for some layers
2987 // (either because a display has changed, or because a layer
2988 // as changed).
2989 //
2990 // Walk through all the layers in currentLayers,
2991 // and update their transform hint.
2992 //
2993 // If a layer is visible only on a single display, then that
2994 // display is used to calculate the hint, otherwise we use the
2995 // default display.
2996 //
2997 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2998 // the hint is set before we acquire a buffer from the surface texture.
2999 //
3000 // NOTE: layer transactions have taken place already, so we use their
3001 // drawing state. However, SurfaceFlinger's own transaction has not
3002 // happened yet, so we must use the current state layer list
3003 // (soon to become the drawing state list).
3004 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003005 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08003006 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08003007 bool first = true;
3008 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08003009 // NOTE: we rely on the fact that layers are sorted by
3010 // layerStack first (so we don't have to traverse the list
3011 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08003013 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08003014 currentlayerStack = layerStack;
3015 // figure out if this layerstack is mirrored
3016 // (more than one display) if so, pick the default display,
3017 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003018 hintDisplay = nullptr;
3019 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08003020 if (display->getCompositionDisplay()
3021 ->belongsInOutput(layer->getLayerStack(),
3022 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003023 if (hintDisplay) {
3024 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08003025 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003027 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08003028 }
3029 }
3030 }
3031 }
Chet Haase91d25932013-04-11 15:24:55 -07003032
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003033 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003034 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3035 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08003036
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003037 // could be null when this layer is using a layerStack
3038 // that is not visible on any display. Also can occur at
3039 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003040 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08003041 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003042
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003043 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003044 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003045 if (hintDisplay) {
3046 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08003047 }
Robert Carr2047fae2016-11-28 14:09:09 -08003048
3049 first = false;
3050 });
Mathias Agopian84300952012-11-21 16:02:13 -08003051 }
3052
3053
Mathias Agopian3559b072012-08-15 13:46:03 -07003054 /*
3055 * Perform our own transaction if needed
3056 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07003057
3058 if (mLayersAdded) {
3059 mLayersAdded = false;
3060 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07003061 mVisibleRegionsDirty = true;
3062 }
3063
3064 // some layers might have been removed, so
3065 // we need to update the regions they're exposing.
3066 if (mLayersRemoved) {
3067 mLayersRemoved = false;
3068 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003069 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003070 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003071 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003072 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003073 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003074 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003075 }
Robert Carr2047fae2016-11-28 14:09:09 -08003076 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077 }
3078
3079 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003080}
3081
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003082void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003083 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003084 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003085 return;
3086 }
3087
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003088 if (mVisibleRegionsDirty || mInputInfoChanged) {
3089 mInputInfoChanged = false;
3090 updateInputWindowInfo();
3091 }
3092
3093 executeInputWindowCommands();
3094}
3095
3096void SurfaceFlinger::updateInputWindowInfo() {
Robert Carr720e5062018-07-30 17:45:14 -07003097 Vector<InputWindowInfo> inputHandles;
3098
3099 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3100 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003101 // When calculating the screen bounds we ignore the transparent region since it may
3102 // result in an unwanted offset.
Arthur Hungd20b2702019-01-14 18:16:16 +08003103 inputHandles.add(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003104 }
3105 });
3106 mInputFlinger->setInputWindows(inputHandles);
3107}
3108
chaviwfbe5d9c2018-12-26 12:23:37 -08003109void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003110 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3111 if (transferTouchFocusCommand.fromToken != nullptr &&
3112 transferTouchFocusCommand.toToken != nullptr &&
3113 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3114 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3115 transferTouchFocusCommand.toToken);
3116 }
3117 }
3118
3119 mInputWindowCommands.clear();
3120}
3121
Riley Andrews03414a12014-07-01 14:22:59 -07003122void SurfaceFlinger::updateCursorAsync()
3123{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003124 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003125 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003126 continue;
3127 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003129 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3130 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003131 }
3132 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003133}
3134
chaviw61626f22018-11-15 16:26:27 -08003135void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3136 if (layer->hasReadyFrame()) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003137 nsecs_t expectedPresentTime;
3138 if (mUseScheduler) {
3139 expectedPresentTime = mScheduler->expectedPresentTime();
3140 } else {
3141 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3142 }
chaviw61626f22018-11-15 16:26:27 -08003143 if (layer->shouldPresentNow(expectedPresentTime)) {
3144 bool ignored = false;
3145 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
3146 }
3147 }
3148 layer->releasePendingBuffer(systemTime());
3149}
3150
Mathias Agopian4fec8732012-06-29 14:12:52 -07003151void SurfaceFlinger::commitTransaction()
3152{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003153 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003154 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 for (const auto& l : mLayersPendingRemoval) {
3156 recordBufferingStats(l->getName().string(),
3157 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003158
3159 // We need to release the HWC layers when the Layer is removed
3160 // from the current state otherwise the HWC layer just continues
3161 // showing at its last configured state until we eventually
3162 // abandon the buffer queue.
3163 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003164 l->destroyHwcLayersForAllDisplays();
3165 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003166 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003167 }
3168 mLayersPendingRemoval.clear();
3169 }
3170
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003171 // If this transaction is part of a window animation then the next frame
3172 // we composite should be considered an animation as well.
3173 mAnimCompositionPending = mAnimTransactionPending;
3174
Mathias Agopian4fec8732012-06-29 14:12:52 -07003175 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003176 // clear the "changed" flags in current state
3177 mCurrentState.colorMatrixChanged = false;
3178
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179 mDrawingState.traverseInZOrder([](Layer* layer) {
3180 layer->commitChildList();
3181 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003182 mTransactionPending = false;
3183 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003184 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185}
3186
Lloyd Pique32cbe282018-10-19 13:09:22 -07003187void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003188 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003189 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003190 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003191
Lloyd Pique32cbe282018-10-19 13:09:22 -07003192 auto display = displayDevice->getCompositionDisplay();
3193
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194 Region aboveOpaqueLayers;
3195 Region aboveCoveredLayers;
3196 Region dirty;
3197
Mathias Agopian87baae12012-07-31 12:38:26 -07003198 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199
Robert Carr2047fae2016-11-28 14:09:09 -08003200 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003201 // start with the whole surface at its current location
3202 const Layer::State& s(layer->getDrawingState());
3203
Jesse Hall01e29052013-02-19 16:13:35 -08003204 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003205 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003206 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003207 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003208
Mathias Agopianab028732010-03-16 16:41:46 -07003209 /*
3210 * opaqueRegion: area of a surface that is fully opaque.
3211 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003213
3214 /*
3215 * visibleRegion: area of a surface that is visible on screen
3216 * and not fully transparent. This is essentially the layer's
3217 * footprint minus the opaque regions above it.
3218 * Areas covered by a translucent surface are considered visible.
3219 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003221
3222 /*
3223 * coveredRegion: area of a surface that is covered by all
3224 * visible regions above it (which includes the translucent areas).
3225 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003227
Jesse Halla8026d22012-09-25 13:25:04 -07003228 /*
3229 * transparentRegion: area of a surface that is hinted to be completely
3230 * transparent. This is only used to tell when the layer has no visible
3231 * non-transparent regions and can be removed from the layer list. It
3232 * does not affect the visibleRegion of this layer or any layers
3233 * beneath it. The hint may not be correct if apps don't respect the
3234 * SurfaceView restrictions (which, sadly, some don't).
3235 */
3236 Region transparentRegion;
3237
Mathias Agopianab028732010-03-16 16:41:46 -07003238
3239 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003240 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003241 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003242 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003243
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003245 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003246 if (!visibleRegion.isEmpty()) {
3247 // Remove the transparent area from the visible region
3248 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003249 if (tr.preserveRects()) {
3250 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003251 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003252 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003253 // transformation too complex, can't do the
3254 // transparent region optimization.
3255 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003256 }
Mathias Agopianab028732010-03-16 16:41:46 -07003257 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258
Mathias Agopianab028732010-03-16 16:41:46 -07003259 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003260 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003261 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003262 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003263 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003264 // the opaque region is the layer's footprint
3265 opaqueRegion = visibleRegion;
3266 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268 }
3269
Robert Carre5f4f692018-01-12 13:12:28 -08003270 if (visibleRegion.isEmpty()) {
3271 layer->clearVisibilityRegions();
3272 return;
3273 }
3274
Mathias Agopianab028732010-03-16 16:41:46 -07003275 // Clip the covered region to the visible region
3276 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3277
3278 // Update aboveCoveredLayers for next (lower) layer
3279 aboveCoveredLayers.orSelf(visibleRegion);
3280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281 // subtract the opaque region covered by the layers above us
3282 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283
3284 // compute this layer's dirty region
3285 if (layer->contentDirty) {
3286 // we need to invalidate the whole region
3287 dirty = visibleRegion;
3288 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003289 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290 layer->contentDirty = false;
3291 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003292 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003293 * the exposed region consists of two components:
3294 * 1) what's VISIBLE now and was COVERED before
3295 * 2) what's EXPOSED now less what was EXPOSED before
3296 *
3297 * note that (1) is conservative, we start with the whole
3298 * visible region but only keep what used to be covered by
3299 * something -- which mean it may have been exposed.
3300 *
3301 * (2) handles areas that were not covered by anything but got
3302 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003303 */
Mathias Agopianab028732010-03-16 16:41:46 -07003304 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003305 const Region oldVisibleRegion = layer->visibleRegion;
3306 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003307 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3308 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309 }
3310 dirty.subtractSelf(aboveOpaqueLayers);
3311
3312 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003313 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314
Mathias Agopianab028732010-03-16 16:41:46 -07003315 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003317
Jesse Halla8026d22012-09-25 13:25:04 -07003318 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319 layer->setVisibleRegion(visibleRegion);
3320 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003321 layer->setVisibleNonTransparentRegion(
3322 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003323 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003324
Mathias Agopian87baae12012-07-31 12:38:26 -07003325 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003326}
3327
Chia-I Wuab0c3192017-08-01 11:29:00 -07003328void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003329 for (const auto& [token, displayDevice] : mDisplays) {
3330 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003331 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003332 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003333 }
3334 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003335}
3336
Daniel Solomon42d04562019-01-20 21:03:19 -08003337void SurfaceFlinger::initDefaultDisplayNativePrimaries() {
3338 mInternalDisplayPrimaries.red.X = kSrgbRedX;
3339 mInternalDisplayPrimaries.red.Y = kSrgbRedY;
3340 mInternalDisplayPrimaries.red.Z = kSrgbRedZ;
3341 mInternalDisplayPrimaries.green.X = kSrgbGreenX;
3342 mInternalDisplayPrimaries.green.Y = kSrgbGreenY;
3343 mInternalDisplayPrimaries.green.Z = kSrgbGreenZ;
3344 mInternalDisplayPrimaries.blue.X = kSrgbBlueX;
3345 mInternalDisplayPrimaries.blue.Y = kSrgbBlueY;
3346 mInternalDisplayPrimaries.blue.Z = kSrgbBlueZ;
3347 mInternalDisplayPrimaries.white.X = kSrgbWhiteX;
3348 mInternalDisplayPrimaries.white.Y = kSrgbWhiteY;
3349 mInternalDisplayPrimaries.white.Z = kSrgbWhiteZ;
3350}
3351
Dan Stoza6b9454d2014-11-07 16:00:59 -08003352bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003354 ALOGV("handlePageFlip");
3355
Brian Andersond6927fb2016-07-23 23:37:30 -07003356 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357
Mathias Agopian4fec8732012-06-29 14:12:52 -07003358 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003359 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003360 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003361
3362 // Store the set of layers that need updates. This set must not change as
3363 // buffers are being latched, as this could result in a deadlock.
3364 // Example: Two producers share the same command stream and:
3365 // 1.) Layer 0 is latched
3366 // 2.) Layer 0 gets a new frame
3367 // 2.) Layer 1 gets a new frame
3368 // 3.) Layer 1 is latched.
3369 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3370 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003371 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003372 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003373 frameQueued = true;
Ady Abrahamc3e21312019-02-07 14:30:23 -08003374 nsecs_t expectedPresentTime;
3375 if (mUseScheduler) {
3376 expectedPresentTime = mScheduler->expectedPresentTime();
3377 } else {
3378 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3379 }
Ana Krulec010d2192018-10-08 06:29:54 -07003380 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003381 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003382 } else {
3383 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003384 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003385 } else {
3386 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003387 }
Robert Carr2047fae2016-11-28 14:09:09 -08003388 });
3389
Lloyd Piquef2c79392018-12-20 16:23:33 -08003390 if (!mLayersWithQueuedFrames.empty()) {
3391 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3392 // writes to Layer current state. See also b/119481871
3393 Mutex::Autolock lock(mStateLock);
3394
3395 for (auto& layer : mLayersWithQueuedFrames) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003396 if (layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence)) {
3397 mLayersPendingRefresh.push_back(layer);
3398 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003399 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003400 if (layer->isBufferLatched()) {
3401 newDataLatched = true;
3402 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003403 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003404 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003405
Alec Mouri86770e52018-09-24 22:40:58 +00003406 // Clear the renderengine fence here...
3407 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3408 // clear instead of sp::clear.
3409 getBE().flushFence = Fence::NO_FENCE;
3410
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003411 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003412
3413 // If we will need to wake up at some time in the future to deal with a
3414 // queued frame that shouldn't be displayed during this vsync period, wake
3415 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003416 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003417 signalLayerUpdate();
3418 }
3419
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003420 // enter boot animation on first buffer latch
3421 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3422 ALOGI("Enter boot animation");
3423 mBootStage = BootStage::BOOTANIMATION;
3424 }
3425
Dan Stoza6b9454d2014-11-07 16:00:59 -08003426 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003427 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003428}
3429
Mathias Agopianad456f92011-01-13 17:53:01 -08003430void SurfaceFlinger::invalidateHwcGeometry()
3431{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003432 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003433}
3434
Lloyd Pique32cbe282018-10-19 13:09:22 -07003435void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003436 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003437 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003438 // We only need to actually compose the display if:
3439 // 1) It is being handled by hardware composer, which may need this to
3440 // keep its virtual display state machine in sync, or
3441 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003442 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003443 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003444 return;
3445 }
3446
Dan Stoza9e56aa02015-11-02 13:00:03 -08003447 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003448 base::unique_fd readyFence;
3449 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003450
3451 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003452 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003453}
3454
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003455bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3456 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003457 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003458 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003459
Lloyd Pique32cbe282018-10-19 13:09:22 -07003460 auto display = displayDevice->getCompositionDisplay();
3461 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003462 const auto displayId = display->getId();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003463
3464 const Region bounds(displayState.bounds);
3465 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003466 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003467 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003468
Peiyong Lind3788632018-09-18 16:01:31 -07003469 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003470 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003471
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003472 renderengine::DisplaySettings clientCompositionDisplay;
3473 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3474 sp<GraphicBuffer> buf;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003475
Dan Stoza9e56aa02015-11-02 13:00:03 -08003476 if (hasClientComposition) {
3477 ALOGV("hasClientComposition");
3478
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003479 buf = display->getRenderSurface()->dequeueBuffer();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003480
3481 if (buf == nullptr) {
3482 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3483 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003484 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003485 return false;
3486 }
3487
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003488 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3489 clientCompositionDisplay.clip = displayState.scissor;
3490 const ui::Transform& displayTransform = displayState.transform;
3491 mat4 m;
3492 m[0][0] = displayTransform[0][0];
3493 m[0][1] = displayTransform[0][1];
3494 m[0][3] = displayTransform[0][2];
3495 m[1][0] = displayTransform[1][0];
3496 m[1][1] = displayTransform[1][1];
3497 m[1][3] = displayTransform[1][2];
3498 m[3][0] = displayTransform[2][0];
3499 m[3][1] = displayTransform[2][1];
3500 m[3][3] = displayTransform[2][2];
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003501
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003502 clientCompositionDisplay.globalTransform = m;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003503
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003504 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003505 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003506 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003507 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003508 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003509 clientCompositionDisplay.outputDataspace = outputDataspace;
3510 clientCompositionDisplay.maxLuminance =
3511 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003512
Lloyd Pique441d5042018-10-18 16:49:51 -07003513 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003514 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003515 getHwComposer()
3516 .hasDisplayCapability(displayId,
3517 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003518
Peiyong Lind3788632018-09-18 16:01:31 -07003519 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003520 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3521 if (applyColorMatrix) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003522 clientCompositionDisplay.colorTransform = colorMatrix;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003523 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003524 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003525
Mathias Agopian85d751c2012-08-29 16:59:24 -07003526 /*
3527 * and then, render the layers targeted at the framebuffer
3528 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003529
Dan Stoza9e56aa02015-11-02 13:00:03 -08003530 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003531 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003532 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003533 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003534 const Region viewportRegion(displayState.viewport);
3535 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003536 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003537 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003538 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003539 switch (layer->getCompositionType(displayDevice)) {
3540 case Hwc2::IComposerClient::Composition::CURSOR:
3541 case Hwc2::IComposerClient::Composition::DEVICE:
3542 case Hwc2::IComposerClient::Composition::SIDEBAND:
3543 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003544 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003545 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003546 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003547 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003548 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003549 // never clear the very first layer since we're
3550 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003551 renderengine::LayerSettings layerSettings;
3552 Region dummyRegion;
3553 bool prepared = layer->prepareClientLayer(renderArea, clip, dummyRegion,
3554 layerSettings);
3555
3556 if (prepared) {
3557 layerSettings.source.buffer.buffer = nullptr;
3558 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3559 layerSettings.alpha = half(0.0);
3560 layerSettings.disableBlending = true;
3561 clientCompositionLayers.push_back(layerSettings);
3562 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003563 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003564 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003565 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003566 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003567 renderengine::LayerSettings layerSettings;
3568 bool prepared =
3569 layer->prepareClientLayer(renderArea, clip, clearRegion, layerSettings);
3570 if (prepared) {
3571 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003572 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003573 break;
3574 }
3575 default:
3576 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003577 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003578 } else {
3579 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003580 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003581 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003582 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003583
Alec Mouri820c7402019-01-23 13:02:39 -08003584 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003585 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003586 clientCompositionDisplay.clearRegion = clearRegion;
3587 if (!debugRegion.isEmpty()) {
3588 Region::const_iterator it = debugRegion.begin();
3589 Region::const_iterator end = debugRegion.end();
3590 while (it != end) {
3591 const Rect& rect = *it++;
3592 renderengine::LayerSettings layerSettings;
3593 layerSettings.source.buffer.buffer = nullptr;
3594 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3595 layerSettings.geometry.boundaries = rect.toFloatRect();
3596 layerSettings.alpha = half(1.0);
3597 clientCompositionLayers.push_back(layerSettings);
3598 }
3599 }
3600 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers,
3601 buf->getNativeBuffer(), readyFence);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003602 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003603 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003604}
3605
Chia-I Wu28e3a252018-09-07 12:05:02 -07003606void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003607 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003608 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609}
3610
Dan Stoza7d89d062015-04-30 13:29:25 -07003611status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003612 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003613 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003614 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003615 const sp<Layer>& parent,
3616 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003617{
Dan Stoza7d89d062015-04-30 13:29:25 -07003618 // add this layer to the current state list
3619 {
3620 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003621 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003622 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3623 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003624 return NO_MEMORY;
3625 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003626 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003627 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003628 } else if (parent == nullptr) {
3629 lbc->onRemovedFromCurrentState();
3630 } else if (parent->isRemovedFromCurrentState()) {
3631 parent->addChild(lbc);
3632 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003633 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003634 parent->addChild(lbc);
3635 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003636
Yiwei Zhang243b3782018-05-15 17:40:04 -07003637 if (gbc != nullptr) {
3638 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3639 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3640 mMaxGraphicBufferProducerListSize,
3641 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3642 mGraphicBufferProducerList.size(),
3643 mMaxGraphicBufferProducerListSize, mNumLayers);
3644 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003645 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003646 }
3647
Mathias Agopian96f08192010-06-02 23:28:45 -07003648 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003649 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003650
Dan Stoza7d89d062015-04-30 13:29:25 -07003651 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003652}
3653
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003654uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003655 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003656}
3657
Mathias Agopian3f844832013-08-07 21:24:32 -07003658uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003659 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660}
3661
Mathias Agopian3f844832013-08-07 21:24:32 -07003662uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003663 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003664}
3665
3666uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003667 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003668 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003669 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003670 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003671 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003672 }
3673 return old;
3674}
3675
Marissa Wall713b63f2018-10-17 15:42:43 -07003676bool SurfaceFlinger::flushTransactionQueues() {
3677 Mutex::Autolock _l(mStateLock);
3678 auto it = mTransactionQueues.begin();
3679 while (it != mTransactionQueues.end()) {
3680 auto& [applyToken, transactionQueue] = *it;
3681
3682 while (!transactionQueue.empty()) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003683 const auto& [states, displays, flags, desiredPresentTime] = transactionQueue.front();
3684 if (!transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003685 break;
3686 }
chaviw273171b2018-12-26 11:46:30 -08003687 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003688 transactionQueue.pop();
3689 }
3690
3691 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3692 }
3693 return mTransactionQueues.empty();
3694}
3695
chaviwca27f252018-02-06 16:46:39 -08003696bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3697 for (const ComposerState& state : states) {
3698 // Here we need to check that the interface we're given is indeed
3699 // one of our own. A malicious client could give us a nullptr
3700 // IInterface, or one of its own or even one of our own but a
3701 // different type. All these situations would cause us to crash.
3702 if (state.client == nullptr) {
3703 return true;
3704 }
3705
3706 sp<IBinder> binder = IInterface::asBinder(state.client);
3707 if (binder == nullptr) {
3708 return true;
3709 }
3710
3711 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3712 return true;
3713 }
3714 }
3715 return false;
3716}
3717
Marissa Wall17b4e452018-12-26 16:32:34 -08003718bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3719 const Vector<ComposerState>& states) {
Ady Abrahamc3e21312019-02-07 14:30:23 -08003720 nsecs_t expectedPresentTime;
3721 if (mUseScheduler) {
3722 expectedPresentTime = mScheduler->expectedPresentTime();
3723 } else {
3724 expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3725 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003726 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3727 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3728 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3729 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3730 return false;
3731 }
3732
Marissa Wall713b63f2018-10-17 15:42:43 -07003733 for (const ComposerState& state : states) {
3734 const layer_state_t& s = state.state;
3735 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3736 continue;
3737 }
3738 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003739 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003740 }
3741 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003742 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003743}
3744
3745void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3746 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003747 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003748 const InputWindowCommands& inputWindowCommands,
3749 int64_t desiredPresentTime) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003750 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003751 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003752
chaviwca27f252018-02-06 16:46:39 -08003753 if (containsAnyInvalidClientState(states)) {
3754 return;
3755 }
3756
Marissa Wall713b63f2018-10-17 15:42:43 -07003757 // If its TransactionQueue already has a pending TransactionState or if it is pending
3758 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003759 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3760 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime);
Marissa Wall713b63f2018-10-17 15:42:43 -07003761 setTransactionFlags(eTransactionNeeded);
3762 return;
3763 }
3764
chaviw273171b2018-12-26 11:46:30 -08003765 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003766}
3767
3768void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003769 const Vector<DisplayState>& displays, uint32_t flags,
3770 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003771 uint32_t transactionFlags = 0;
3772
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003773 if (flags & eAnimation) {
3774 // For window updates that are part of an animation we must wait for
3775 // previous animation "frames" to be handled.
3776 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003777 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003778 if (CC_UNLIKELY(err != NO_ERROR)) {
3779 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003780 // caller after a few seconds.
3781 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3782 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003783 mAnimTransactionPending = false;
3784 break;
3785 }
3786 }
3787 }
3788
chaviwca27f252018-02-06 16:46:39 -08003789 for (const DisplayState& display : displays) {
3790 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003791 }
3792
Marissa Walle2ffb422018-10-12 11:33:52 -07003793 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003794 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003795 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003796 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003797 // If the state doesn't require a traversal and there are callbacks, send them now
3798 if (!(clientStateFlags & eTraversalNeeded)) {
3799 mTransactionCompletedThread.sendCallbacks();
3800 }
3801 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003802
chaviw273171b2018-12-26 11:46:30 -08003803 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3804
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003805 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3806 // anyway. This can be used as a flush mechanism for previous async transactions.
3807 // Empty animation transaction can be used to simulate back-pressure, so also force a
3808 // transaction for empty animation transactions.
3809 if (transactionFlags == 0 &&
3810 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003811 transactionFlags = eTransactionNeeded;
3812 }
3813
Mathias Agopian386aa982011-11-07 21:58:03 -08003814 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003815 if (mInterceptor->isEnabled()) {
3816 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003817 }
Irvel468051e2016-06-13 16:44:44 -07003818
Mathias Agopian386aa982011-11-07 21:58:03 -08003819 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003820 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3821 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003822 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003823
3824 // if this is a synchronous transaction, wait for it to take effect
3825 // before returning.
3826 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003827 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003828 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003829 if (flags & eAnimation) {
3830 mAnimTransactionPending = true;
3831 }
3832 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003833 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3834 if (CC_UNLIKELY(err != NO_ERROR)) {
3835 // just in case something goes wrong in SF, return to the
3836 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003837 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3838 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003839 break;
3840 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003841 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 }
3843}
3844
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003845uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3846 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3847 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003848
Mathias Agopiane57f2922012-08-09 16:29:12 -07003849 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003850 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3851
3852 const uint32_t what = s.what;
3853 if (what & DisplayState::eSurfaceChanged) {
3854 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3855 state.surface = s.surface;
3856 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003857 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003858 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003859 if (what & DisplayState::eLayerStackChanged) {
3860 if (state.layerStack != s.layerStack) {
3861 state.layerStack = s.layerStack;
3862 flags |= eDisplayTransactionNeeded;
3863 }
3864 }
3865 if (what & DisplayState::eDisplayProjectionChanged) {
3866 if (state.orientation != s.orientation) {
3867 state.orientation = s.orientation;
3868 flags |= eDisplayTransactionNeeded;
3869 }
3870 if (state.frame != s.frame) {
3871 state.frame = s.frame;
3872 flags |= eDisplayTransactionNeeded;
3873 }
3874 if (state.viewport != s.viewport) {
3875 state.viewport = s.viewport;
3876 flags |= eDisplayTransactionNeeded;
3877 }
3878 }
3879 if (what & DisplayState::eDisplaySizeChanged) {
3880 if (state.width != s.width) {
3881 state.width = s.width;
3882 flags |= eDisplayTransactionNeeded;
3883 }
3884 if (state.height != s.height) {
3885 state.height = s.height;
3886 flags |= eDisplayTransactionNeeded;
3887 }
3888 }
3889
Mathias Agopiane57f2922012-08-09 16:29:12 -07003890 return flags;
3891}
3892
Robert Carrd4ae7f32018-06-07 16:10:57 -07003893bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3894 IPCThreadState* ipc = IPCThreadState::self();
3895 const int pid = ipc->getCallingPid();
3896 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003897 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003898 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003899 return false;
3900 }
3901 return true;
3902}
3903
chaviwca27f252018-02-06 16:46:39 -08003904uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3905 const layer_state_t& s = composerState.state;
3906 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3907
Mathias Agopian13127d82013-03-05 17:47:11 -08003908 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003909 if (layer == nullptr) {
3910 return 0;
3911 }
3912
chaviw8b3871a2017-11-01 17:41:01 -07003913 uint32_t flags = 0;
3914
Garfield Tan8a3083e2018-12-03 13:21:07 -08003915 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003916 bool geometryAppliesWithResize =
3917 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003918
3919 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3920 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003921 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003922 layer->pushPendingState();
3923 }
3924
chaviw8b3871a2017-11-01 17:41:01 -07003925 if (what & layer_state_t::ePositionChanged) {
3926 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3927 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003928 }
chaviw8b3871a2017-11-01 17:41:01 -07003929 }
3930 if (what & layer_state_t::eLayerChanged) {
3931 // NOTE: index needs to be calculated before we update the state
3932 const auto& p = layer->getParent();
3933 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003934 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003935 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003936 mCurrentState.layersSortedByZ.removeAt(idx);
3937 mCurrentState.layersSortedByZ.add(layer);
3938 // we need traversal (state changed)
3939 // AND transaction (list changed)
3940 flags |= eTransactionNeeded|eTraversalNeeded;
3941 }
chaviw8b3871a2017-11-01 17:41:01 -07003942 } else {
3943 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003944 flags |= eTransactionNeeded|eTraversalNeeded;
3945 }
3946 }
chaviw8b3871a2017-11-01 17:41:01 -07003947 }
3948 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003949 // NOTE: index needs to be calculated before we update the state
3950 const auto& p = layer->getParent();
3951 if (p == nullptr) {
3952 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3953 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3954 mCurrentState.layersSortedByZ.removeAt(idx);
3955 mCurrentState.layersSortedByZ.add(layer);
3956 // we need traversal (state changed)
3957 // AND transaction (list changed)
3958 flags |= eTransactionNeeded|eTraversalNeeded;
3959 }
3960 } else {
3961 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3962 flags |= eTransactionNeeded|eTraversalNeeded;
3963 }
chaviw8b3871a2017-11-01 17:41:01 -07003964 }
3965 }
3966 if (what & layer_state_t::eSizeChanged) {
3967 if (layer->setSize(s.w, s.h)) {
3968 flags |= eTraversalNeeded;
3969 }
3970 }
3971 if (what & layer_state_t::eAlphaChanged) {
3972 if (layer->setAlpha(s.alpha))
3973 flags |= eTraversalNeeded;
3974 }
3975 if (what & layer_state_t::eColorChanged) {
3976 if (layer->setColor(s.color))
3977 flags |= eTraversalNeeded;
3978 }
Peiyong Lind3788632018-09-18 16:01:31 -07003979 if (what & layer_state_t::eColorTransformChanged) {
3980 if (layer->setColorTransform(s.colorTransform)) {
3981 flags |= eTraversalNeeded;
3982 }
3983 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003984 if (what & layer_state_t::eBackgroundColorChanged) {
3985 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3986 flags |= eTraversalNeeded;
3987 }
3988 }
chaviw8b3871a2017-11-01 17:41:01 -07003989 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003990 // TODO: b/109894387
3991 //
3992 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3993 // rotation. To see the problem observe that if we have a square parent, and a child
3994 // of the same size, then we rotate the child 45 degrees around it's center, the child
3995 // must now be cropped to a non rectangular 8 sided region.
3996 //
3997 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3998 // private API, and the WindowManager only uses rotation in one case, which is on a top
3999 // level layer in which cropping is not an issue.
4000 //
4001 // However given that abuse of rotation matrices could lead to surfaces extending outside
4002 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4003 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4004 // transformations.
4005 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07004006 flags |= eTraversalNeeded;
4007 }
4008 if (what & layer_state_t::eTransparentRegionChanged) {
4009 if (layer->setTransparentRegionHint(s.transparentRegion))
4010 flags |= eTraversalNeeded;
4011 }
4012 if (what & layer_state_t::eFlagsChanged) {
4013 if (layer->setFlags(s.flags, s.mask))
4014 flags |= eTraversalNeeded;
4015 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004016 if (what & layer_state_t::eCropChanged_legacy) {
4017 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004018 flags |= eTraversalNeeded;
4019 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004020 if (what & layer_state_t::eCornerRadiusChanged) {
4021 if (layer->setCornerRadius(s.cornerRadius))
4022 flags |= eTraversalNeeded;
4023 }
chaviw8b3871a2017-11-01 17:41:01 -07004024 if (what & layer_state_t::eLayerStackChanged) {
4025 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4026 // We only allow setting layer stacks for top level layers,
4027 // everything else inherits layer stack from its parent.
4028 if (layer->hasParent()) {
4029 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4030 layer->getName().string());
4031 } else if (idx < 0) {
4032 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4033 "that also does not appear in the top level layer list. Something"
4034 " has gone wrong.", layer->getName().string());
4035 } else if (layer->setLayerStack(s.layerStack)) {
4036 mCurrentState.layersSortedByZ.removeAt(idx);
4037 mCurrentState.layersSortedByZ.add(layer);
4038 // we need traversal (state changed)
4039 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004040 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004041 }
4042 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004043 if (what & layer_state_t::eDeferTransaction_legacy) {
4044 if (s.barrierHandle_legacy != nullptr) {
4045 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4046 } else if (s.barrierGbp_legacy != nullptr) {
4047 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004048 if (authenticateSurfaceTextureLocked(gbp)) {
4049 const auto& otherLayer =
4050 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004051 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004052 } else {
4053 ALOGE("Attempt to defer transaction to to an"
4054 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004055 }
4056 }
chaviw8b3871a2017-11-01 17:41:01 -07004057 // We don't trigger a traversal here because if no other state is
4058 // changed, we don't want this to cause any more work
4059 }
4060 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004061 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004062 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004063 if (!hadParent) {
4064 mCurrentState.layersSortedByZ.remove(layer);
4065 }
chaviw8b3871a2017-11-01 17:41:01 -07004066 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004067 }
chaviw8b3871a2017-11-01 17:41:01 -07004068 }
4069 if (what & layer_state_t::eReparentChildren) {
4070 if (layer->reparentChildren(s.reparentHandle)) {
4071 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004072 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004073 }
chaviw8b3871a2017-11-01 17:41:01 -07004074 if (what & layer_state_t::eDetachChildren) {
4075 layer->detachChildren();
4076 }
4077 if (what & layer_state_t::eOverrideScalingModeChanged) {
4078 layer->setOverrideScalingMode(s.overrideScalingMode);
4079 // We don't trigger a traversal here because if no other state is
4080 // changed, we don't want this to cause any more work
4081 }
Marissa Wall61c58622018-07-18 10:12:20 -07004082 if (what & layer_state_t::eTransformChanged) {
4083 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4084 }
4085 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4086 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4087 flags |= eTraversalNeeded;
4088 }
4089 if (what & layer_state_t::eCropChanged) {
4090 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4091 }
Marissa Wall861616d2018-10-22 12:52:23 -07004092 if (what & layer_state_t::eFrameChanged) {
4093 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4094 }
Marissa Wall61c58622018-07-18 10:12:20 -07004095 if (what & layer_state_t::eAcquireFenceChanged) {
4096 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4097 }
4098 if (what & layer_state_t::eDataspaceChanged) {
4099 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4100 }
4101 if (what & layer_state_t::eHdrMetadataChanged) {
4102 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4103 }
4104 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4105 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4106 }
4107 if (what & layer_state_t::eApiChanged) {
4108 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4109 }
4110 if (what & layer_state_t::eSidebandStreamChanged) {
4111 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4112 }
Robert Carr720e5062018-07-30 17:45:14 -07004113 if (what & layer_state_t::eInputInfoChanged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004114 if (callingThreadHasUnscopedSurfaceFlingerAccess()) {
4115 layer->setInputInfo(s.inputInfo);
4116 flags |= eTraversalNeeded;
4117 } else {
4118 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4119 }
Robert Carr720e5062018-07-30 17:45:14 -07004120 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004121 if (what & layer_state_t::eMetadataChanged) {
4122 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4123 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004124 std::vector<sp<CallbackHandle>> callbackHandles;
4125 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
4126 mTransactionCompletedThread.run();
4127 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
4128 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4129 }
4130 }
Marissa Wall73411622019-01-25 10:45:41 -08004131
4132 if (what & layer_state_t::eBufferChanged) {
4133 // Add the new buffer to the cache. This should always come before eCachedBufferChanged.
4134 BufferStateLayerCache::getInstance().add(s.cachedBuffer.token, s.cachedBuffer.bufferId,
4135 s.buffer);
4136 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004137 if (what & layer_state_t::eCachedBufferChanged) {
4138 sp<GraphicBuffer> buffer =
Marissa Wall73411622019-01-25 10:45:41 -08004139 BufferStateLayerCache::getInstance().get(s.cachedBuffer.token,
4140 s.cachedBuffer.bufferId);
Marissa Wallebc2c052019-01-16 19:16:55 -08004141 if (layer->setBuffer(buffer)) flags |= eTraversalNeeded;
4142 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004143 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4144 // Do not put anything that updates layer state or modifies flags after
4145 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004146 return flags;
4147}
4148
chaviw273171b2018-12-26 11:46:30 -08004149uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4150 uint32_t flags = 0;
4151 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4152 flags |= eTraversalNeeded;
4153 }
4154
4155 mInputWindowCommands.merge(inputWindowCommands);
4156 return flags;
4157}
4158
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004159status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4160 uint32_t h, PixelFormat format, uint32_t flags,
4161 LayerMetadata metadata, sp<IBinder>* handle,
4162 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004163 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004164 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004165 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004166 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004167 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004168
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004169 status_t result = NO_ERROR;
4170
4171 sp<Layer> layer;
4172
Cody Northropbc755282017-03-31 12:00:08 -06004173 String8 uniqueName = getUniqueLayerName(name);
4174
Mathias Agopian3165cc22012-08-08 19:42:09 -07004175 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004176 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07004177 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
4178 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004179
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004180 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004181 case ISurfaceComposerClient::eFXSurfaceBufferState:
4182 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
4183 break;
chaviw13fdc492017-06-27 12:40:18 -07004184 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004185 // check if buffer size is set for color layer.
4186 if (w > 0 || h > 0) {
4187 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4188 int(w), int(h));
4189 return BAD_VALUE;
4190 }
4191
chaviw13fdc492017-06-27 12:40:18 -07004192 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06004193 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004194 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004195 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004196 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004197 // check if buffer size is set for container layer.
4198 if (w > 0 || h > 0) {
4199 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4200 int(w), int(h));
4201 return BAD_VALUE;
4202 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07004203 result = createContainerLayer(client,
4204 uniqueName, w, h, flags,
4205 handle, &layer);
4206 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004207 default:
4208 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209 break;
4210 }
4211
Dan Stoza7d89d062015-04-30 13:29:25 -07004212 if (result != NO_ERROR) {
4213 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004214 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004215
Chia-I Wuab0c3192017-08-01 11:29:00 -07004216 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4217 // TODO b/64227542
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004218 if (metadata.has(METADATA_WINDOW_TYPE)) {
4219 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4220 if (windowType == 441731) {
4221 metadata.setInt32(METADATA_WINDOW_TYPE, 2024); // TYPE_NAVIGATION_BAR_PANEL
4222 layer->setPrimaryDisplayOnly();
4223 }
Chia-I Wuab0c3192017-08-01 11:29:00 -07004224 }
4225
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004226 layer->setMetadata(std::move(metadata));
Albert Chaulk479c60c2017-01-27 14:21:34 -05004227
Robert Carrb89ea9d2018-12-10 13:01:14 -08004228 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4229 result = addClientLayer(client, *handle, *gbp, layer, *parent,
4230 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004231 if (result != NO_ERROR) {
4232 return result;
4233 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004234 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004235
4236 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004237 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004238}
4239
Cody Northropbc755282017-03-31 12:00:08 -06004240String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4241{
4242 bool matchFound = true;
4243 uint32_t dupeCounter = 0;
4244
4245 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4246 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4247
Dan Stoza436ccf32018-06-21 12:10:12 -07004248 // Grab the state lock since we're accessing mCurrentState
4249 Mutex::Autolock lock(mStateLock);
4250
Cody Northropbc755282017-03-31 12:00:08 -06004251 // Loop over layers until we're sure there is no matching name
4252 while (matchFound) {
4253 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004254 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004255 if (layer->getName() == uniqueName) {
4256 matchFound = true;
4257 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4258 }
4259 });
4260 }
4261
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004262 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4263 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004264
4265 return uniqueName;
4266}
4267
Marissa Wallfd668622018-05-10 10:21:13 -07004268status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4269 uint32_t w, uint32_t h, uint32_t flags,
4270 PixelFormat& format, sp<IBinder>* handle,
4271 sp<IGraphicBufferProducer>* gbp,
4272 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004274 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004275 case PIXEL_FORMAT_TRANSPARENT:
4276 case PIXEL_FORMAT_TRANSLUCENT:
4277 format = PIXEL_FORMAT_RGBA_8888;
4278 break;
4279 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004280 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004281 break;
4282 }
4283
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004284 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004285 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07004286 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004287 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004288 *handle = layer->getHandle();
4289 *gbp = layer->getProducer();
4290 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004291 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004292
Marissa Wallfd668622018-05-10 10:21:13 -07004293 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004294 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004295}
4296
Marissa Wall61c58622018-07-18 10:12:20 -07004297status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4298 uint32_t w, uint32_t h, uint32_t flags,
4299 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07004300 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07004301 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07004302 *handle = layer->getHandle();
4303 *outLayer = layer;
4304
4305 return NO_ERROR;
4306}
4307
chaviw13fdc492017-06-27 12:40:18 -07004308status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004309 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07004310 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004311{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004312 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004313 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004314 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004315}
4316
Robert Carr6b3f6c52018-08-13 13:05:17 -07004317status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
4318 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
4319 sp<IBinder>* handle, sp<Layer>* outLayer)
4320{
Lloyd Pique90c115d2018-09-18 21:39:42 -07004321 *outLayer =
4322 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004323 *handle = (*outLayer)->getHandle();
4324 return NO_ERROR;
4325}
4326
4327
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004328void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004329 mLayersPendingRemoval.add(layer);
4330 mLayersRemoved = true;
4331 setTransactionFlags(eTransactionNeeded);
4332}
4333
Robert Carr695d5282018-12-18 15:27:58 -08004334void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004335{
Robert Carr2e102c92018-10-23 12:11:15 -07004336 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004337 // If a layer has a parent, we allow it to out-live it's handle
4338 // with the idea that the parent holds a reference and will eventually
4339 // be cleaned up. However no one cleans up the top-level so we do so
4340 // here.
4341 if (layer->getParent() == nullptr) {
4342 mCurrentState.layersSortedByZ.remove(layer);
4343 }
4344 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004345 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004346}
4347
Mathias Agopianb60314a2012-04-10 22:09:54 -07004348// ---------------------------------------------------------------------------
4349
Andy McFadden13a082e2012-08-24 10:16:42 -07004350void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004351 const auto display = getDefaultDisplayDeviceLocked();
4352 if (!display) return;
4353
4354 const sp<IBinder> token = display->getDisplayToken().promote();
4355 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004356
Jesse Hall01e29052013-02-19 16:13:35 -08004357 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004358 Vector<ComposerState> state;
4359 Vector<DisplayState> displays;
4360 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004361 d.what = DisplayState::eDisplayProjectionChanged |
4362 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004363 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004364 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004365 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004366 d.frame.makeInvalid();
4367 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004368 d.width = 0;
4369 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004370 displays.add(d);
Marissa Wall17b4e452018-12-26 16:32:34 -08004371 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands, -1);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004372
Dominik Laskowskie9774092018-12-11 10:04:24 -08004373 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004374
Dominik Laskowski83b88212018-12-11 13:34:06 -08004375 const nsecs_t vsyncPeriod = getVsyncPeriod();
4376 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004377
Brian Andersond0010582017-03-07 13:20:31 -08004378 // Use phase of 0 since phase is not known.
4379 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004380 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004381 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004382}
4383
4384void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004385 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004386 postMessageAsync(
4387 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004388}
4389
Dominik Laskowskie9774092018-12-11 10:04:24 -08004390void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004391 if (display->isVirtual()) {
4392 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004393 return;
4394 }
4395
Dominik Laskowski075d3172018-05-24 15:50:06 -07004396 const auto displayId = display->getId();
4397 LOG_ALWAYS_FATAL_IF(!displayId);
4398
Dominik Laskowski34157762018-10-31 13:07:19 -07004399 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004400
4401 int currentMode = display->getPowerMode();
4402 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004403 return;
4404 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004405
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004406 display->setPowerMode(mode);
4407
Lloyd Pique4dccc412018-01-22 17:21:36 -08004408 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004409 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004410 }
4411
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004412 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004413 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004414 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004415 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004416 if (mUseScheduler) {
4417 mScheduler->onScreenAcquired(mAppConnectionHandle);
4418 } else {
4419 mEventThread->onScreenAcquired();
4420 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004421 resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004423
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004424 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004425 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004426 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004427
4428 struct sched_param param = {0};
4429 param.sched_priority = 1;
4430 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4431 ALOGW("Couldn't set SCHED_FIFO on display on");
4432 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004433 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004434 // Turn off the display
4435 struct sched_param param = {0};
4436 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4437 ALOGW("Couldn't set SCHED_OTHER on display off");
4438 }
4439
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004440 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004441 if (mUseScheduler) {
4442 mScheduler->disableHardwareVsync(true);
4443 } else {
4444 disableHardwareVsync(true); // also cancels any in-progress resync
4445 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004446 if (mUseScheduler) {
4447 mScheduler->onScreenReleased(mAppConnectionHandle);
4448 } else {
4449 mEventThread->onScreenReleased();
4450 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004451 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004452
Dominik Laskowski075d3172018-05-24 15:50:06 -07004453 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004454 mVisibleRegionsDirty = true;
4455 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004456 } else if (mode == HWC_POWER_MODE_DOZE ||
4457 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004458 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004459 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004460 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004461 if (mUseScheduler) {
4462 mScheduler->onScreenAcquired(mAppConnectionHandle);
4463 } else {
4464 mEventThread->onScreenAcquired();
4465 }
Dominik Laskowski83b88212018-12-11 13:34:06 -08004466 resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004467 }
4468 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4469 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004470 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004471 if (mUseScheduler) {
4472 mScheduler->disableHardwareVsync(true);
4473 } else {
4474 disableHardwareVsync(true); // also cancels any in-progress resync
4475 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004476 if (mUseScheduler) {
4477 mScheduler->onScreenReleased(mAppConnectionHandle);
4478 } else {
4479 mEventThread->onScreenReleased();
4480 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004481 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004482 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004483 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004484 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004485 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004486 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004487
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004488 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004489 mTimeStats->setPowerMode(mode);
Ana Krulec4593b692019-01-11 22:07:25 -08004490 if (mUseScheduler && mRefreshRateStats) {
Ana Krulecb43429d2019-01-09 14:28:51 -08004491 // Update refresh rate stats.
4492 mRefreshRateStats->setPowerMode(mode);
4493 }
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004494 }
4495
Dominik Laskowski34157762018-10-31 13:07:19 -07004496 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004497}
4498
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004499void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004500 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004501 const auto display = getDisplayDevice(displayToken);
4502 if (!display) {
4503 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4504 displayToken.get());
4505 } else if (display->isVirtual()) {
4506 ALOGW("Attempt to set power mode %d for virtual display", mode);
4507 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004508 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004509 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004510 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004511}
4512
4513// ---------------------------------------------------------------------------
4514
Dominik Laskowskic2867142019-01-21 11:33:38 -08004515status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4516 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004518
Mathias Agopianbd115332013-04-18 16:41:04 -07004519 IPCThreadState* ipc = IPCThreadState::self();
4520 const int pid = ipc->getCallingPid();
4521 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004522
Mathias Agopianbd115332013-04-18 16:41:04 -07004523 if ((uid != AID_SHELL) &&
4524 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4526 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004528 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004529 // (this would indicate SF is stuck, but we want to be able to
4530 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004531 status_t err = mStateLock.timedLock(s2ns(1));
4532 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004533 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004534 StringAppendF(&result,
4535 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4536 "(no locks held)\n",
4537 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004538 }
4539
Dominik Laskowskic2867142019-01-21 11:33:38 -08004540 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004541
Dominik Laskowskic2867142019-01-21 11:33:38 -08004542 static const std::unordered_map<std::string, Dumper> dumpers = {
4543 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4544 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4545 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004546 {"--dispsync"s, dumper([this](std::string& s) {
4547 if (mUseScheduler) {
4548 mScheduler->dumpPrimaryDispSync(s);
4549 } else {
4550 mPrimaryDispSync->dump(s);
4551 }
4552 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004553 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4554 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4555 {"--frame-composition"s, dumper(&SurfaceFlinger::dumpFrameCompositionInfo)},
4556 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4557 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4558 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4559 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4560 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4561 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004562 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004563 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4564 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004565
Dominik Laskowskic2867142019-01-21 11:33:38 -08004566 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004567
Dominik Laskowskic2867142019-01-21 11:33:38 -08004568 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4569 (it->second)(args, asProto, result);
4570 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004571 if (asProto) {
4572 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4573 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4574 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004575 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004576 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004577 }
4578
Mathias Agopian9795c422009-08-26 16:36:26 -07004579 if (locked) {
4580 mStateLock.unlock();
4581 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004582 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004583 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004584 return NO_ERROR;
4585}
4586
Dominik Laskowskic2867142019-01-21 11:33:38 -08004587void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 mCurrentState.traverseInZOrder(
4589 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004590}
4591
Dominik Laskowskic2867142019-01-21 11:33:38 -08004592void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004593 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004594
Dominik Laskowskic2867142019-01-21 11:33:38 -08004595 if (args.size() > 1) {
4596 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004597 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004598 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004599 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004600 }
Robert Carr2047fae2016-11-28 14:09:09 -08004601 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004602 } else {
4603 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004604 }
4605}
4606
Dominik Laskowskic2867142019-01-21 11:33:38 -08004607void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004608 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004609 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004610 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004611 }
Robert Carr2047fae2016-11-28 14:09:09 -08004612 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004613
Svetoslavd85084b2014-03-20 10:28:31 -07004614 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004615}
4616
Dominik Laskowskic2867142019-01-21 11:33:38 -08004617void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4618 mTimeStats->parseArgs(asProto, args, result);
4619}
4620
Jamie Gennis6547ff42013-07-16 20:12:42 -07004621// This should only be called from the main thread. Otherwise it would need
4622// the lock and should use mCurrentState rather than mDrawingState.
4623void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004624 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004625 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004626 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004627
4628 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4629}
4630
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004632 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004633
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004634 if (isLayerTripleBufferingDisabled())
4635 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004636
Yiwei Zhang5434a782018-12-05 18:06:32 -08004637 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4638 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4639 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4640 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4641 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4642 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004643 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004644}
4645
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004646void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004647 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004648 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004649 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004650 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004651
4652 StringAppendF(&result, "Scheduler: %s\n\n", mUseScheduler ? "enabled" : "disabled");
4653
4654 if (mUseScheduler) {
4655 mScheduler->dump(mAppConnectionHandle, result);
4656 } else {
4657 mEventThread->dump(result);
4658 }
4659}
4660
Yiwei Zhang5434a782018-12-05 18:06:32 -08004661void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4662 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004663 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4664 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004665 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004666 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004668 }
David Sodman4a36e932017-11-07 14:29:47 -08004669 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004670 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004671 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4673 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004674}
4675
Dan Stozae77c7662016-05-13 11:37:28 -07004676void SurfaceFlinger::recordBufferingStats(const char* layerName,
4677 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004678 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4679 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004680 for (const auto& segment : history) {
4681 if (!segment.usedThirdBuffer) {
4682 stats.twoBufferTime += segment.totalTime;
4683 }
4684 if (segment.occupancyAverage < 1.0f) {
4685 stats.doubleBufferedTime += segment.totalTime;
4686 } else if (segment.occupancyAverage < 2.0f) {
4687 stats.tripleBufferedTime += segment.totalTime;
4688 }
4689 ++stats.numSegments;
4690 stats.totalTime += segment.totalTime;
4691 }
4692}
4693
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4695 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004696
4697 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4698 const size_t count = currentLayers.size();
4699 for (size_t i=0 ; i<count ; i++) {
4700 currentLayers[i]->dumpFrameEvents(result);
4701 }
4702}
4703
Yiwei Zhang5434a782018-12-05 18:06:32 -08004704void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004705 result.append("Buffering stats:\n");
4706 result.append(" [Layer name] <Active time> <Two buffer> "
4707 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004708 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004709 typedef std::tuple<std::string, float, float, float> BufferTuple;
4710 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004711 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004712 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004713 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004714 if (stats.numSegments == 0) {
4715 continue;
4716 }
4717 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4718 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4719 stats.totalTime;
4720 float doubleBufferRatio = static_cast<float>(
4721 stats.doubleBufferedTime) / stats.totalTime;
4722 float tripleBufferRatio = static_cast<float>(
4723 stats.tripleBufferedTime) / stats.totalTime;
4724 sorted.insert({activeTime, {name, twoBufferRatio,
4725 doubleBufferRatio, tripleBufferRatio}});
4726 }
4727 for (const auto& sortedPair : sorted) {
4728 float activeTime = sortedPair.first;
4729 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4731 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004732 }
4733 result.append("\n");
4734}
4735
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 const auto displayId = display->getId();
4739 if (!displayId) {
4740 continue;
4741 }
4742 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004743 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004744 continue;
4745 }
4746
Yiwei Zhang5434a782018-12-05 18:06:32 -08004747 StringAppendF(&result,
4748 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4749 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004750 uint8_t port;
4751 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004752 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004753 result.append("no identification data\n");
4754 continue;
4755 }
4756
4757 if (!isEdid(data)) {
4758 result.append("unknown identification data: ");
4759 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004760 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004761 }
4762 result.append("\n");
4763 continue;
4764 }
4765
4766 const auto edid = parseEdid(data);
4767 if (!edid) {
4768 result.append("invalid EDID: ");
4769 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004771 }
4772 result.append("\n");
4773 continue;
4774 }
4775
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004777 result.append(edid->displayName.data(), edid->displayName.length());
4778 result.append("\"\n");
4779 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004780}
4781
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4783 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4784 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4785 StringAppendF(&result, "DisplayColorSetting: %s\n",
4786 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004787
4788 // TODO: print out if wide-color mode is active or not
4789
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004790 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004791 const auto displayId = display->getId();
4792 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004793 continue;
4794 }
4795
Yiwei Zhang5434a782018-12-05 18:06:32 -08004796 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004797 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004798 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004799 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004800 }
4801
Lloyd Pique32cbe282018-10-19 13:09:22 -07004802 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004803 StringAppendF(&result, " Current color mode: %s (%d)\n",
4804 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004805 }
4806 result.append("\n");
4807}
4808
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004810 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004811 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4812 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004813 continue;
4814 }
4815
Dominik Laskowski05275f12018-11-01 15:03:24 -07004816 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004817 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4818 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004819 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004820 compositionInfo.dump(result, nullptr);
4821 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004822 }
4823 }
David Sodman7e4ae112018-02-09 15:02:28 -08004824}
4825
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004826LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004827 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004828 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4829 const State& state = useDrawing ? mDrawingState : mCurrentState;
4830 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004831 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004832 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004833 });
4834
4835 return layersProto;
4836}
4837
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004838LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4839 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004840 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004841
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004842 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004843 resolution->set_w(displayDevice->getWidth());
4844 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004845
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004846 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004847 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004848
Lloyd Pique32cbe282018-10-19 13:09:22 -07004849 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4850 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4851 layersProto.set_global_transform(displayState.orientation);
4852
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004853 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004854 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004855 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004856 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004857 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004858 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004859 }
4860 });
4861
4862 return layersProto;
4863}
4864
Dominik Laskowskic2867142019-01-21 11:33:38 -08004865void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4866 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004867 Colorizer colorizer(colorize);
4868
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004869 // figure out if we're stuck somewhere
4870 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004871 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004872 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4873
4874 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004875 * Dump library configuration.
4876 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004877
4878 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004879 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004880 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004881 appendSfConfigString(result);
4882 appendUiConfigString(result);
4883 appendGuiConfigString(result);
4884 result.append("\n");
4885
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004886 result.append("\nDisplay identification data:\n");
4887 dumpDisplayIdentificationData(result);
4888
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004889 result.append("\nWide-Color information:\n");
4890 dumpWideColorInfo(result);
4891
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004892 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004893 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004894 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004895 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004896 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004897
Andy McFadden41d67d72014-04-25 16:58:34 -07004898 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004899 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004900 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004901 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004902 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004903
Dan Stozab90cf072015-03-05 11:05:59 -08004904 dumpStaticScreenStats(result);
4905 result.append("\n");
4906
Yiwei Zhang5434a782018-12-05 18:06:32 -08004907 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004908
Dan Stozae77c7662016-05-13 11:37:28 -07004909 dumpBufferingStats(result);
4910
Andy McFadden4803b742012-09-24 19:07:20 -07004911 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004912 * Dump the visible layer list
4913 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004914 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004915 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4916 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4917 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004918 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004919
Chia-I Wu2f884132018-09-13 15:17:58 -07004920 {
4921 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4922 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004923 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004924 result.append("\n");
4925 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004926
David Sodman7e4ae112018-02-09 15:02:28 -08004927 result.append("\nFrame-Composition information:\n");
4928 dumpFrameCompositionInfo(result);
4929 result.append("\n");
4930
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004931 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004932 * Dump Display state
4933 */
4934
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004935 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004936 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004937 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004938 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004939 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004940 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004941 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004942
4943 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004944 * Dump SurfaceFlinger global state
4945 */
4946
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004947 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004948 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004949 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004950
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004951 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004952
Dominik Laskowski075d3172018-05-24 15:50:06 -07004953 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004954 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4955 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004956 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4957 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004958 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004959 StringAppendF(&result,
4960 " transaction-flags : %08x\n"
4961 " gpu_to_cpu_unsupported : %d\n",
4962 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004963
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004964 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004965 displayId && getHwComposer().isConnected(*displayId)) {
4966 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004967 StringAppendF(&result,
4968 " refresh-rate : %f fps\n"
4969 " x-dpi : %f\n"
4970 " y-dpi : %f\n",
4971 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4972 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004973 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004974
Yiwei Zhang5434a782018-12-05 18:06:32 -08004975 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004976
Dan Stozae22aec72016-08-01 13:20:59 -07004977 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004978 * Tracing state
4979 */
4980 mTracing.dump(result);
4981 result.append("\n");
4982
4983 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004984 * HWC layer minidump
4985 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004986 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004987 const auto displayId = display->getId();
4988 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004989 continue;
4990 }
4991
Yiwei Zhang5434a782018-12-05 18:06:32 -08004992 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004993 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004994 const sp<DisplayDevice> displayDevice = display;
4995 mCurrentState.traverseInZOrder(
4996 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004997 result.append("\n");
4998 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004999
5000 /*
5001 * Dump HWComposer state
5002 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005003 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005004 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005005 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005006 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005007 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005008 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005009
5010 /*
5011 * Dump gralloc state
5012 */
5013 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5014 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005015
5016 /*
5017 * Dump VrFlinger state if in use.
5018 */
5019 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5020 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005021 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005022 result.append("\n");
5023 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005024
5025 /**
5026 * Scheduler dump state.
5027 */
5028 if (mUseScheduler) {
5029 result.append("\nScheduler state:\n");
5030 result.append(mScheduler->doDump() + "\n");
5031 result.append(mRefreshRateStats->doDump() + "\n");
5032 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005033}
5034
Dominik Laskowski075d3172018-05-24 15:50:06 -07005035const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005036 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005037 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005038 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005039 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005040 }
5041 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005042
Dominik Laskowski34157762018-10-31 13:07:19 -07005043 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005044 static const Vector<sp<Layer>> empty;
5045 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005046}
5047
Chia-I Wu28f320b2018-05-03 11:02:56 -07005048void SurfaceFlinger::updateColorMatrixLocked() {
5049 mat4 colorMatrix;
5050 if (mGlobalSaturationFactor != 1.0f) {
5051 // Rec.709 luma coefficients
5052 float3 luminance{0.213f, 0.715f, 0.072f};
5053 luminance *= 1.0f - mGlobalSaturationFactor;
5054 mat4 saturationMatrix = mat4(
5055 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5056 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5057 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5058 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5059 );
5060 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5061 } else {
5062 colorMatrix = mClientColorMatrix * mDaltonizer();
5063 }
5064
5065 if (mCurrentState.colorMatrix != colorMatrix) {
5066 mCurrentState.colorMatrix = colorMatrix;
5067 mCurrentState.colorMatrixChanged = true;
5068 setTransactionFlags(eTransactionNeeded);
5069 }
5070}
5071
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005072status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005073#pragma clang diagnostic push
5074#pragma clang diagnostic error "-Wswitch-enum"
5075 switch (static_cast<ISurfaceComposerTag>(code)) {
5076 // These methods should at minimum make sure that the client requested
5077 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005078 case BOOT_FINISHED:
5079 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005080 case CREATE_DISPLAY:
5081 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005082 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005083 case GET_ACTIVE_COLOR_MODE:
5084 case GET_ANIMATION_FRAME_STATS:
5085 case GET_HDR_CAPABILITIES:
5086 case SET_ACTIVE_CONFIG:
5087 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005088 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005089 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005090 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005091 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5092 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005093 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5094 IPCThreadState* ipc = IPCThreadState::self();
5095 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5096 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005097 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005098 }
Robert Carr1db73f62016-12-21 12:58:51 -08005099 return OK;
5100 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005101 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005102 IPCThreadState* ipc = IPCThreadState::self();
5103 const int pid = ipc->getCallingPid();
5104 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005105 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5106 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005107 return PERMISSION_DENIED;
5108 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005109 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005110 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005111 // Used by apps to hook Choreographer to SurfaceFlinger.
5112 case CREATE_DISPLAY_EVENT_CONNECTION:
5113 // The following calls are currently used by clients that do not
5114 // request necessary permissions. However, they do not expose any secret
5115 // information, so it is OK to pass them.
5116 case AUTHENTICATE_SURFACE:
5117 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005118 case GET_PHYSICAL_DISPLAY_IDS:
5119 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005120 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005121 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005122 case GET_DISPLAY_CONFIGS:
5123 case GET_DISPLAY_STATS:
5124 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5125 // Calling setTransactionState is safe, because you need to have been
5126 // granted a reference to Client* and Handle* to do anything with it.
5127 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005128 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005129 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005130 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005131 case GET_PROTECTED_CONTENT_SUPPORT:
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08005132 case IS_WIDE_COLOR_DISPLAY: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005133 return OK;
5134 }
5135 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005136 case CAPTURE_SCREEN:
5137 case ADD_REGION_SAMPLING_LISTENER:
5138 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005139 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005140 IPCThreadState* ipc = IPCThreadState::self();
5141 const int pid = ipc->getCallingPid();
5142 const int uid = ipc->getCallingUid();
5143 if ((uid != AID_GRAPHICS) &&
5144 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5145 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5146 return PERMISSION_DENIED;
5147 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005148 return OK;
5149 }
5150 // The following codes are deprecated and should never be allowed to access SF.
5151 case CONNECT_DISPLAY_UNUSED:
5152 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5153 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5154 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005155 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005157
5158 // These codes are used for the IBinder protocol to either interrogate the recipient
5159 // side of the transaction for its canonical interface descriptor or to dump its state.
5160 // We let them pass by default.
5161 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5162 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5163 code == IBinder::SYSPROPS_TRANSACTION) {
5164 return OK;
5165 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005166 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005167 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08005168 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005169 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5170 return OK;
5171 }
5172 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5173 return PERMISSION_DENIED;
5174#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005175}
5176
Ana Krulec13be8ad2018-08-21 02:43:56 +00005177status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5178 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005179 status_t credentialCheck = CheckTransactCodeCredentials(code);
5180 if (credentialCheck != OK) {
5181 return credentialCheck;
5182 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005184 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5185 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005186 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005187 IPCThreadState* ipc = IPCThreadState::self();
5188 const int uid = ipc->getCallingUid();
5189 if (CC_UNLIKELY(uid != AID_SYSTEM
5190 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005191 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005192 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005193 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005194 return PERMISSION_DENIED;
5195 }
5196 int n;
5197 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005198 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005199 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005200 return NO_ERROR;
5201 case 1002: // SHOW_UPDATES
5202 n = data.readInt32();
5203 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005204 invalidateHwcGeometry();
5205 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005206 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005207 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005208 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005209 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005210 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005211 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005212 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005213 setTransactionFlags(
5214 eTransactionNeeded|
5215 eDisplayTransactionNeeded|
5216 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005217 return NO_ERROR;
5218 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005219 case 1006:{ // send empty update
5220 signalRefresh();
5221 return NO_ERROR;
5222 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005223 case 1008: // toggle use of hw composer
5224 n = data.readInt32();
5225 mDebugDisableHWC = n ? 1 : 0;
5226 invalidateHwcGeometry();
5227 repaintEverything();
5228 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005229 case 1009: // toggle use of transform hint
5230 n = data.readInt32();
5231 mDebugDisableTransformHint = n ? 1 : 0;
5232 invalidateHwcGeometry();
5233 repaintEverything();
5234 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005235 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005236 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005237 reply->writeInt32(0);
5238 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005239 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005240 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005241 return NO_ERROR;
5242 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005243 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005244 if (!display) {
5245 return NAME_NOT_FOUND;
5246 }
5247
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005248 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005249 return NO_ERROR;
5250 }
5251 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005252 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005253 // daltonize
5254 n = data.readInt32();
5255 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005256 case 1:
5257 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5258 break;
5259 case 2:
5260 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5261 break;
5262 case 3:
5263 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5264 break;
5265 default:
5266 mDaltonizer.setType(ColorBlindnessType::None);
5267 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005268 }
5269 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005270 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005271 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005272 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005273 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005274
5275 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005276 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005277 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005278 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005279 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005280 // apply a color matrix
5281 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005282 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005283 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005284 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005285 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005286 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005287 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005288 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005289 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005290 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005291 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005292
5293 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5294 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005295 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005296 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5297 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5298 }
5299
Chia-I Wu28f320b2018-05-03 11:02:56 -07005300 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005301 return NO_ERROR;
5302 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005303 // This is an experimental interface
5304 // Needs to be shifted to proper binder interface when we productize
5305 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005306 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005307 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005308 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005309 return NO_ERROR;
5310 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005311 case 1017: {
5312 n = data.readInt32();
5313 mForceFullDamage = static_cast<bool>(n);
5314 return NO_ERROR;
5315 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005316 case 1018: { // Modify Choreographer's phase offset
5317 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005318 if (mUseScheduler) {
5319 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5320 } else {
5321 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5322 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005323 return NO_ERROR;
5324 }
5325 case 1019: { // Modify SurfaceFlinger's phase offset
5326 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005327 if (mUseScheduler) {
5328 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5329 } else {
5330 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5331 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005332 return NO_ERROR;
5333 }
Irvel468051e2016-06-13 16:44:44 -07005334 case 1020: { // Layer updates interceptor
5335 n = data.readInt32();
5336 if (n) {
5337 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005338 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005339 }
5340 else{
5341 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005342 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005343 }
5344 return NO_ERROR;
5345 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005346 case 1021: { // Disable HWC virtual displays
5347 n = data.readInt32();
5348 mUseHwcVirtualDisplays = !n;
5349 return NO_ERROR;
5350 }
Romain Guy0147a172017-06-01 13:53:56 -07005351 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005352 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005353 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005354
Chia-I Wu28f320b2018-05-03 11:02:56 -07005355 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005356 return NO_ERROR;
5357 }
Romain Guy54f154a2017-10-24 21:40:32 +01005358 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005359 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005360 invalidateHwcGeometry();
5361 repaintEverything();
5362 return NO_ERROR;
5363 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005364 // Deprecate, use 1030 to check whether the device is color managed.
5365 case 1024: {
5366 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005367 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005368 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005369 n = data.readInt32();
5370 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005371 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005372 mTracing.enable();
5373 doTracing("tracing.enable");
5374 reply->writeInt32(NO_ERROR);
5375 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005376 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005377 status_t err = mTracing.disable();
5378 reply->writeInt32(err);
5379 }
5380 return NO_ERROR;
5381 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005382 case 1026: { // Get layer tracing status
5383 reply->writeBool(mTracing.isEnabled());
5384 return NO_ERROR;
5385 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005386 // Is a DisplayColorSetting supported?
5387 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005388 const auto display = getDefaultDisplayDevice();
5389 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005390 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005391 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005392
5393 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5394 switch (setting) {
5395 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005396 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005397 break;
5398 case DisplayColorSetting::UNMANAGED:
5399 reply->writeBool(true);
5400 break;
5401 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005402 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005403 break;
5404 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005405 reply->writeBool(
5406 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005407 break;
5408 }
5409 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005410 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005411 // Is VrFlinger active?
5412 case 1028: {
5413 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005414 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005415 return NO_ERROR;
5416 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005417 // Is device color managed?
5418 case 1030: {
5419 reply->writeBool(useColorManagement);
5420 return NO_ERROR;
5421 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005422 // Override default composition data space
5423 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5424 // && adb shell stop zygote && adb shell start zygote
5425 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5426 // adb shell stop zygote && adb shell start zygote
5427 case 1031: {
5428 Mutex::Autolock _l(mStateLock);
5429 n = data.readInt32();
5430 if (n) {
5431 n = data.readInt32();
5432 if (n) {
5433 Dataspace dataspace = static_cast<Dataspace>(n);
5434 if (!validateCompositionDataspace(dataspace)) {
5435 return BAD_VALUE;
5436 }
5437 mDefaultCompositionDataspace = dataspace;
5438 }
5439 n = data.readInt32();
5440 if (n) {
5441 Dataspace dataspace = static_cast<Dataspace>(n);
5442 if (!validateCompositionDataspace(dataspace)) {
5443 return BAD_VALUE;
5444 }
5445 mWideColorGamutCompositionDataspace = dataspace;
5446 }
5447 } else {
5448 // restore composition data space.
5449 mDefaultCompositionDataspace = defaultCompositionDataspace;
5450 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5451 }
5452 return NO_ERROR;
5453 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005454 }
5455 }
5456 return err;
5457}
5458
Steven Thomas6d8110b2017-08-31 18:24:21 -07005459void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005460 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005461 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005462}
5463
Ana Krulec7d1d6832018-12-27 11:10:09 -08005464void SurfaceFlinger::repaintEverythingForHWC() {
5465 mRepaintEverything = true;
5466 mEventQueue->invalidateForHWC();
5467}
5468
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005469// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5470class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005471public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005472 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5473 ~WindowDisconnector() {
5474 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005475 }
5476
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005477private:
5478 ANativeWindow* mWindow;
5479 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005480};
5481
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005482status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005483 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5484 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005485 uint32_t reqWidth, uint32_t reqHeight,
5486 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005487 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005488 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005489
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005490 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005491
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005492 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5493
Chia-I Wu20261cb2018-08-23 12:55:44 -07005494 sp<DisplayDevice> display;
5495 {
5496 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005497
Chia-I Wu20261cb2018-08-23 12:55:44 -07005498 display = getDisplayDeviceLocked(displayToken);
5499 if (!display) return BAD_VALUE;
5500
Chia-I Wucb023152018-08-28 12:57:23 -07005501 // set the requested width/height to the logical display viewport size
5502 // by default
5503 if (reqWidth == 0 || reqHeight == 0) {
5504 reqWidth = uint32_t(display->getViewport().width());
5505 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005506 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005507 }
5508
Peiyong Lin0e003c92018-09-17 11:09:51 -07005509 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5510 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005511
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005512 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5513 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005514 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5515 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005516}
5517
5518status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005519 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5520 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005521 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005522 ATRACE_CALL();
5523
5524 class LayerRenderArea : public RenderArea {
5525 public:
Robert Carr578038f2018-03-09 12:25:24 -08005526 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005527 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5528 bool childrenOnly)
5529 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005530 mLayer(layer),
5531 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005532 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005533 mFlinger(flinger),
5534 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005535 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005536 Rect getBounds() const override {
5537 const Layer::State& layerState(mLayer->getDrawingState());
5538 return mLayer->getBufferSize(layerState);
5539 }
Marissa Wall61c58622018-07-18 10:12:20 -07005540 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005541 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005542 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005543 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005544 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005545 }
chaviwa76b2712017-09-20 12:02:26 -07005546 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005547 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005548 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005549 Rect getSourceCrop() const override {
5550 if (mCrop.isEmpty()) {
5551 return getBounds();
5552 } else {
5553 return mCrop;
5554 }
5555 }
Robert Carr578038f2018-03-09 12:25:24 -08005556 class ReparentForDrawing {
5557 public:
5558 const sp<Layer>& oldParent;
5559 const sp<Layer>& newParent;
5560
Vishnu Nair4351ad52019-02-11 14:13:02 -08005561 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5562 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005563 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005564 // Compute and cache the bounds for the new parent layer.
5565 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005566 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005567 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08005568 ~ReparentForDrawing() { newParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005569 };
5570
5571 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005572 const Rect sourceCrop = getSourceCrop();
5573 // no need to check rotation because there is none
5574 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5575 sourceCrop.height() != getReqHeight();
5576
Robert Carr578038f2018-03-09 12:25:24 -08005577 if (!mChildrenOnly) {
5578 mTransform = mLayer->getTransform().inverse();
5579 drawLayers();
5580 } else {
5581 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005582 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005583 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5584 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005585
Vishnu Nair4351ad52019-02-11 14:13:02 -08005586 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005587 drawLayers();
5588 }
5589 }
chaviwa76b2712017-09-20 12:02:26 -07005590
chaviwa76b2712017-09-20 12:02:26 -07005591 private:
chaviw7206d492017-11-10 16:16:12 -08005592 const sp<Layer> mLayer;
5593 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005594
5595 // In the "childrenOnly" case we reparent the children to a screenshot
5596 // layer which has no properties set and which does not draw.
5597 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005598 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005599 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005600
5601 SurfaceFlinger* mFlinger;
5602 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005603 };
5604
5605 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5606 auto parent = layerHandle->owner.promote();
5607
Robert Carr2e102c92018-10-23 12:11:15 -07005608 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005609 ALOGE("captureLayers called with a removed parent");
5610 return NAME_NOT_FOUND;
5611 }
5612
Robert Carr578038f2018-03-09 12:25:24 -08005613 const int uid = IPCThreadState::self()->getCallingUid();
5614 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005615 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005616 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5617 return PERMISSION_DENIED;
5618 }
5619
chaviw7206d492017-11-10 16:16:12 -08005620 Rect crop(sourceCrop);
5621 if (sourceCrop.width() <= 0) {
5622 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005623 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005624 }
5625
5626 if (sourceCrop.height() <= 0) {
5627 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005628 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005629 }
5630
5631 int32_t reqWidth = crop.width() * frameScale;
5632 int32_t reqHeight = crop.height() * frameScale;
5633
Chia-I Wu20261cb2018-08-23 12:55:44 -07005634 // really small crop or frameScale
5635 if (reqWidth <= 0) {
5636 reqWidth = 1;
5637 }
5638 if (reqHeight <= 0) {
5639 reqHeight = 1;
5640 }
5641
Peiyong Lin0e003c92018-09-17 11:09:51 -07005642 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005643
Robert Carr578038f2018-03-09 12:25:24 -08005644 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005645 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5646 if (!layer->isVisible()) {
5647 return;
Robert Carr578038f2018-03-09 12:25:24 -08005648 } else if (childrenOnly && layer == parent.get()) {
5649 return;
chaviwa76b2712017-09-20 12:02:26 -07005650 }
5651 visitor(layer);
5652 });
5653 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005654 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005655}
5656
5657status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5658 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005659 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005660 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005661 bool useIdentityTransform) {
5662 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005663
Peiyong Lin0e003c92018-09-17 11:09:51 -07005664 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005665 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5666 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005667 *outBuffer =
5668 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5669 static_cast<android_pixel_format>(reqPixelFormat), 1,
5670 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005671
5672 // This mutex protects syncFd and captureResult for communication of the return values from the
5673 // main thread back to this Binder thread
5674 std::mutex captureMutex;
5675 std::condition_variable captureCondition;
5676 std::unique_lock<std::mutex> captureLock(captureMutex);
5677 int syncFd = -1;
5678 std::optional<status_t> captureResult;
5679
Robert Carr03480e22018-01-04 16:02:06 -08005680 const int uid = IPCThreadState::self()->getCallingUid();
5681 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5682
Dominik Laskowski8c001672018-05-30 16:52:06 -07005683 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005684 // If there is a refresh pending, bug out early and tell the binder thread to try again
5685 // after the refresh.
5686 if (mRefreshPending) {
5687 ATRACE_NAME("Skipping screenshot for now");
5688 std::unique_lock<std::mutex> captureLock(captureMutex);
5689 captureResult = std::make_optional<status_t>(EAGAIN);
5690 captureCondition.notify_one();
5691 return;
5692 }
5693
5694 status_t result = NO_ERROR;
5695 int fd = -1;
5696 {
5697 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005698 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005699 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5700 useIdentityTransform, forSystem, &fd);
5701 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005702 }
5703
5704 {
5705 std::unique_lock<std::mutex> captureLock(captureMutex);
5706 syncFd = fd;
5707 captureResult = std::make_optional<status_t>(result);
5708 captureCondition.notify_one();
5709 }
5710 });
5711
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005712 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005713 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005714 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005715 while (*captureResult == EAGAIN) {
5716 captureResult.reset();
5717 result = postMessageAsync(message);
5718 if (result != NO_ERROR) {
5719 return result;
5720 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005721 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005722 }
5723 result = *captureResult;
5724 }
5725
5726 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005727 sync_wait(syncFd, -1);
5728 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005729 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005730
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005731 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005732}
5733
chaviwa76b2712017-09-20 12:02:26 -07005734void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005735 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005736 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5737 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005738 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005739
chaviwa76b2712017-09-20 12:02:26 -07005740 const auto reqWidth = renderArea.getReqWidth();
5741 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005742 const auto sourceCrop = renderArea.getSourceCrop();
5743 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005744
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005745 renderengine::DisplaySettings clientCompositionDisplay;
5746 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005747
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005748 // assume that bounds are never offset, and that they are the same as the
5749 // buffer bounds.
5750 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5751 ui::Transform transform = renderArea.getTransform();
5752 mat4 m;
5753 m[0][0] = transform[0][0];
5754 m[0][1] = transform[0][1];
5755 m[0][3] = transform[0][2];
5756 m[1][0] = transform[1][0];
5757 m[1][1] = transform[1][1];
5758 m[1][3] = transform[1][2];
5759 m[3][0] = transform[2][0];
5760 m[3][1] = transform[2][1];
5761 m[3][3] = transform[2][2];
Mathias Agopian180f10d2013-04-10 22:55:41 -07005762
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005763 clientCompositionDisplay.globalTransform = m;
5764 mat4 rotMatrix;
5765 // Displacement for repositioning the clipping rectangle after rotating it
5766 // with the rotation hint.
5767 int displacementX = 0;
5768 int displacementY = 0;
5769 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5770 switch (rotation) {
5771 case ui::Transform::ROT_90:
5772 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5773 displacementX = reqWidth;
5774 break;
5775 case ui::Transform::ROT_180:
5776 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5777 displacementX = reqWidth;
5778 displacementY = reqHeight;
5779 break;
5780 case ui::Transform::ROT_270:
5781 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5782 displacementY = reqHeight;
5783 break;
5784 default:
5785 break;
5786 }
5787 // We need to transform the clipping window into the right spot.
5788 // First, rotate the clipping rectangle by the rotation hint to get the
5789 // right orientation
5790 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5791 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5792 const vec4 rotClipTL = rotMatrix * clipTL;
5793 const vec4 rotClipBR = rotMatrix * clipBR;
5794 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5795 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5796 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5797 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5798
5799 // Now reposition the clipping rectangle with the displacement vector
5800 // computed above.
5801 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5802
5803 clientCompositionDisplay.clip =
5804 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5805 newClipRight + displacementX, newClipBottom + displacementY);
5806
5807 // We need to perform the same transformation in layer space, so propagate
5808 // it to the global transform.
5809 mat4 clipTransform = displacementMat * rotMatrix;
5810 clientCompositionDisplay.globalTransform *= clipTransform;
5811 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5812 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005813
chaviw50da5042018-04-09 13:49:37 -07005814 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005815
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005816 renderengine::LayerSettings fillLayer;
5817 fillLayer.source.buffer.buffer = nullptr;
5818 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5819 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5820 fillLayer.alpha = half(alpha);
5821 clientCompositionLayers.push_back(fillLayer);
5822
5823 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005824 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005825 renderengine::LayerSettings layerSettings;
5826 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5827 layerSettings);
5828 if (prepared) {
5829 clientCompositionLayers.push_back(layerSettings);
5830 }
chaviwa76b2712017-09-20 12:02:26 -07005831 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005832
5833 clientCompositionDisplay.clearRegion = clearRegion;
5834 base::unique_fd drawFence;
5835 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5836 &drawFence);
5837
5838 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005839}
5840
chaviwa76b2712017-09-20 12:02:26 -07005841status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5842 TraverseLayersFunction traverseLayers,
5843 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005844 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005845 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005846 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005847 ATRACE_CALL();
5848
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005849 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005850
5851 traverseLayers([&](Layer* layer) {
5852 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5853 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005854
Robert Carr03480e22018-01-04 16:02:06 -08005855 // We allow the system server to take screenshots of secure layers for
5856 // use in situations like the Screen-rotation animation and place
5857 // the impetus on WindowManager to not persist them.
5858 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005859 ALOGW("FB is protected: PERMISSION_DENIED");
5860 return PERMISSION_DENIED;
5861 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005862 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005863 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005864}
5865
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005866// ---------------------------------------------------------------------------
5867
Dan Stoza412903f2017-04-27 13:42:17 -07005868void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5869 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005870}
5871
Dan Stoza412903f2017-04-27 13:42:17 -07005872void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5873 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005874}
5875
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005876void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005877 const LayerVector::Visitor& visitor) {
5878 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005879 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005880 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005881 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005882 continue;
5883 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005884 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005885 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005886 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005887 return;
5888 }
chaviwa76b2712017-09-20 12:02:26 -07005889 if (!layer->isVisible()) {
5890 return;
5891 }
5892 visitor(layer);
5893 });
5894 }
5895}
5896
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005897}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005898
Lloyd Pique074e8122018-07-26 12:57:23 -07005899
Mathias Agopian3f844832013-08-07 21:24:32 -07005900#if defined(__gl_h_)
5901#error "don't include gl/gl.h in this file"
5902#endif
5903
5904#if defined(__gl2_h_)
5905#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005906#endif